@10x-media/analytics 1.0.0-beta.6 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +5 -1
  3. package/dist/adapters/http/fetchJson.js +1 -1
  4. package/dist/adapters/plausible/plausible.d.ts +10 -0
  5. package/dist/adapters/plausible/plausible.js +40 -0
  6. package/dist/adapters/plausible/plausible.js.map +1 -1
  7. package/dist/adapters/posthog/posthog.d.ts +10 -1
  8. package/dist/adapters/posthog/posthog.js +47 -0
  9. package/dist/adapters/posthog/posthog.js.map +1 -1
  10. package/dist/adapters/umami/umami.d.ts +5 -1
  11. package/dist/adapters/umami/umami.js +26 -0
  12. package/dist/adapters/umami/umami.js.map +1 -1
  13. package/dist/capture/getTrackerConfig.d.ts +20 -0
  14. package/dist/capture/getTrackerConfig.js +31 -0
  15. package/dist/capture/getTrackerConfig.js.map +1 -0
  16. package/dist/capture/mountPath.js +14 -0
  17. package/dist/capture/mountPath.js.map +1 -0
  18. package/dist/capture/proxyEndpoint.js +123 -0
  19. package/dist/capture/proxyEndpoint.js.map +1 -0
  20. package/dist/capture/proxyRoutes.js +108 -0
  21. package/dist/capture/proxyRoutes.js.map +1 -0
  22. package/dist/capture/requestBody.js +68 -0
  23. package/dist/capture/requestBody.js.map +1 -0
  24. package/dist/capture/slots.d.ts +8 -0
  25. package/dist/capture/slots.js +43 -0
  26. package/dist/capture/slots.js.map +1 -0
  27. package/dist/capture/trackerConfig.d.ts +32 -0
  28. package/dist/capture/trackerConfig.js +70 -0
  29. package/dist/capture/trackerConfig.js.map +1 -0
  30. package/dist/capture/trackerEndpoint.js +35 -0
  31. package/dist/capture/trackerEndpoint.js.map +1 -0
  32. package/dist/core/capture.d.ts +49 -0
  33. package/dist/core/contract.d.ts +26 -2
  34. package/dist/core/contract.js.map +1 -1
  35. package/dist/core/options.d.ts +97 -2
  36. package/dist/core/options.js +63 -2
  37. package/dist/core/options.js.map +1 -1
  38. package/dist/core/registry.d.ts +1 -0
  39. package/dist/core/scopeList.js +32 -0
  40. package/dist/core/scopeList.js.map +1 -0
  41. package/dist/core/scopedRead.js +13 -6
  42. package/dist/core/scopedRead.js.map +1 -1
  43. package/dist/exports/next.d.ts +2 -1
  44. package/dist/exports/next.js +2 -1
  45. package/dist/exports/react.d.ts +4 -0
  46. package/dist/exports/react.js +5 -0
  47. package/dist/exports/rsc.d.ts +4 -1
  48. package/dist/exports/rsc.js +3 -1
  49. package/dist/exports/tracker.d.ts +18 -0
  50. package/dist/exports/tracker.js +12 -0
  51. package/dist/exports/types.d.ts +5 -2
  52. package/dist/fields/AnalyticsPanelClient.js +1 -1
  53. package/dist/fields/config/narrow.js +2 -0
  54. package/dist/fields/config/narrow.js.map +1 -1
  55. package/dist/fields/readForDocument.js +1 -1
  56. package/dist/goals/match.js +64 -0
  57. package/dist/goals/match.js.map +1 -0
  58. package/dist/goals/types.d.ts +33 -0
  59. package/dist/goals/types.js +7 -0
  60. package/dist/goals/types.js.map +1 -0
  61. package/dist/index.d.ts +4 -3
  62. package/dist/index.js +33 -9
  63. package/dist/index.js.map +1 -1
  64. package/dist/native/collections/events.js +21 -1
  65. package/dist/native/collections/events.js.map +1 -1
  66. package/dist/native/collections/rollups.js +24 -0
  67. package/dist/native/collections/rollups.js.map +1 -1
  68. package/dist/native/geo/maxmindResolver.js +2 -4
  69. package/dist/native/geo/maxmindResolver.js.map +1 -1
  70. package/dist/native/ingest/clientIp.js +15 -0
  71. package/dist/native/ingest/clientIp.js.map +1 -0
  72. package/dist/native/ingest/endpoint.js +40 -4
  73. package/dist/native/ingest/endpoint.js.map +1 -1
  74. package/dist/native/ingest/flushBatch.js +4 -13
  75. package/dist/native/ingest/flushBatch.js.map +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +76 -9
  77. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  78. package/dist/native/nativeAdapter.js +20 -4
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/native/query/eventAgg.js +39 -13
  81. package/dist/native/query/eventAgg.js.map +1 -1
  82. package/dist/native/rollupAcc.js +12 -1
  83. package/dist/native/rollupAcc.js.map +1 -1
  84. package/dist/native/rollups/bumpRollup.js +5 -1
  85. package/dist/native/rollups/bumpRollup.js.map +1 -1
  86. package/dist/native/rollups/deltas.js +28 -6
  87. package/dist/native/rollups/deltas.js.map +1 -1
  88. package/dist/next/captureRewrites.d.ts +41 -0
  89. package/dist/next/captureRewrites.js +56 -0
  90. package/dist/next/captureRewrites.js.map +1 -0
  91. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  92. package/dist/next/posthogProxyRewrites.js +16 -21
  93. package/dist/next/posthogProxyRewrites.js.map +1 -1
  94. package/dist/plugin/documentEndpoint.js +1 -1
  95. package/dist/plugin/paths.js +11 -1
  96. package/dist/plugin/paths.js.map +1 -1
  97. package/dist/plugin/runtime.d.ts +1 -0
  98. package/dist/plugin/runtime.js.map +1 -1
  99. package/dist/plugin/sourcesEndpoint.js +16 -4
  100. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  101. package/dist/plugin/warmTask.js +0 -0
  102. package/dist/plugin/warmTask.js.map +1 -1
  103. package/dist/providers/collection.js +56 -16
  104. package/dist/providers/collection.js.map +1 -1
  105. package/dist/providers/factory.js +8 -2
  106. package/dist/providers/factory.js.map +1 -1
  107. package/dist/react/AnalyticsProvider.d.ts +43 -0
  108. package/dist/react/AnalyticsProvider.js +66 -0
  109. package/dist/react/AnalyticsProvider.js.map +1 -0
  110. package/dist/react/TrackerBoot.d.ts +22 -0
  111. package/dist/react/TrackerBoot.js +30 -0
  112. package/dist/react/TrackerBoot.js.map +1 -0
  113. package/dist/react/useAnalytics.d.ts +17 -0
  114. package/dist/react/useAnalytics.js +36 -0
  115. package/dist/react/useAnalytics.js.map +1 -0
  116. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  117. package/dist/rsc/AnalyticsScripts.js +41 -0
  118. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  119. package/dist/surfacing/cacheStore.d.ts +1 -0
  120. package/dist/surfacing/cacheStore.js +18 -2
  121. package/dist/surfacing/cacheStore.js.map +1 -1
  122. package/dist/surfacing/engine.d.ts +1 -0
  123. package/dist/surfacing/engine.js +44 -4
  124. package/dist/surfacing/engine.js.map +1 -1
  125. package/dist/surfacing/queue.js +22 -6
  126. package/dist/surfacing/queue.js.map +1 -1
  127. package/dist/surfacing/rateLimiter.js +130 -0
  128. package/dist/surfacing/rateLimiter.js.map +1 -0
  129. package/dist/surfacing/retryPolicy.js +15 -0
  130. package/dist/surfacing/retryPolicy.js.map +1 -0
  131. package/dist/sync/syncTask.js +60 -33
  132. package/dist/sync/syncTask.js.map +1 -1
  133. package/dist/testing/memoryAdapter.d.ts +2 -0
  134. package/dist/testing/memoryAdapter.js +10 -0
  135. package/dist/testing/memoryAdapter.js.map +1 -1
  136. package/dist/tracker/autoCapture.d.ts +48 -0
  137. package/dist/tracker/autoCapture.js +129 -0
  138. package/dist/tracker/autoCapture.js.map +1 -0
  139. package/dist/tracker/consent.d.ts +24 -0
  140. package/dist/tracker/consent.js +48 -0
  141. package/dist/tracker/consent.js.map +1 -0
  142. package/dist/tracker/createTracker.d.ts +18 -0
  143. package/dist/tracker/createTracker.js +163 -0
  144. package/dist/tracker/createTracker.js.map +1 -0
  145. package/dist/tracker/initTracker.d.ts +22 -0
  146. package/dist/tracker/initTracker.js +33 -0
  147. package/dist/tracker/initTracker.js.map +1 -0
  148. package/dist/tracker/loadScript.d.ts +14 -0
  149. package/dist/tracker/loadScript.js +41 -0
  150. package/dist/tracker/loadScript.js.map +1 -0
  151. package/dist/tracker/pageTracking.d.ts +17 -0
  152. package/dist/tracker/pageTracking.js +38 -0
  153. package/dist/tracker/pageTracking.js.map +1 -0
  154. package/dist/tracker/registry.d.ts +27 -0
  155. package/dist/tracker/registry.js +73 -0
  156. package/dist/tracker/registry.js.map +1 -0
  157. package/dist/tracker/sinks/native.d.ts +22 -0
  158. package/dist/tracker/sinks/native.js +56 -0
  159. package/dist/tracker/sinks/native.js.map +1 -0
  160. package/dist/tracker/sinks/plausible.d.ts +14 -0
  161. package/dist/tracker/sinks/plausible.js +25 -0
  162. package/dist/tracker/sinks/plausible.js.map +1 -0
  163. package/dist/tracker/sinks/posthog.d.ts +14 -0
  164. package/dist/tracker/sinks/posthog.js +18 -0
  165. package/dist/tracker/sinks/posthog.js.map +1 -0
  166. package/dist/tracker/sinks/umami.d.ts +13 -0
  167. package/dist/tracker/sinks/umami.js +17 -0
  168. package/dist/tracker/sinks/umami.js.map +1 -0
  169. package/dist/tracker/sinks/vendor.d.ts +14 -0
  170. package/dist/tracker/sinks/vendor.js +66 -0
  171. package/dist/tracker/sinks/vendor.js.map +1 -0
  172. package/dist/tracker/transport.js +28 -0
  173. package/dist/tracker/transport.js.map +1 -0
  174. package/dist/tracker/types.d.ts +66 -0
  175. package/dist/translations/ar.js +6 -0
  176. package/dist/translations/ar.js.map +1 -1
  177. package/dist/translations/de.js +6 -0
  178. package/dist/translations/de.js.map +1 -1
  179. package/dist/translations/en.js +6 -0
  180. package/dist/translations/en.js.map +1 -1
  181. package/dist/translations/es.js +6 -0
  182. package/dist/translations/es.js.map +1 -1
  183. package/dist/translations/fr.js +6 -0
  184. package/dist/translations/fr.js.map +1 -1
  185. package/dist/translations/id.js +6 -0
  186. package/dist/translations/id.js.map +1 -1
  187. package/dist/translations/keys.d.ts +6 -0
  188. package/dist/translations/keys.js +6 -0
  189. package/dist/translations/keys.js.map +1 -1
  190. package/dist/translations/ko.js +6 -0
  191. package/dist/translations/ko.js.map +1 -1
  192. package/dist/translations/pt.js +6 -0
  193. package/dist/translations/pt.js.map +1 -1
  194. package/dist/translations/ru.js +6 -0
  195. package/dist/translations/ru.js.map +1 -1
  196. package/dist/translations/uk.js +6 -0
  197. package/dist/translations/uk.js.map +1 -1
  198. package/dist/translations/zh.js +6 -0
  199. package/dist/translations/zh.js.map +1 -1
  200. package/dist/widgets/breakdownTypes.js +5 -0
  201. package/dist/widgets/breakdownTypes.js.map +1 -1
  202. package/dist/widgets/readForWidget.js +24 -14
  203. package/dist/widgets/readForWidget.js.map +1 -1
  204. package/dist/widgets/readForWidgetBreakdown.js +23 -14
  205. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  206. package/dist/widgets/readForWidgetRealtime.js +1 -1
  207. package/dist/widgets/readForWidgetSeries.js +26 -16
  208. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  209. package/dist/widgets/registerWidgets.js +10 -4
  210. package/dist/widgets/registerWidgets.js.map +1 -1
  211. package/dist/widgets/types.js +4 -1
  212. package/dist/widgets/types.js.map +1 -1
  213. package/package.json +21 -6
@@ -0,0 +1,123 @@
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
+ const empty = (status, headers) => new Response(null, {
34
+ status,
35
+ headers
36
+ });
37
+ /**
38
+ * The request path relative to the slot mount, still percent-encoded: path-to-regexp
39
+ * decodes it per segment, so re-encoding here would turn legal path characters
40
+ * (`,=+:@`) into escapes the vendor never sent.
41
+ */
42
+ const subPath = (req, slot) => {
43
+ const pathname = req.pathname ?? (req.url ? new URL(req.url).pathname : "");
44
+ const mount = `${PROXY_PATH}/${slot}`;
45
+ const start = pathname.indexOf(mount);
46
+ if (start === -1) return "/";
47
+ return pathname.slice(start + mount.length) || "/";
48
+ };
49
+ const proxyLimits = (runtime) => ({
50
+ timeoutMs: runtime.captureProxy?.timeoutMs ?? 1e4,
51
+ maxBodyBytes: runtime.captureProxy?.maxBodyBytes ?? 1048576
52
+ });
53
+ /**
54
+ * Public first-party proxy for a slot's vendor tracker: `${PROXY_PATH}/:slot/:path*`,
55
+ * registered for every method Payload routes.
56
+ *
57
+ * The only URLs it ever fetches are compiled from the slot adapter's own
58
+ * `capture.proxy.routes` templates, so an unfilled slot, an adapter without capture, or
59
+ * a path outside the declared routes is a 404 and nothing leaves the server. Credentials
60
+ * (`cookie`, `authorization`) never go upstream and `set-cookie` never comes back; a
61
+ * body over `capture.proxy.maxBodyBytes` is refused with 413 and one that dies in
62
+ * transit with 400, both before anything is forwarded; upstream failures answer 502
63
+ * without echoing the URL or the error.
64
+ */
65
+ const makeProxyHandler = () => async (req) => {
66
+ const method = (req.method ?? "get").toUpperCase();
67
+ if (!SERVED_METHODS.has(method)) return empty(405, { allow: ALLOWED_METHODS });
68
+ if (method === "OPTIONS") return empty(204, { allow: ALLOWED_METHODS });
69
+ const runtime = getRuntime(req.payload);
70
+ const slot = req.routeParams?.slot;
71
+ if (!runtime || typeof slot !== "string" || !isCaptureSlot(slot)) return empty(404);
72
+ const adapter = await resolveSlotAdapter(runtime, req, slot);
73
+ const descriptor = adapter?.capture?.proxy;
74
+ if (!descriptor || descriptor.routes.length === 0) return empty(404);
75
+ const matched = matchProxyRoute(descriptor.routes, subPath(req, slot), { trailingSlashes: descriptor.trailingSlashes });
76
+ if (!matched) return empty(404);
77
+ const { upstreamUrl } = matched;
78
+ const search = req.search ?? (req.url ? new URL(req.url).search : "");
79
+ if (search && search !== "?") {
80
+ const incoming = search.startsWith("?") ? search.slice(1) : search;
81
+ upstreamUrl.search = upstreamUrl.search ? `${upstreamUrl.search}&${incoming}` : `?${incoming}`;
82
+ }
83
+ const limits = proxyLimits(runtime);
84
+ let body;
85
+ if (method === "POST") {
86
+ const read = await readCappedBody(req, limits.maxBodyBytes);
87
+ if (!read.ok) return empty(read.reason === "too-large" ? 413 : 400);
88
+ body = read.body;
89
+ }
90
+ const controller = new AbortController();
91
+ const timer = setTimeout(() => controller.abort(), limits.timeoutMs);
92
+ try {
93
+ const upstream = await fetch(upstreamUrl, {
94
+ method,
95
+ headers: buildUpstreamHeaders(req.headers, clientIpFromHeaders(req.headers), descriptor.forwardHeaders ?? []),
96
+ body,
97
+ redirect: "manual",
98
+ signal: controller.signal
99
+ });
100
+ return new Response(upstream.body, {
101
+ status: upstream.status,
102
+ headers: buildDownstreamHeaders(upstream.headers)
103
+ });
104
+ } catch (err) {
105
+ req.payload?.logger?.warn(`analytics: capture proxy upstream failed for "${adapter?.id}": ${String(err)}`);
106
+ return empty(502);
107
+ } finally {
108
+ clearTimeout(timer);
109
+ }
110
+ };
111
+ /** The six endpoint entries the plugin registers, all sharing one handler. */
112
+ const proxyEndpoints = () => {
113
+ const handler = makeProxyHandler();
114
+ return PROXY_METHODS.map((method) => ({
115
+ method,
116
+ path: PROXY_ENDPOINT_PATH,
117
+ handler
118
+ }));
119
+ };
120
+ //#endregion
121
+ export { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS, proxyEndpoints };
122
+
123
+ //# 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\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),\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;AAEzD,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,OAAO,GAC/B,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,43 @@
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
+ const resolveSlotAdapter = async (runtime, req, slot) => {
18
+ const configured = runtime.captureSlots?.[slot];
19
+ if (configured === false) return null;
20
+ try {
21
+ if (slot === "global") {
22
+ if (configured) return runtime.registry.get(configured);
23
+ if (runtime.platformAdapterId) return runtime.registry.get(runtime.platformAdapterId);
24
+ const all = runtime.registry.all();
25
+ return all.length === 1 ? all[0] : null;
26
+ }
27
+ const scope = await resolveScopeFor(runtime, req);
28
+ if (scope === null) return null;
29
+ const registry = await resolveRegistryFor(runtime, {
30
+ payload: req.payload,
31
+ req,
32
+ scope
33
+ });
34
+ return configured ? registry.get(configured) : registry.default();
35
+ } catch (err) {
36
+ req.payload?.logger?.warn(`analytics: capture slot "${slot}" resolution failed: ${String(err)}`);
37
+ return null;
38
+ }
39
+ };
40
+ //#endregion
41
+ export { CAPTURE_SLOTS, isCaptureSlot, resolveSlotAdapter };
42
+
43
+ //# 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 */\nexport const resolveSlotAdapter = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => {\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 scope = await resolveScopeFor(runtime, req)\n\t\tif (scope === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, { payload: req.payload, req, scope })\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"],"mappings":";;AAOA,MAAa,gBAAwC,CAAC,UAAU,QAAQ;AAExE,MAAa,iBAAiB,UAC5B,cAAoC,SAAS,KAAK;;;;;;;;;;;;;AAcpD,MAAa,qBAAqB,OACjC,SACA,KACA,SACsC;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,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,IAAI,UAAU,MACb,OAAO;EAER,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAAE,SAAS,IAAI;GAAS;GAAK;EAAM,CAAC;EACvF,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"}
@@ -0,0 +1,32 @@
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
+ goals: TrackerGoal[];
27
+ /** Where the native sink posts events, derived from the app's own `routes.api`. */
28
+ ingestPath: string;
29
+ }
30
+ //#endregion
31
+ export { TrackerConfig, TrackerSlotConfig };
32
+ //# sourceMappingURL=trackerConfig.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { INGEST_PATH, PROXY_PATH } from "../plugin/paths.js";
2
+ import { CAPTURE_SLOTS, resolveSlotAdapter } from "./slots.js";
3
+ import { DEFAULT_AUTO_CAPTURE, defaultConsentFor } from "../core/options.js";
4
+ import { normalizeMountPath } from "./mountPath.js";
5
+ //#region src/capture/trackerConfig.ts
6
+ const apiRoute = (req) => req.payload?.config?.routes?.api ?? "/api";
7
+ const trackerGoals = (goals) => (goals ?? []).map(({ slug, match, value, currency }) => ({
8
+ slug,
9
+ match,
10
+ ...value ? { value } : {},
11
+ ...currency ? { currency } : {}
12
+ }));
13
+ /** The config for an install with no runtime yet: no slots, but still a usable ingest path. */
14
+ const emptyTrackerConfig = (req) => ({
15
+ slots: [],
16
+ autoCapture: DEFAULT_AUTO_CAPTURE,
17
+ goals: [],
18
+ ingestPath: `${apiRoute(req)}${INGEST_PATH}`
19
+ });
20
+ /**
21
+ * The per-request tracker config: one entry per capture slot that resolves to an adapter
22
+ * declaring `capture`, in slot order. A slot whose adapter does not resolve (no scope, an
23
+ * unknown id, a throwing scope resolver) is simply absent, as is one whose snippet throws;
24
+ * this runs on a public, unauthenticated path, so every failure degrades a slot away
25
+ * rather than surfacing an error.
26
+ *
27
+ * One adapter fills at most one slot. A scoped install whose tenant registry defaults to
28
+ * the same adapter the global slot names would otherwise hand the tracker two sinks for
29
+ * it and send every event twice; the native adapter in particular resolves its scope from
30
+ * the request, so one sink already covers both. The global slot iterates first and keeps
31
+ * the entry.
32
+ */
33
+ const resolveTrackerConfig = async (args) => {
34
+ const { runtime, req } = args;
35
+ const base = apiRoute(req);
36
+ const slots = [];
37
+ const filled = /* @__PURE__ */ new Set();
38
+ for (const slot of CAPTURE_SLOTS) {
39
+ const adapter = await resolveSlotAdapter(runtime, req, slot);
40
+ const capture = adapter?.capture;
41
+ if (!adapter || !capture || filled.has(adapter.id)) continue;
42
+ const override = runtime.capturePaths?.[slot];
43
+ const path = override ? normalizeMountPath(override) : `${base}${PROXY_PATH}/${slot}`;
44
+ const kind = capture.client.kind;
45
+ try {
46
+ slots.push({
47
+ slot,
48
+ kind,
49
+ adapterId: adapter.id,
50
+ path,
51
+ snippet: capture.snippet({ path }),
52
+ client: capture.client,
53
+ requiresConsent: (runtime.consentFor?.(slot, adapter.id, kind) ?? defaultConsentFor(kind)) === "required"
54
+ });
55
+ filled.add(adapter.id);
56
+ } catch (err) {
57
+ req.payload?.logger?.warn(`analytics: capture snippet for "${adapter.id}" failed, dropping the ${slot} slot: ${String(err)}`);
58
+ }
59
+ }
60
+ return {
61
+ slots,
62
+ autoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,
63
+ goals: trackerGoals(runtime.goals),
64
+ ingestPath: `${base}${runtime.ingestPath ?? "/analytics/ingest"}`
65
+ };
66
+ };
67
+ //#endregion
68
+ export { emptyTrackerConfig, resolveTrackerConfig };
69
+
70
+ //# sourceMappingURL=trackerConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { CaptureClientKind, CaptureSnippet, CaptureSupport } from '../core/capture'\nimport { DEFAULT_AUTO_CAPTURE, defaultConsentFor, type ResolvedAutoCapture } from '../core/options'\nimport type { Goal, TrackerGoal } from '../goals/types'\nimport { INGEST_PATH, PROXY_PATH } from '../plugin/paths'\nimport type { AnalyticsRuntime } from '../plugin/runtime'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, type CaptureSlot, resolveSlotAdapter } from './slots'\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to: the runtime proxy, or a `capture.paths` override. */\n\tpath: string\n\tsnippet: CaptureSnippet\n\tclient: CaptureSupport['client']\n\trequiresConsent: boolean\n}\n\n/**\n * Everything the browser tracker needs, and nothing else. Serialized to any visitor by the\n * public tracker endpoint, so it carries only what an adapter puts in `capture.client` and\n * `capture.snippet`: never a query credential, never a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, derived from the app's own `routes.api`. */\n\tingestPath: string\n}\n\nconst apiRoute = (req: PayloadRequest): string => req.payload?.config?.routes?.api ?? '/api'\n\nconst trackerGoals = (goals: Goal[] | undefined): TrackerGoal[] =>\n\t(goals ?? []).map(({ slug, match, value, currency }) => ({\n\t\tslug,\n\t\tmatch,\n\t\t...(value ? { value } : {}),\n\t\t...(currency ? { currency } : {}),\n\t}))\n\n/** The config for an install with no runtime yet: no slots, but still a usable ingest path. */\nexport const emptyTrackerConfig = (req: PayloadRequest): TrackerConfig => ({\n\tslots: [],\n\tautoCapture: DEFAULT_AUTO_CAPTURE,\n\tgoals: [],\n\tingestPath: `${apiRoute(req)}${INGEST_PATH}`,\n})\n\n/**\n * The per-request tracker config: one entry per capture slot that resolves to an adapter\n * declaring `capture`, in slot order. A slot whose adapter does not resolve (no scope, an\n * unknown id, a throwing scope resolver) is simply absent, as is one whose snippet throws;\n * this runs on a public, unauthenticated path, so every failure degrades a slot away\n * rather than surfacing an error.\n *\n * One adapter fills at most one slot. A scoped install whose tenant registry defaults to\n * the same adapter the global slot names would otherwise hand the tracker two sinks for\n * it and send every event twice; the native adapter in particular resolves its scope from\n * the request, so one sink already covers both. The global slot iterates first and keeps\n * the entry.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n}): Promise<TrackerConfig> => {\n\tconst { runtime, req } = args\n\tconst base = apiRoute(req)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapter(runtime, req, slot)\n\t\tconst capture = adapter?.capture\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override ? normalizeMountPath(override) : `${base}${PROXY_PATH}/${slot}`\n\t\tconst kind = capture.client.kind\n\t\ttry {\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet: capture.snippet({ path }),\n\t\t\t\tclient: capture.client,\n\t\t\t\trequiresConsent:\n\t\t\t\t\t(runtime.consentFor?.(slot, adapter.id, kind) ?? defaultConsentFor(kind)) === 'required',\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(runtime.goals),\n\t\tingestPath: `${base}${runtime.ingestPath ?? INGEST_PATH}`,\n\t}\n}\n"],"mappings":";;;;;AAiCA,MAAM,YAAY,QAAgC,IAAI,SAAS,QAAQ,QAAQ,OAAO;AAEtF,MAAM,gBAAgB,WACpB,SAAS,CAAC,GAAG,KAAK,EAAE,MAAM,OAAO,OAAO,gBAAgB;CACxD;CACA;CACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CACzB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAChC,EAAE;;AAGH,MAAa,sBAAsB,SAAwC;CAC1E,OAAO,CAAC;CACR,aAAa;CACb,OAAO,CAAC;CACR,YAAY,GAAG,SAAS,GAAG,IAAI;AAChC;;;;;;;;;;;;;;AAeA,MAAa,uBAAuB,OAAO,SAGb;CAC7B,MAAM,EAAE,SAAS,QAAQ;CACzB,MAAM,OAAO,SAAS,GAAG;CACzB,MAAM,QAA6B,CAAC;CACpC,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,QAAQ,eAAe;EACjC,MAAM,UAAU,MAAM,mBAAmB,SAAS,KAAK,IAAI;EAC3D,MAAM,UAAU,SAAS;EACzB,IAAI,CAAC,WAAW,CAAC,WAAW,OAAO,IAAI,QAAQ,EAAE,GAChD;EAED,MAAM,WAAW,QAAQ,eAAe;EACxC,MAAM,OAAO,WAAW,mBAAmB,QAAQ,IAAI,GAAG,OAAO,WAAW,GAAG;EAC/E,MAAM,OAAO,QAAQ,OAAO;EAC5B,IAAI;GACH,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA,SAAS,QAAQ,QAAQ,EAAE,KAAK,CAAC;IACjC,QAAQ,QAAQ;IAChB,kBACE,QAAQ,aAAa,MAAM,QAAQ,IAAI,IAAI,KAAK,kBAAkB,IAAI,OAAO;GAChF,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,QAAQ,KAAK;EACjC,YAAY,GAAG,OAAO,QAAQ,cAAA;CAC/B;AACD"}
@@ -0,0 +1,35 @@
1
+ import { TRACKER_PATH } from "../plugin/paths.js";
2
+ import { getRuntime } from "../plugin/runtime.js";
3
+ import { emptyTrackerConfig, resolveTrackerConfig } from "./trackerConfig.js";
4
+ //#region src/capture/trackerEndpoint.ts
5
+ /**
6
+ * Public GET serving the browser tracker its per-request configuration. Like the capture
7
+ * proxy, it runs with no `req.user` and calls the host's `scopeResolver` on behalf of an
8
+ * anonymous visitor: a resolver that throws or resolves nothing leaves the tenant slot
9
+ * absent rather than failing the request, so a broken resolver degrades capture instead of
10
+ * breaking the page.
11
+ *
12
+ * The response is per-visitor and hostname-derived, never shared: `private` with a short
13
+ * max-age, `Vary: Host, Cookie` (a `scopeResolver` may read `req.user` or a tenant cookie,
14
+ * which makes the body cookie-dependent), and no cookie of its own.
15
+ */
16
+ const makeTrackerHandler = () => async (req) => {
17
+ const runtime = getRuntime(req.payload);
18
+ const config = runtime ? await resolveTrackerConfig({
19
+ runtime,
20
+ req
21
+ }) : emptyTrackerConfig(req);
22
+ return Response.json(config, { headers: {
23
+ "cache-control": "private, max-age=60",
24
+ vary: "Host, Cookie"
25
+ } });
26
+ };
27
+ const trackerEndpoint = () => ({
28
+ method: "get",
29
+ path: TRACKER_PATH,
30
+ handler: makeTrackerHandler()
31
+ });
32
+ //#endregion
33
+ export { trackerEndpoint };
34
+
35
+ //# sourceMappingURL=trackerEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trackerEndpoint.js","names":[],"sources":["../../src/capture/trackerEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadHandler } from 'payload'\nimport { TRACKER_PATH } from '../plugin/paths'\nimport { getRuntime } from '../plugin/runtime'\nimport { emptyTrackerConfig, resolveTrackerConfig } from './trackerConfig'\n\nexport { TRACKER_PATH }\n\n/**\n * Public GET serving the browser tracker its per-request configuration. Like the capture\n * proxy, it runs with no `req.user` and calls the host's `scopeResolver` on behalf of an\n * anonymous visitor: a resolver that throws or resolves nothing leaves the tenant slot\n * absent rather than failing the request, so a broken resolver degrades capture instead of\n * breaking the page.\n *\n * The response is per-visitor and hostname-derived, never shared: `private` with a short\n * max-age, `Vary: Host, Cookie` (a `scopeResolver` may read `req.user` or a tenant cookie,\n * which makes the body cookie-dependent), and no cookie of its own.\n */\nexport const makeTrackerHandler = (): PayloadHandler => async (req) => {\n\tconst runtime = getRuntime(req.payload)\n\tconst config = runtime ? await resolveTrackerConfig({ runtime, req }) : emptyTrackerConfig(req)\n\treturn Response.json(config, {\n\t\theaders: { 'cache-control': 'private, max-age=60', vary: 'Host, Cookie' },\n\t})\n}\n\nexport const trackerEndpoint = (): Endpoint => ({\n\tmethod: 'get',\n\tpath: TRACKER_PATH,\n\thandler: makeTrackerHandler(),\n})\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,MAAa,2BAA2C,OAAO,QAAQ;CACtE,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,MAAM,SAAS,UAAU,MAAM,qBAAqB;EAAE;EAAS;CAAI,CAAC,IAAI,mBAAmB,GAAG;CAC9F,OAAO,SAAS,KAAK,QAAQ,EAC5B,SAAS;EAAE,iBAAiB;EAAuB,MAAM;CAAe,EACzE,CAAC;AACF;AAEA,MAAa,yBAAmC;CAC/C,QAAQ;CACR,MAAM;CACN,SAAS,mBAAmB;AAC7B"}
@@ -0,0 +1,49 @@
1
+ //#region src/core/capture.d.ts
2
+ /** One rewrite the runtime proxy endpoint answers, source pattern to vendor upstream. */
3
+ interface ProxyRoute {
4
+ source: string;
5
+ upstream: string;
6
+ }
7
+ /** Routes a Next rewrites helper and the runtime proxy endpoint both consume. */
8
+ interface ProxyDescriptor {
9
+ routes: ProxyRoute[];
10
+ forwardHeaders?: string[];
11
+ /**
12
+ * The vendor serves some paths only with a trailing slash (PostHog's capture
13
+ * endpoints). Both slash forms always match; this decides what reaches the vendor:
14
+ * true keeps the request's trailing slash on the upstream path, absent or false
15
+ * normalizes it away. Next apps proxying such a vendor through rewrites also need
16
+ * `skipTrailingSlashRedirect: true`.
17
+ */
18
+ trailingSlashes?: boolean;
19
+ }
20
+ interface SnippetScript {
21
+ src?: string;
22
+ inline?: string;
23
+ attrs?: Record<string, string>;
24
+ async?: boolean;
25
+ defer?: boolean;
26
+ type?: string;
27
+ }
28
+ interface CaptureSnippet {
29
+ scripts: SnippetScript[];
30
+ }
31
+ type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami';
32
+ /**
33
+ * Pure descriptor of how a vendor's browser tracker is proxied and booted, consumed by
34
+ * a later runtime proxy endpoint, a Next rewrites helper, and a snippet renderer. Never
35
+ * carries private/secret credentials (e.g. PostHog's Query API key); only what the
36
+ * browser is allowed to see.
37
+ */
38
+ interface CaptureSupport {
39
+ proxy: ProxyDescriptor;
40
+ snippet(args: {
41
+ path: string;
42
+ }): CaptureSnippet;
43
+ client: {
44
+ kind: CaptureClientKind;
45
+ } & Record<string, string | number | boolean>;
46
+ }
47
+ //#endregion
48
+ export { CaptureClientKind, CaptureSnippet, CaptureSupport, ProxyDescriptor, ProxyRoute, SnippetScript };
49
+ //# sourceMappingURL=capture.d.ts.map