@10x-media/analytics 1.0.0-beta.16 → 1.0.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/adapters/ga4/ga4.js +33 -2
  3. package/dist/adapters/ga4/ga4.js.map +1 -1
  4. package/dist/adapters/ga4/measurementId.js +4 -1
  5. package/dist/adapters/ga4/measurementId.js.map +1 -1
  6. package/dist/adapters/ga4/propertyId.js +17 -0
  7. package/dist/adapters/ga4/propertyId.js.map +1 -0
  8. package/dist/adapters/http/fetchJson.js +24 -1
  9. package/dist/adapters/http/fetchJson.js.map +1 -1
  10. package/dist/adapters/plausible/plausible.js +16 -1
  11. package/dist/adapters/plausible/plausible.js.map +1 -1
  12. package/dist/adapters/plausible/siteId.js +31 -0
  13. package/dist/adapters/plausible/siteId.js.map +1 -0
  14. package/dist/adapters/posthog/posthog.js +17 -3
  15. package/dist/adapters/posthog/posthog.js.map +1 -1
  16. package/dist/adapters/umami/umami.js +34 -7
  17. package/dist/adapters/umami/umami.js.map +1 -1
  18. package/dist/charts/series.js +1 -1
  19. package/dist/core/contract.d.ts +16 -1
  20. package/dist/core/contract.js.map +1 -1
  21. package/dist/core/options.d.ts +1 -1
  22. package/dist/core/options.js +1 -1
  23. package/dist/core/options.js.map +1 -1
  24. package/dist/core/scopedRead.js +62 -14
  25. package/dist/core/scopedRead.js.map +1 -1
  26. package/dist/core/sourceErrors.js +12 -1
  27. package/dist/core/sourceErrors.js.map +1 -1
  28. package/dist/core/sourceOptions.js +1 -1
  29. package/dist/core/sourceOptions.js.map +1 -1
  30. package/dist/core/sourcePolicy.d.ts +8 -1
  31. package/dist/core/sourcePolicy.js.map +1 -1
  32. package/dist/core/throttle.js +3 -1
  33. package/dist/core/throttle.js.map +1 -1
  34. package/dist/exports/adapters/contract.d.ts +1 -1
  35. package/dist/exports/adapters/ga4.d.ts +2 -2
  36. package/dist/exports/adapters/native.d.ts +2 -2
  37. package/dist/exports/adapters/plausible.d.ts +2 -2
  38. package/dist/exports/adapters/posthog.d.ts +2 -2
  39. package/dist/exports/adapters/umami.d.ts +2 -2
  40. package/dist/exports/client.d.ts +3 -1
  41. package/dist/exports/client.js +3 -1
  42. package/dist/exports/next.d.ts +2 -2
  43. package/dist/exports/testing.d.ts +2 -2
  44. package/dist/exports/types.d.ts +3 -3
  45. package/dist/fields/config/fetchSources.js +1 -1
  46. package/dist/fields/config/fetchSources.js.map +1 -1
  47. package/dist/goals/collection.js +3 -2
  48. package/dist/goals/collection.js.map +1 -1
  49. package/dist/goals/resolver.js +1 -1
  50. package/dist/index.d.ts +4 -3
  51. package/dist/index.js +50 -4
  52. package/dist/index.js.map +1 -1
  53. package/dist/native/geo/maxmindResolver.js +1 -1
  54. package/dist/native/nativeAdapter.js +1 -1
  55. package/dist/plugin/createRuntime.js +57 -13
  56. package/dist/plugin/createRuntime.js.map +1 -1
  57. package/dist/plugin/pluginCollections.js +4 -1
  58. package/dist/plugin/pluginCollections.js.map +1 -1
  59. package/dist/plugin/providerStatusEndpoint.js +80 -0
  60. package/dist/plugin/providerStatusEndpoint.js.map +1 -0
  61. package/dist/plugin/queryEndpoint.js +1 -1
  62. package/dist/plugin/queryEndpoint.js.map +1 -1
  63. package/dist/plugin/readContextForRequest.d.ts +4 -3
  64. package/dist/plugin/readContextForRequest.js +2 -2
  65. package/dist/plugin/readContextForRequest.js.map +1 -1
  66. package/dist/plugin/refreshEndpoint.js +1 -1
  67. package/dist/plugin/routes.d.ts +5 -0
  68. package/dist/plugin/routes.js +1 -0
  69. package/dist/plugin/routes.js.map +1 -1
  70. package/dist/plugin/runtime.js.map +1 -1
  71. package/dist/providers/ProviderConnection.d.ts +12 -0
  72. package/dist/providers/ProviderConnection.js +105 -0
  73. package/dist/providers/ProviderConnection.js.map +1 -0
  74. package/dist/providers/ProviderConnectionTest.d.ts +12 -0
  75. package/dist/providers/ProviderConnectionTest.js +55 -0
  76. package/dist/providers/ProviderConnectionTest.js.map +1 -0
  77. package/dist/providers/ProvidersListNotice.d.ts +1 -1
  78. package/dist/providers/ProvidersListNotice.js +3 -2
  79. package/dist/providers/ProvidersListNotice.js.map +1 -1
  80. package/dist/providers/collection.d.ts +1 -1
  81. package/dist/providers/collection.js +97 -38
  82. package/dist/providers/collection.js.map +1 -1
  83. package/dist/providers/connectionCheck.d.ts +1 -0
  84. package/dist/providers/connectionCheck.js +80 -0
  85. package/dist/providers/connectionCheck.js.map +1 -0
  86. package/dist/providers/connectionState.js +53 -0
  87. package/dist/providers/connectionState.js.map +1 -0
  88. package/dist/providers/factory.d.ts +1 -3
  89. package/dist/providers/factory.js +18 -21
  90. package/dist/providers/factory.js.map +1 -1
  91. package/dist/providers/hosts.js +20 -6
  92. package/dist/providers/hosts.js.map +1 -1
  93. package/dist/providers/ids.d.ts +6 -0
  94. package/dist/providers/ids.js +32 -0
  95. package/dist/providers/ids.js.map +1 -0
  96. package/dist/providers/providerStatusClient.js +60 -0
  97. package/dist/providers/providerStatusClient.js.map +1 -0
  98. package/dist/providers/registry.js +56 -20
  99. package/dist/providers/registry.js.map +1 -1
  100. package/dist/providers/retarget.js +39 -8
  101. package/dist/providers/retarget.js.map +1 -1
  102. package/dist/providers/secrets.d.ts +1 -1
  103. package/dist/providers/secrets.js.map +1 -1
  104. package/dist/providers/status.d.ts +1 -0
  105. package/dist/providers/status.js +181 -0
  106. package/dist/providers/status.js.map +1 -0
  107. package/dist/surfacing/classifyError.js +37 -5
  108. package/dist/surfacing/classifyError.js.map +1 -1
  109. package/dist/surfacing/engine.js +2 -2
  110. package/dist/surfacing/engine.js.map +1 -1
  111. package/dist/surfacing/lanes.js +29 -22
  112. package/dist/surfacing/lanes.js.map +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/testing/settle.d.ts +2 -1
  115. package/dist/testing/settle.js +6 -2
  116. package/dist/testing/settle.js.map +1 -1
  117. package/dist/tracker/sinks/ga4.js +2 -2
  118. package/dist/translations/ar.js +40 -8
  119. package/dist/translations/ar.js.map +1 -1
  120. package/dist/translations/de.js +40 -8
  121. package/dist/translations/de.js.map +1 -1
  122. package/dist/translations/en.js +40 -8
  123. package/dist/translations/en.js.map +1 -1
  124. package/dist/translations/es.js +40 -8
  125. package/dist/translations/es.js.map +1 -1
  126. package/dist/translations/fr.js +40 -8
  127. package/dist/translations/fr.js.map +1 -1
  128. package/dist/translations/id.js +40 -8
  129. package/dist/translations/id.js.map +1 -1
  130. package/dist/translations/keys.d.ts +32 -0
  131. package/dist/translations/keys.js +32 -0
  132. package/dist/translations/keys.js.map +1 -1
  133. package/dist/translations/ko.js +40 -8
  134. package/dist/translations/ko.js.map +1 -1
  135. package/dist/translations/pt.js +40 -8
  136. package/dist/translations/pt.js.map +1 -1
  137. package/dist/translations/ru.js +40 -8
  138. package/dist/translations/ru.js.map +1 -1
  139. package/dist/translations/uk.js +40 -8
  140. package/dist/translations/uk.js.map +1 -1
  141. package/dist/translations/zh.js +40 -8
  142. package/dist/translations/zh.js.map +1 -1
  143. package/dist/ui/analytics.css +63 -0
  144. package/dist/ui/components/SourcesNoticeBanner.js +4 -3
  145. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
  146. package/dist/view/ViewSections.js +9 -2
  147. package/dist/view/ViewSections.js.map +1 -1
  148. package/dist/view/sections/EmptyStates.js +5 -4
  149. package/dist/view/sections/EmptyStates.js.map +1 -1
  150. package/dist/view/sections/OverviewCards.js +6 -2
  151. package/dist/view/sections/OverviewCards.js.map +1 -1
  152. package/dist/view/sections/SourceConnectionNote.js +56 -0
  153. package/dist/view/sections/SourceConnectionNote.js.map +1 -0
  154. package/dist/view/viewProps.d.ts +2 -0
  155. package/dist/view/viewProps.js +2 -1
  156. package/dist/view/viewProps.js.map +1 -1
  157. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connectionState.js","names":[],"sources":["../../src/providers/connectionState.ts"],"sourcesContent":["import { isRecord } from '../core/values'\nimport type { ReadFailureKind } from '../surfacing/classifyError'\nimport { PROVIDER_IDS, type ProviderId } from './ids'\n\n/**\n * Why a check was refused, when the plugin knows: `incomplete`, the document lacks a key or an ID\n * the check needs; `unknownSite`, the vendor does not know the site ID (self-hosted Umami).\n */\nexport type ConnectionFailureReason = 'incomplete' | 'unknownSite'\n\nconst CONNECTION_FAILURE_REASONS: readonly ConnectionFailureReason[] = ['incomplete', 'unknownSite']\n\n/** A stored reason as the type it names, or undefined for any other value. */\nexport const connectionFailureReasonOf = (value: unknown): ConnectionFailureReason | undefined =>\n\tCONNECTION_FAILURE_REASONS.find((reason) => reason === value)\n\n/** One provider document's status row, its dates as ISO strings. */\nexport interface ProviderStatus {\n\tlastSuccessAt?: string\n\tlastErrorAt?: string\n\terrorKind?: ReadFailureKind\n\t/** Why the last failure happened, when the plugin knows. */\n\terrorReason?: ConnectionFailureReason\n\terrorDetail?: string\n\tpausedUntil?: string\n}\n\n/** What one read or check told about a document's connection. */\nexport type ConnectionOutcome =\n\t| { ok: true }\n\t| {\n\t\t\tok: false\n\t\t\tkind: ReadFailureKind\n\t\t\treason?: ConnectionFailureReason\n\t\t\t/** The vendor's own words. */\n\t\t\tdetail?: string\n\t\t\t/** How long the source rests from now, when it does. */\n\t\t\tpausedForMs?: number\n\t }\n\n/** What the provider status endpoint answers. */\nexport interface ProviderStatusResponse {\n\t/** The document's row, empty until a read or a check wrote one. */\n\tstatus: ProviderStatus\n\t/** What the check this POST ran found; absent on a GET and on a debounced POST. */\n\tchecked?: ConnectionOutcome\n}\n\n/** What a document's connection last came to, as its form shows it. */\nexport type ConnectionState = 'works' | 'refused' | 'unreachable' | 'unchecked'\n\nconst timeOf = (iso: string | undefined): number | undefined => {\n\tconst at = iso === undefined ? Number.NaN : Date.parse(iso)\n\treturn Number.isNaN(at) ? undefined : at\n}\n\n/** The later of the last success and the last failure decides; neither yet is unchecked. */\nexport const connectionStateOf = (status: ProviderStatus): ConnectionState => {\n\tconst success = timeOf(status.lastSuccessAt)\n\tconst failure = timeOf(status.lastErrorAt)\n\tif (failure !== undefined && (success === undefined || failure > success)) {\n\t\treturn status.errorKind === 'unavailable' ? 'unreachable' : 'refused'\n\t}\n\treturn success === undefined ? 'unchecked' : 'works'\n}\n\n/**\n * Whether a document's source counts as failing, for a `fallback` policy to stand in for it:\n * refused until a read or a check works again, unreachable only while its reads rest, so one slow\n * answer moves no one off their own numbers.\n */\nexport const isFailingConnection = (status: ProviderStatus, now: number): boolean => {\n\tconst state = connectionStateOf(status)\n\treturn state === 'refused' || (state === 'unreachable' && (timeOf(status.pausedUntil) ?? 0) > now)\n}\n\nconst isOptionalString = (value: unknown): boolean =>\n\tvalue === undefined || typeof value === 'string'\n\n/** Whether a body is the endpoint's answer; the fields the form reads are checked, the rest kept. */\nexport const isProviderStatusResponse = (value: unknown): value is ProviderStatusResponse =>\n\tisRecord(value) &&\n\tisRecord(value.status) &&\n\t['lastSuccessAt', 'lastErrorAt', 'errorKind', 'errorReason', 'errorDetail', 'pausedUntil'].every(\n\t\t(key) => isOptionalString(isRecord(value.status) ? value.status[key] : undefined)\n\t) &&\n\t(value.checked === undefined ||\n\t\t(isRecord(value.checked) && typeof value.checked.ok === 'boolean'))\n\n/** A stored vendor answer as a reader reads it: who said it and what; the HTTP status stays in the logs. */\nexport interface VendorWords {\n\tprovider?: ProviderId\n\tmessage: string\n}\n\n/**\n * `posthog: HTTP 403 Bad key`, as `fetchJson` words a refusal, into its parts; any other text is\n * the message as it is.\n */\nexport const vendorWordsOf = (detail: string): VendorWords => {\n\tconst match = /^([a-z0-9]+): HTTP (\\d{3})\\s*([\\s\\S]*)$/.exec(detail)\n\tconst provider = PROVIDER_IDS.find((id) => id === match?.[1])\n\tif (!match || !provider) {\n\t\treturn { message: detail.trim() }\n\t}\n\treturn { provider, message: (match[3] ?? '').trim() }\n}\n"],"mappings":";;;AAUA,MAAM,6BAAiE,CAAC,cAAc,aAAa;;AAGnG,MAAa,6BAA6B,UACzC,2BAA2B,MAAM,W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} from "./hosts.js";
5
5
 
6
6
  //#region src/providers/factory.d.ts
7
- type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog';
8
- declare const PROVIDER_IDS: readonly ["native", "plausible", "umami", "ga4", "posthog"];
9
7
  /** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */
10
8
  type ProviderDoc = {
11
9
  id?: number | string;
@@ -80,5 +78,5 @@ interface ProviderFactoryContext {
80
78
  */
81
79
  declare const adapterFromProviderDoc: (doc: ProviderDoc, ctx: ProviderFactoryContext) => AnalyticsAdapter | null;
82
80
  //#endregion
83
- export { PROVIDER_IDS, ProviderDoc, ProviderFactoryContext, ProviderId, adapterFromProviderDoc };
81
+ export { ProviderDoc, ProviderFactoryContext, adapterFromProviderDoc };
84
82
  //# sourceMappingURL=factory.d.ts.map
@@ -1,22 +1,18 @@
1
1
  import { isOneOf, isRecord } from "../core/values.js";
2
2
  import { HostRefusedError } from "../core/sourceErrors.js";
3
+ import { documentAdapterId } from "./ids.js";
3
4
  import { withFixedLabel } from "../core/sourceLabel.js";
4
5
  import { WITHOUT_CONSENT_LEVELS } from "../capture/withoutConsent.js";
6
+ import { checkDocumentHost } from "./hosts.js";
5
7
  import { ga4 } from "../adapters/ga4/ga4.js";
6
8
  import { plausible } from "../adapters/plausible/plausible.js";
7
9
  import { posthog } from "../adapters/posthog/posthog.js";
8
10
  import { umami } from "../adapters/umami/umami.js";
9
- import { checkDocumentHost } from "./hosts.js";
10
11
  //#region src/providers/factory.ts
11
- const PROVIDER_IDS = [
12
- "native",
13
- "plausible",
14
- "umami",
15
- "ga4",
16
- "posthog"
17
- ];
12
+ /** A stored text value without the spaces a paste can leave around it. */
13
+ const trimmed = (value) => value?.trim() ?? "";
18
14
  /** A stored blank reads as unset. */
19
- const orUndefined = (value) => value || void 0;
15
+ const orUndefined = (value) => trimmed(value) || void 0;
20
16
  /** An unset or unrecognized stored level follows `capture.withoutConsent`. */
21
17
  const documentWithoutConsent = (value) => isOneOf(WITHOUT_CONSENT_LEVELS, value) ? value : void 0;
22
18
  /** An unset or unrecognized stored region falls back to host-derived detection. */
@@ -27,8 +23,6 @@ const posthogRegion = (value) => value === "us" || value === "eu" ? value : void
27
23
  */
28
24
  const normalizePrivateKey = (key) => key.replace(/\\n/g, "\n");
29
25
  const shortId = (id) => String(id).slice(-6);
30
- /** The registry id of a provider document's adapter, which grants and stand-ins must match. */
31
- const documentAdapterId = (provider, id) => `${String(provider)}:${String(id)}`;
32
26
  /** A lent `native` adapter under the document's name, so a source reads as its tenant named it. */
33
27
  const withDocumentLabel = (adapter, doc) => doc.name ? withFixedLabel(adapter, doc.name) : adapter;
34
28
  /** Per-document ids keep two projects of one provider type apart in a registry. */
@@ -53,6 +47,9 @@ const failingAdapter = (shape, error) => {
53
47
  capabilities: shape.capabilities,
54
48
  isConfigured: shape.isConfigured ?? (() => true),
55
49
  query: fail,
50
+ checkConnection: async () => {
51
+ throw error();
52
+ },
56
53
  ...shape.realtime ? { realtime: fail } : {}
57
54
  };
58
55
  };
@@ -73,10 +70,10 @@ const buildBaseAdapter = (doc, ctx) => {
73
70
  case "plausible": {
74
71
  const cfg = doc.plausible ?? {};
75
72
  return onDocumentHost(checkDocumentHost("plausible", cfg.host, ctx.hosts), (host) => plausible({
76
- siteId: cfg.siteId ?? "",
77
- apiKey: cfg.apiKey ?? "",
73
+ siteId: trimmed(cfg.siteId),
74
+ apiKey: trimmed(cfg.apiKey),
78
75
  host,
79
- domain: orUndefined(cfg.domain),
76
+ domain: orUndefined(cfg.domain && [...new Set(cfg.domain.split(",").map((site) => site.trim()))].join(",")),
80
77
  scriptId: orUndefined(cfg.scriptId),
81
78
  revenueCurrency: orUndefined(cfg.revenueCurrency),
82
79
  fetch: ctx.fetch,
@@ -86,7 +83,7 @@ const buildBaseAdapter = (doc, ctx) => {
86
83
  case "umami": {
87
84
  const cfg = doc.umami ?? {};
88
85
  return onDocumentHost(checkDocumentHost("umami", cfg.host, ctx.hosts), (host) => umami({
89
- websiteId: cfg.websiteId ?? "",
86
+ websiteId: trimmed(cfg.websiteId),
90
87
  apiKey: orUndefined(cfg.apiKey),
91
88
  token: orUndefined(cfg.token),
92
89
  host,
@@ -97,9 +94,9 @@ const buildBaseAdapter = (doc, ctx) => {
97
94
  case "ga4": {
98
95
  const cfg = doc.ga4 ?? {};
99
96
  return ga4({
100
- propertyId: cfg.propertyId ?? "",
97
+ propertyId: trimmed(cfg.propertyId),
101
98
  credentials: {
102
- client_email: cfg.clientEmail ?? "",
99
+ client_email: trimmed(cfg.clientEmail),
103
100
  private_key: normalizePrivateKey(cfg.privateKey ?? "")
104
101
  },
105
102
  projectId: orUndefined(cfg.projectId),
@@ -112,12 +109,12 @@ const buildBaseAdapter = (doc, ctx) => {
112
109
  case "posthog": {
113
110
  const cfg = doc.posthog ?? {};
114
111
  return onDocumentHost(checkDocumentHost("posthog", cfg.host, ctx.hosts), (host) => posthog({
115
- projectId: cfg.projectId ?? "",
116
- apiKey: cfg.apiKey ?? "",
112
+ projectId: trimmed(cfg.projectId),
113
+ apiKey: trimmed(cfg.apiKey),
117
114
  host,
118
115
  projectToken: orUndefined(cfg.projectToken),
119
116
  region: posthogRegion(cfg.region),
120
- scopeProperty: orUndefined(cfg.scopeProperty?.trim()),
117
+ scopeProperty: orUndefined(cfg.scopeProperty),
121
118
  fetch: ctx.fetch,
122
119
  ...consent
123
120
  }));
@@ -138,6 +135,6 @@ const adapterFromProviderDoc = (doc, ctx) => {
138
135
  return doc.provider === "native" ? withDocumentLabel(base, doc) : withInstanceIdentity(base, doc);
139
136
  };
140
137
  //#endregion
141
- export { PROVIDER_IDS, adapterFromProviderDoc, documentAdapterId, failingAdapter };
138
+ export { adapterFromProviderDoc, failingAdapter };
142
139
 
143
140
  //# sourceMappingURL=factory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport { WITHOUT_CONSENT_LEVELS } from '../capture/withoutConsent'\nimport type { AnalyticsAdapter, AnalyticsResult } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { HostRefusedError } from '../core/sourceErrors'\nimport { withFixedLabel } from '../core/sourceLabel'\nimport { isOneOf, isRecord } from '../core/values'\nimport type { WithoutConsentLevel } from '../tracker/config'\nimport { checkDocumentHost, type DocumentHost, type ProviderHostPolicy } from './hosts'\n\nexport type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog'\nexport const PROVIDER_IDS = [\n\t'native',\n\t'plausible',\n\t'umami',\n\t'ga4',\n\t'posthog',\n] as const satisfies readonly ProviderId[]\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\t/** A vendor document's own level without consent; unset or blank follows the install. */\n\twithoutConsent?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t\trevenueCurrency?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t\tmeasurementId?: string | null\n\t\tcurrency?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t\tscopeProperty?: string | null\n\t} | null\n}\n\n/** A stored blank reads as unset. */\nconst orUndefined = (value: string | null | undefined): string | undefined => value || undefined\n\n/** An unset or unrecognized stored level follows `capture.withoutConsent`. */\nconst documentWithoutConsent = (\n\tvalue: string | null | undefined\n): WithoutConsentLevel | undefined => (isOneOf(WITHOUT_CONSENT_LEVELS, value) ? value : undefined)\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** The registry id of a provider document's adapter, which grants and stand-ins must match. */\nexport const documentAdapterId = (provider: unknown, id: unknown): string =>\n\t`${String(provider)}:${String(id)}`\n\n/** A lent `native` adapter under the document's name, so a source reads as its tenant named it. */\nconst withDocumentLabel = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter =>\n\tdoc.name ? withFixedLabel(adapter, doc.name) : adapter\n\n/** Per-document ids keep two projects of one provider type apart in a registry. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...withFixedLabel(adapter, doc.name || `${adapter.label} ${shortId(doc.id)}`),\n\t\tid: documentAdapterId(doc.provider, doc.id),\n\t}\n}\n\n/**\n * Keeps `shape`'s identity, capabilities and `isConfigured` (configured when absent) so the source\n * still lists, but every read throws `error()` and it declares no capture, so its proxy mount 404s.\n */\nexport const failingAdapter = (\n\tshape: Pick<AnalyticsAdapter, 'id' | 'label' | 'capabilities' | 'realtime'> &\n\t\tPartial<Pick<AnalyticsAdapter, 'isConfigured'>>,\n\terror: () => Error\n): AnalyticsAdapter => {\n\tconst fail = async (): Promise<AnalyticsResult> => {\n\t\tthrow error()\n\t}\n\treturn {\n\t\tid: shape.id,\n\t\tlabel: shape.label,\n\t\tcapabilities: shape.capabilities,\n\t\tisConfigured: shape.isConfigured ?? (() => true),\n\t\tquery: fail,\n\t\t...(shape.realtime ? { realtime: fail } : {}),\n\t}\n}\n\n/**\n * Builds a hosted vendor's adapter on the address its host check allowed, none being the vendor's\n * cloud; a refused host builds one whose reads fail with a `HostRefusedError`.\n */\nconst onDocumentHost = (\n\tverdict: DocumentHost,\n\tbuild: (host: string | undefined) => AnalyticsAdapter\n): AnalyticsAdapter => {\n\tif (verdict.ok) {\n\t\treturn build(verdict.address ?? undefined)\n\t}\n\tconst { host, reason } = verdict\n\treturn failingAdapter(build(undefined), () => new HostRefusedError(host, reason))\n}\n\nconst buildBaseAdapter = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\t// Saying off where the slot would resolve off anyway keeps the adapter from acting (or warning)\n\t// as if it might count without consent.\n\tconst withoutConsent =\n\t\tctx.heldWithoutConsent === false\n\t\t\t? 'off'\n\t\t\t: (documentWithoutConsent(doc.withoutConsent) ??\n\t\t\t\t(ctx.followingCountsWithoutConsent === false ? 'off' : undefined))\n\tconst consent = withoutConsent ? { withoutConsent } : {}\n\tswitch (doc.provider) {\n\t\tcase 'native':\n\t\t\treturn ctx.native ?? null\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('plausible', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tplausible({\n\t\t\t\t\tsiteId: cfg.siteId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tdomain: orUndefined(cfg.domain),\n\t\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t\t\trevenueCurrency: orUndefined(cfg.revenueCurrency),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('umami', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tumami({\n\t\t\t\t\twebsiteId: cfg.websiteId ?? '',\n\t\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\t\thost,\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: cfg.propertyId ?? '',\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: cfg.clientEmail ?? '',\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t\tmeasurementId: orUndefined(cfg.measurementId),\n\t\t\t\tcurrency: orUndefined(cfg.currency),\n\t\t\t\t...(ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {}),\n\t\t\t\t...consent,\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('posthog', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tposthog({\n\t\t\t\t\tprojectId: cfg.projectId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t\t\tscopeProperty: orUndefined(cfg.scopeProperty?.trim()),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * What the factory needs to build a document's adapter: `fetch` and `hosts` keep a stored key on a\n * host the install allows.\n *\n * @beta\n */\nexport interface ProviderFactoryContext {\n\t/** The guarded fetch `providers.resolve` receives, or one from `createGuardedFetch`. */\n\tfetch: FetchLike\n\t/**\n\t * The policy `providers.resolve` receives, or one from `resolveHostPolicy`: a host outside it\n\t * builds an adapter that reads as `source_misconfigured` and captures nothing.\n\t */\n\thosts: ProviderHostPolicy\n\t/**\n\t * The install's config native adapter, which a `native` document grants rather than building a\n\t * second one.\n\t */\n\tnative?: AnalyticsAdapter\n\t/** The plugin's `sdks`: a GA4 document's adapter reads through `sdks.ga4`. */\n\tsdks?: AnalyticsSdks\n\t/**\n\t * False when no slot `capture.gate` holds can fall to a document's adapter: it is then off\n\t * without consent, whatever the document says.\n\t */\n\theldWithoutConsent?: boolean\n\t/** False when `capture.withoutConsent` is `'off'` in both phases: a document following it is off. */\n\tfollowingCountsWithoutConsent?: boolean\n}\n\n/** Checked at runtime: a JavaScript caller can leave the guards out, which would go out unguarded. */\nconst isGuarded = (ctx: unknown): ctx is ProviderFactoryContext =>\n\tisRecord(ctx) &&\n\ttypeof ctx.fetch === 'function' &&\n\tisRecord(ctx.hosts) &&\n\tArray.isArray(ctx.hosts.allow)\n\n/**\n * Builds a provider document's adapter: missing credentials read as `isConfigured() === false`, an\n * unknown provider as null, and a `native` document lends the config adapter under its label.\n */\nexport const adapterFromProviderDoc = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\tif (!isGuarded(ctx)) {\n\t\tthrow new Error(\n\t\t\t'analytics: adapterFromProviderDoc needs { fetch, hosts }: pass the ones providers.resolve receives'\n\t\t)\n\t}\n\tconst base = buildBaseAdapter(doc, ctx)\n\tif (!base) {\n\t\treturn null\n\t}\n\treturn doc.provider === 'native' ? withDocumentLabel(base, doc) : withInstanceIdentity(base, doc)\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAa,eAAe;CAC3B;CACA;CACA;CACA;CACA;AACD;;AA4CA,MAAM,eAAe,UAAyD,SAAS,KAAA;;AA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K,IAAI,SACzE,QAAQ;IACP,WAAW,IAAI,aAAa;IAC5B,QAAQ,IAAI,UAAU;IACtB;IACA,cAAc,YAAY,IAAI,YAAY;IAC1C,QAAQ,cAAc,IAAI,MAAM;IAChC,eAAe,YAAY,IAAI,eAAe,KAAK,CAAC;IACpD,OAAO,IAAI;IACX,GAAG;GACJ,CAAC,CACF;EACD;EACA,SACC,OAAO;CACT;AACD;;AAiCA,MAAM,aAAa,QAClB,SAAS,GAAG,KACZ,OAAO,IAAI,UAAU,cACrB,SAAS,IAAI,KAAK,KAClB,MAAM,QAAQ,IAAI,MAAM,KAAK;;;;;AAM9B,MAAa,0BACZ,KACA,QAC6B;CAC7B,IAAI,CAAC,UAAU,GAAG,GACjB,MAAM,IAAI,MACT,oGACD;CAED,MAAM,OAAO,iBAAiB,KAAK,GAAG;CACtC,IAAI,CAAC,MACJ,OAAO;CAER,OAAO,IAAI,aAAa,WAAW,kBAAkB,MAAM,GAAG,IAAI,qBAAqB,MAAM,GAAG;AACjG"}
1
+ {"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport { WITHOUT_CONSENT_LEVELS } from '../capture/withoutConsent'\nimport type { AnalyticsAdapter, AnalyticsResult } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { HostRefusedError } from '../core/sourceErrors'\nimport { withFixedLabel } from '../core/sourceLabel'\nimport { isOneOf, isRecord } from '../core/values'\nimport type { WithoutConsentLevel } from '../tracker/config'\nimport { checkDocumentHost, type DocumentHost, type ProviderHostPolicy } from './hosts'\nimport { documentAdapterId } from './ids'\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\t/** A vendor document's own level without consent; unset or blank follows the install. */\n\twithoutConsent?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t\trevenueCurrency?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t\tmeasurementId?: string | null\n\t\tcurrency?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t\tscopeProperty?: string | null\n\t} | null\n}\n\n/** A stored text value without the spaces a paste can leave around it. */\nconst trimmed = (value: string | null | undefined): string => value?.trim() ?? ''\n\n/** A stored blank reads as unset. */\nconst orUndefined = (value: string | null | undefined): string | undefined =>\n\ttrimmed(value) || undefined\n\n/** An unset or unrecognized stored level follows `capture.withoutConsent`. */\nconst documentWithoutConsent = (\n\tvalue: string | null | undefined\n): WithoutConsentLevel | undefined => (isOneOf(WITHOUT_CONSENT_LEVELS, value) ? value : undefined)\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** A lent `native` adapter under the document's name, so a source reads as its tenant named it. */\nconst withDocumentLabel = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter =>\n\tdoc.name ? withFixedLabel(adapter, doc.name) : adapter\n\n/** Per-document ids keep two projects of one provider type apart in a registry. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...withFixedLabel(adapter, doc.name || `${adapter.label} ${shortId(doc.id)}`),\n\t\tid: documentAdapterId(doc.provider, doc.id),\n\t}\n}\n\n/**\n * Keeps `shape`'s identity, capabilities and `isConfigured` (configured when absent) so the source\n * still lists, but every read throws `error()` and it declares no capture, so its proxy mount 404s.\n */\nexport const failingAdapter = (\n\tshape: Pick<AnalyticsAdapter, 'id' | 'label' | 'capabilities' | 'realtime'> &\n\t\tPartial<Pick<AnalyticsAdapter, 'isConfigured'>>,\n\terror: () => Error\n): AnalyticsAdapter => {\n\tconst fail = async (): Promise<AnalyticsResult> => {\n\t\tthrow error()\n\t}\n\treturn {\n\t\tid: shape.id,\n\t\tlabel: shape.label,\n\t\tcapabilities: shape.capabilities,\n\t\tisConfigured: shape.isConfigured ?? (() => true),\n\t\tquery: fail,\n\t\t// So Test connection says why, as a read would, rather than that there is nothing to check.\n\t\tcheckConnection: async () => {\n\t\t\tthrow error()\n\t\t},\n\t\t...(shape.realtime ? { realtime: fail } : {}),\n\t}\n}\n\n/**\n * Builds a hosted vendor's adapter on the address its host check allowed, none being the vendor's\n * cloud; a refused host builds one whose reads fail with a `HostRefusedError`.\n */\nconst onDocumentHost = (\n\tverdict: DocumentHost,\n\tbuild: (host: string | undefined) => AnalyticsAdapter\n): AnalyticsAdapter => {\n\tif (verdict.ok) {\n\t\treturn build(verdict.address ?? undefined)\n\t}\n\tconst { host, reason } = verdict\n\treturn failingAdapter(build(undefined), () => new HostRefusedError(host, reason))\n}\n\nconst buildBaseAdapter = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\t// Saying off where the slot would resolve off anyway keeps the adapter from acting (or warning)\n\t// as if it might count without consent.\n\tconst withoutConsent =\n\t\tctx.heldWithoutConsent === false\n\t\t\t? 'off'\n\t\t\t: (documentWithoutConsent(doc.withoutConsent) ??\n\t\t\t\t(ctx.followingCountsWithoutConsent === false ? 'off' : undefined))\n\tconst consent = withoutConsent ? { withoutConsent } : {}\n\tswitch (doc.provider) {\n\t\tcase 'native':\n\t\t\treturn ctx.native ?? null\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('plausible', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tplausible({\n\t\t\t\t\tsiteId: trimmed(cfg.siteId),\n\t\t\t\t\tapiKey: trimmed(cfg.apiKey),\n\t\t\t\t\thost,\n\t\t\t\t\tdomain: orUndefined(\n\t\t\t\t\t\tcfg.domain && [...new Set(cfg.domain.split(',').map((site) => site.trim()))].join(',')\n\t\t\t\t\t),\n\t\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t\t\trevenueCurrency: orUndefined(cfg.revenueCurrency),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('umami', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tumami({\n\t\t\t\t\twebsiteId: trimmed(cfg.websiteId),\n\t\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\t\thost,\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: trimmed(cfg.propertyId),\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: trimmed(cfg.clientEmail),\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t\tmeasurementId: orUndefined(cfg.measurementId),\n\t\t\t\tcurrency: orUndefined(cfg.currency),\n\t\t\t\t...(ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {}),\n\t\t\t\t...consent,\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('posthog', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tposthog({\n\t\t\t\t\tprojectId: trimmed(cfg.projectId),\n\t\t\t\t\tapiKey: trimmed(cfg.apiKey),\n\t\t\t\t\thost,\n\t\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t\t\tscopeProperty: orUndefined(cfg.scopeProperty),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * What the factory needs to build a document's adapter: `fetch` and `hosts` keep a stored key on a\n * host the install allows.\n *\n * @beta\n */\nexport interface ProviderFactoryContext {\n\t/** The guarded fetch `providers.resolve` receives, or one from `createGuardedFetch`. */\n\tfetch: FetchLike\n\t/**\n\t * The policy `providers.resolve` receives, or one from `resolveHostPolicy`: a host outside it\n\t * builds an adapter that reads as `source_misconfigured` and captures nothing.\n\t */\n\thosts: ProviderHostPolicy\n\t/**\n\t * The install's config native adapter, which a `native` document grants rather than building a\n\t * second one.\n\t */\n\tnative?: AnalyticsAdapter\n\t/** The plugin's `sdks`: a GA4 document's adapter reads through `sdks.ga4`. */\n\tsdks?: AnalyticsSdks\n\t/**\n\t * False when no slot `capture.gate` holds can fall to a document's adapter: it is then off\n\t * without consent, whatever the document says.\n\t */\n\theldWithoutConsent?: boolean\n\t/** False when `capture.withoutConsent` is `'off'` in both phases: a document following it is off. */\n\tfollowingCountsWithoutConsent?: boolean\n}\n\n/** Checked at runtime: a JavaScript caller can leave the guards out, which would go out unguarded. */\nconst isGuarded = (ctx: unknown): ctx is ProviderFactoryContext =>\n\tisRecord(ctx) &&\n\ttypeof ctx.fetch === 'function' &&\n\tisRecord(ctx.hosts) &&\n\tArray.isArray(ctx.hosts.allow)\n\n/**\n * Builds a provider document's adapter: missing credentials read as `isConfigured() === false`, an\n * unknown provider as null, and a `native` document lends the config adapter under its label.\n */\nexport const adapterFromProviderDoc = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\tif (!isGuarded(ctx)) {\n\t\tthrow new Error(\n\t\t\t'analytics: adapterFromProviderDoc needs { fetch, hosts }: pass the ones providers.resolve receives'\n\t\t)\n\t}\n\tconst base = buildBaseAdapter(doc, ctx)\n\tif (!base) {\n\t\treturn null\n\t}\n\treturn doc.provider === 'native' ? withDocumentLabel(base, doc) : withInstanceIdentity(base, doc)\n}\n"],"mappings":";;;;;;;;;;;;AAyDA,MAAM,WAAW,UAA6C,OAAO,KAAK,KAAK;;AAG/E,MAAM,eAAe,UACpB,QAAQ,KAAK,KAAK,KAAA;;AAGnB,MAAM,0BACL,UACsC,QAAQ,wBAAwB,KAAK,IAAI,QAAQ,KAAA;;AAGxF,MAAM,iBAAiB,UACtB,UAAU,QAAQ,UAAU,OAAO,QAAQ,KAAA;;;;;AAM5C,MAAa,uBAAuB,QAAwB,IAAI,QAAQ,QAAQ,IAAI;AAEpF,MAAM,WAAW,OAAgC,OAAO,EAAE,EAAE,MAAM,EAAE;;AAGpE,MAAM,qBAAqB,SAA2B,QACrD,IAAI,OAAO,eAAe,SAAS,IAAI,IAAI,IAAI;;AAGhD,MAAM,wBAAwB,SAA2B,QAAuC;CAC/F,IAAI,IAAI,OAAO,KAAA,KAAa,IAAI,OAAO,QAAQ,IAAI,OAAO,IACzD,OAAO;CAER,OAAO;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AI,KAAK,KAClB,MAAM,QAAQ,IAAI,MAAM,KAAK;;;;;AAM9B,MAAa,0BACZ,KACA,QAC6B;CAC7B,IAAI,CAAC,UAAU,GAAG,GACjB,MAAM,IAAI,MACT,oGACD;CAED,MAAM,OAAO,iBAAiB,KAAK,GAAG;CACtC,IAAI,CAAC,MACJ,OAAO;CAER,OAAO,IAAI,aAAa,WAAW,kBAAkB,MAAM,GAAG,IAAI,qBAAqB,MAAM,GAAG;AACjG"}
@@ -3,6 +3,7 @@ import { keys } from "../translations/keys.js";
3
3
  import { parseHttpUrl, parseOrigin } from "../net/origin.js";
4
4
  import { asTranslate } from "../translations/server.js";
5
5
  import { POSTHOG_CLOUD_HOSTS, cloudRegionOf } from "../adapters/posthog/cloud.js";
6
+ import { validations } from "payload";
6
7
  //#region src/providers/hosts.ts
7
8
  /**
8
9
  * Each vendor's own cloud, always allowed: its default origin, Umami Cloud's app address, and
@@ -112,25 +113,38 @@ const checkDocumentHost = (provider, raw, policy) => {
112
113
  /**
113
114
  * The `validate` of every provider `host` field: blank, or the address of the service with an
114
115
  * optional base path and nothing else, over https unless the install allows private networks.
116
+ * With `listed`, also the vendor's cloud or an address the allow list names, which reads would
117
+ * otherwise refuse after the save.
115
118
  */
116
- const validateProviderHost = (allowPrivateNetwork) => (value, { req }) => {
119
+ const validateProviderHost = (allowPrivateNetwork, listed) => (value, { req }) => {
117
120
  if (!value || value.trim() === "") return true;
118
121
  const parsed = parseHostAddress(value, allowPrivateNetwork);
119
- if (!("problem" in parsed)) return true;
120
- return asTranslate(req.t)(parsed.problem === "insecure" ? keys.providerErrorHostInsecure : keys.providerErrorHostFormat);
122
+ if ("problem" in parsed) return asTranslate(req.t)(parsed.problem === "insecure" ? keys.providerErrorHostInsecure : keys.providerErrorHostFormat);
123
+ return listed && !checkDocumentHost(listed.provider, value, {
124
+ allow: listed.allow,
125
+ allowPrivateNetwork
126
+ }).ok ? asTranslate(req.t)(keys.providerErrorHostNotAllowed) : true;
121
127
  };
122
128
  /**
123
129
  * A PostHog document's Host, after `validateProviderHost`: a PostHog Cloud address must be the cloud
124
130
  * its Region names, or capture would go to one region and reads to the other.
125
131
  */
126
- const validatePosthogHost = (allowPrivateNetwork) => (value, args) => {
127
- const address = validateProviderHost(allowPrivateNetwork)(value, args);
132
+ const validatePosthogHost = (allowPrivateNetwork, listed) => (value, args) => {
133
+ const address = validateProviderHost(allowPrivateNetwork, listed)(value, args);
128
134
  if (address !== true || !value) return address;
129
135
  const region = isRecord(args.siblingData) ? args.siblingData.region : void 0;
130
136
  const cloud = cloudRegionOf(value);
131
137
  return cloud && (region === "us" || region === "eu") && cloud !== region ? asTranslate(args.req.t)(keys.providerErrorPosthogHostRegion) : true;
132
138
  };
139
+ /**
140
+ * A PostHog document's Region, required while Host is blank: then it alone decides where reads and
141
+ * capture go, and an unset one would read from US Cloud without anyone choosing it.
142
+ */
143
+ const validatePosthogRegion = (value, options) => {
144
+ const host = isRecord(options.siblingData) ? options.siblingData.host : void 0;
145
+ return !value && (typeof host !== "string" || host.trim() === "") ? asTranslate(options.req.t)(keys.providerErrorPosthogRegionRequired) : validations.select(value, options);
146
+ };
133
147
  //#endregion
134
- export { checkDocumentHost, resolveHostPolicy, validatePosthogHost, validateProviderHost };
148
+ export { checkDocumentHost, resolveHostPolicy, validatePosthogHost, validatePosthogRegion, validateProviderHost };
135
149
 
136
150
  //# sourceMappingURL=hosts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hosts.js","names":[],"sources":["../../src/providers/hosts.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { cloudRegionOf, POSTHOG_CLOUD_HOSTS } from '../adapters/posthog/cloud'\nimport { isRecord, onlyKeys } from '../core/values'\nimport { type OriginProblem, parseHttpUrl, parseOrigin } from '../net/origin'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\n\n/** The providers whose document names a host. GA4 always talks to Google. */\nexport type HostedProvider = 'plausible' | 'umami' | 'posthog'\n\n/**\n * Each vendor's own cloud, always allowed: its default origin, Umami Cloud's app address, and\n * PostHog's other region and legacy US address.\n */\nexport const CLOUD_ORIGINS: Readonly<Record<HostedProvider, readonly string[]>> = {\n\tplausible: ['https://plausible.io'],\n\tumami: ['https://api.umami.is', 'https://cloud.umami.is'],\n\tposthog: Object.keys(POSTHOG_CLOUD_HOSTS).map((hostname) => `https://${hostname}`),\n}\n\n/** One `providers.hosts.allow` entry, parsed. */\nexport type HostPattern =\n\t| { kind: 'exact'; origin: string }\n\t| { kind: 'subdomains'; protocol: string; port: string; suffix: string }\n\n/** `providers.hosts`, resolved. */\nexport interface ProviderHostPolicy {\n\tallow: readonly HostPattern[]\n\tallowPrivateNetwork: boolean\n}\n\nexport const DEFAULT_HOST_POLICY: ProviderHostPolicy = { allow: [], allowPrivateNetwork: false }\n\n/** A vendor's address, as a document's `host` names it. */\ninterface HostAddress {\n\t/** Scheme, host and port: what the allowlist matches. */\n\torigin: string\n\t/** The origin and the base path a vendor served under a sub-path needs, with no trailing slash. */\n\taddress: string\n}\n\n/**\n * The address `value` names: an origin and an optional base path, with no credentials, query or\n * fragment and its trailing slash dropped. `http` only when the install allows private networks.\n */\nexport const parseHostAddress = (\n\tvalue: string,\n\tallowPrivateNetwork: boolean\n): HostAddress | { problem: OriginProblem } => {\n\tconst url = parseHttpUrl(value, allowPrivateNetwork)\n\tif (!(url instanceof URL)) {\n\t\treturn url\n\t}\n\treturn { origin: url.origin, address: `${url.origin}${url.pathname.replace(/\\/+$/, '')}` }\n}\n\nconst WILDCARD = '*.'\n\n/**\n * One allow entry: `https://analytics.example.com`, or `https://*.example.com` for every\n * subdomain of example.com (not example.com itself). Throws a boot error naming the entry.\n */\nexport const parseHostPattern = (entry: unknown, allowPrivateNetwork: boolean): HostPattern => {\n\tconst fail = (reason: string): never => {\n\t\tthrow new Error(`analytics: providers.hosts.allow entry ${JSON.stringify(entry)} ${reason}`)\n\t}\n\tif (typeof entry !== 'string' || entry.trim() === '') {\n\t\treturn fail('must be an origin such as \"https://analytics.example.com\"')\n\t}\n\tconst trimmed = entry.trim()\n\tconst scheme = trimmed.indexOf('://')\n\tconst wildcard = scheme !== -1 && trimmed.startsWith(WILDCARD, scheme + 3)\n\tconst candidate = wildcard\n\t\t? `${trimmed.slice(0, scheme + 3)}${trimmed.slice(scheme + 3 + WILDCARD.length)}`\n\t\t: trimmed\n\tif (candidate.includes('*')) {\n\t\treturn fail('may only start its host with \"*.\", as in \"https://*.example.com\"')\n\t}\n\tconst parsed = parseOrigin(candidate, allowPrivateNetwork)\n\tif ('problem' in parsed) {\n\t\treturn fail(\n\t\t\tparsed.problem === 'insecure'\n\t\t\t\t? 'uses http, which needs providers.hosts.allowPrivateNetwork'\n\t\t\t\t: 'must be an origin with no path, query or credentials, such as \"https://analytics.example.com\"'\n\t\t)\n\t}\n\tif (!wildcard) {\n\t\treturn { kind: 'exact', origin: parsed.origin }\n\t}\n\tconst url = new URL(parsed.origin)\n\tif (!url.hostname.includes('.')) {\n\t\treturn fail(\n\t\t\t'would match every site under one top-level domain; name a domain, as in \"https://*.example.com\"'\n\t\t)\n\t}\n\treturn { kind: 'subdomains', protocol: url.protocol, port: url.port, suffix: url.hostname }\n}\n\n/**\n * `providers.hosts` checked at boot.\n *\n * @beta\n */\nexport const resolveHostPolicy = (option: unknown): ProviderHostPolicy => {\n\tif (option === undefined) {\n\t\treturn DEFAULT_HOST_POLICY\n\t}\n\tif (!isRecord(option) || Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t'analytics: providers.hosts must be an object such as { allow: [\"https://analytics.example.com\"] }'\n\t\t)\n\t}\n\tonlyKeys(option, ['allow', 'allowPrivateNetwork'], 'providers.hosts')\n\tconst allowPrivateNetwork = option.allowPrivateNetwork ?? false\n\tif (typeof allowPrivateNetwork !== 'boolean') {\n\t\tthrow new Error('analytics: providers.hosts.allowPrivateNetwork must be a boolean')\n\t}\n\tconst allow = option.allow ?? []\n\tif (!Array.isArray(allow)) {\n\t\tthrow new Error('analytics: providers.hosts.allow must be a list of origins')\n\t}\n\treturn {\n\t\tallow: allow.map((entry: unknown) => parseHostPattern(entry, allowPrivateNetwork)),\n\t\tallowPrivateNetwork,\n\t}\n}\n\nconst matches = (pattern: HostPattern, url: URL): boolean =>\n\tpattern.kind === 'exact'\n\t\t? url.origin === pattern.origin\n\t\t: url.protocol === pattern.protocol &&\n\t\t\turl.port === pattern.port &&\n\t\t\turl.hostname.endsWith(`.${pattern.suffix}`)\n\n/** Whether a document's host may be reached, and the address it names; null for the vendor's cloud. */\nexport type DocumentHost =\n\t| { ok: true; address: string | null }\n\t| { ok: false; host: string; reason: string }\n\n/**\n * A document's `host` under the install's policy: blank is the vendor's cloud, anything else needs\n * an origin that is that cloud or in `allow`. The allowlist is about which server, not which path.\n */\nexport const checkDocumentHost = (\n\tprovider: HostedProvider,\n\traw: string | null | undefined,\n\tpolicy: ProviderHostPolicy\n): DocumentHost => {\n\tconst value = raw?.trim() ?? ''\n\tif (value === '') {\n\t\treturn { ok: true, address: null }\n\t}\n\tconst parsed = parseHostAddress(value, policy.allowPrivateNetwork)\n\tif ('problem' in parsed) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\thost: value,\n\t\t\treason:\n\t\t\t\tparsed.problem === 'insecure'\n\t\t\t\t\t? 'it uses http, which needs providers.hosts.allowPrivateNetwork'\n\t\t\t\t\t: 'it is not an address this install accepts',\n\t\t}\n\t}\n\tif (CLOUD_ORIGINS[provider].includes(parsed.origin)) {\n\t\treturn { ok: true, address: parsed.address }\n\t}\n\tconst url = new URL(parsed.origin)\n\tif (policy.allow.some((pattern) => matches(pattern, url))) {\n\t\treturn { ok: true, address: parsed.address }\n\t}\n\treturn { ok: false, host: parsed.origin, reason: 'it is not listed in providers.hosts.allow' }\n}\n\n/**\n * The `validate` of every provider `host` field: blank, or the address of the service with an\n * optional base path and nothing else, over https unless the install allows private networks.\n */\nexport const validateProviderHost =\n\t(allowPrivateNetwork: boolean): TextFieldSingleValidation =>\n\t(value, { req }) => {\n\t\tif (!value || value.trim() === '') {\n\t\t\treturn true\n\t\t}\n\t\tconst parsed = parseHostAddress(value, allowPrivateNetwork)\n\t\tif (!('problem' in parsed)) {\n\t\t\treturn true\n\t\t}\n\t\treturn asTranslate(req.t)(\n\t\t\tparsed.problem === 'insecure' ? keys.providerErrorHostInsecure : keys.providerErrorHostFormat\n\t\t)\n\t}\n\n/**\n * A PostHog document's Host, after `validateProviderHost`: a PostHog Cloud address must be the cloud\n * its Region names, or capture would go to one region and reads to the other.\n */\nexport const validatePosthogHost =\n\t(allowPrivateNetwork: boolean): TextFieldSingleValidation =>\n\t(value, args) => {\n\t\tconst address = validateProviderHost(allowPrivateNetwork)(value, args)\n\t\tif (address !== true || !value) {\n\t\t\treturn address\n\t\t}\n\t\tconst region = isRecord(args.siblingData) ? args.siblingData.region : undefined\n\t\tconst cloud = cloudRegionOf(value)\n\t\treturn cloud && (region === 'us' || region === 'eu') && cloud !== region\n\t\t\t? asTranslate(args.req.t)(keys.providerErrorPosthogHostRegion)\n\t\t\t: true\n\t}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,gBAAqE;CACjF,WAAW,CAAC,sBAAsB;CAClC,OAAO,CAAC,wBAAwB,wBAAwB;CACxD,SAAS,OAAO,KAAK,mBAAmB,EAAE,KAAK,aAAa,WAAW,UAAU;AAClF;AAaA,MAAa,sBAA0C;CAAE,OAAO,CAAC;CAAG,qBAAqB;AAAM;;;;;AAc/F,MAAa,oBACZ,OACA,wBAC8C;CAC9C,MAAM,MAAM,aAAa,OAAO,mBAAmB;CACnD,IAAI,EAAE,eAAe,MACpB,OAAO;CAER,OAAO;EAAE,QAAQ,IAAI;EAAQ,SAAS,GAAG,IAAI,SAAS,IAAI,SAAS,QAAQ,QAAQ,EAAE;CAAI;AAC1F;AAEA,MAAM,WAAW;;;;;AAMjB,MAAa,oBAAoB,OAAgB,wBAA8C;CAC9F,MAAM,QAAQ,WAA0B;EACvC,MAAM,IAAI,MAAM,0CAA0C,KAAK,UAAU,KAAK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KAAK,YAAY,SAAS,KAAA;CACtE,MAAM,QAAQ,cAAc,KAAK;CACjC,OAAO,UAAU,WAAW,QAAQ,WAAW,SAAS,UAAU,SAC/D,YAAY,KAAK,IAAI,CAAC,EAAE,KAAK,8BAA8B,IAC3D;AACJ"}
1
+ {"version":3,"file":"hosts.js","names":[],"sources":["../../src/providers/hosts.ts"],"sourcesContent":["import {\n\ttype SelectFieldSingleValidation,\n\ttype TextFieldSingleValidation,\n\tvalidations,\n} from 'payload'\nimport { cloudRegionOf, POSTHOG_CLOUD_HOSTS } from '../adapters/posthog/cloud'\nimport { isRecord, onlyKeys } from '../core/values'\nimport { type OriginProblem, parseHttpUrl, parseOrigin } from '../net/origin'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\n\n/** The providers whose document names a host. GA4 always talks to Google. */\nexport type HostedProvider = 'plausible' | 'umami' | 'posthog'\n\n/**\n * Each vendor's own cloud, always allowed: its default origin, Umami Cloud's app address, and\n * PostHog's other region and legacy US address.\n */\nexport const CLOUD_ORIGINS: Readonly<Record<HostedProvider, readonly string[]>> = {\n\tplausible: ['https://plausible.io'],\n\tumami: ['https://api.umami.is', 'https://cloud.umami.is'],\n\tposthog: Object.keys(POSTHOG_CLOUD_HOSTS).map((hostname) => `https://${hostname}`),\n}\n\n/** One `providers.hosts.allow` entry, parsed. */\nexport type HostPattern =\n\t| { kind: 'exact'; origin: string }\n\t| { kind: 'subdomains'; protocol: string; port: string; suffix: string }\n\n/** `providers.hosts`, resolved. */\nexport interface ProviderHostPolicy {\n\tallow: readonly HostPattern[]\n\tallowPrivateNetwork: boolean\n}\n\nexport const DEFAULT_HOST_POLICY: ProviderHostPolicy = { allow: [], allowPrivateNetwork: false }\n\n/** A vendor's address, as a document's `host` names it. */\ninterface HostAddress {\n\t/** Scheme, host and port: what the allowlist matches. */\n\torigin: string\n\t/** The origin and the base path a vendor served under a sub-path needs, with no trailing slash. */\n\taddress: string\n}\n\n/**\n * The address `value` names: an origin and an optional base path, with no credentials, query or\n * fragment and its trailing slash dropped. `http` only when the install allows private networks.\n */\nexport const parseHostAddress = (\n\tvalue: string,\n\tallowPrivateNetwork: boolean\n): HostAddress | { problem: OriginProblem } => {\n\tconst url = parseHttpUrl(value, allowPrivateNetwork)\n\tif (!(url instanceof URL)) {\n\t\treturn url\n\t}\n\treturn { origin: url.origin, address: `${url.origin}${url.pathname.replace(/\\/+$/, '')}` }\n}\n\nconst WILDCARD = '*.'\n\n/**\n * One allow entry: `https://analytics.example.com`, or `https://*.example.com` for every\n * subdomain of example.com (not example.com itself). Throws a boot error naming the entry.\n */\nexport const parseHostPattern = (entry: unknown, allowPrivateNetwork: boolean): HostPattern => {\n\tconst fail = (reason: string): never => {\n\t\tthrow new Error(`analytics: providers.hosts.allow entry ${JSON.stringify(entry)} ${reason}`)\n\t}\n\tif (typeof entry !== 'string' || entry.trim() === '') {\n\t\treturn fail('must be an origin such as \"https://analytics.example.com\"')\n\t}\n\tconst trimmed = entry.trim()\n\tconst scheme = trimmed.indexOf('://')\n\tconst wildcard = scheme !== -1 && trimmed.startsWith(WILDCARD, scheme + 3)\n\tconst candidate = wildcard\n\t\t? `${trimmed.slice(0, scheme + 3)}${trimmed.slice(scheme + 3 + WILDCARD.length)}`\n\t\t: trimmed\n\tif (candidate.includes('*')) {\n\t\treturn fail('may only start its host with \"*.\", as in \"https://*.example.com\"')\n\t}\n\tconst parsed = parseOrigin(candidate, allowPrivateNetwork)\n\tif ('problem' in parsed) {\n\t\treturn fail(\n\t\t\tparsed.problem === 'insecure'\n\t\t\t\t? 'uses http, which needs providers.hosts.allowPrivateNetwork'\n\t\t\t\t: 'must be an origin with no path, query or credentials, such as \"https://analytics.example.com\"'\n\t\t)\n\t}\n\tif (!wildcard) {\n\t\treturn { kind: 'exact', origin: parsed.origin }\n\t}\n\tconst url = new URL(parsed.origin)\n\tif (!url.hostname.includes('.')) {\n\t\treturn fail(\n\t\t\t'would match every site under one top-level domain; name a domain, as in \"https://*.example.com\"'\n\t\t)\n\t}\n\treturn { kind: 'subdomains', protocol: url.protocol, port: url.port, suffix: url.hostname }\n}\n\n/**\n * `providers.hosts` checked at boot.\n *\n * @beta\n */\nexport const resolveHostPolicy = (option: unknown): ProviderHostPolicy => {\n\tif (option === undefined) {\n\t\treturn DEFAULT_HOST_POLICY\n\t}\n\tif (!isRecord(option) || Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t'analytics: providers.hosts must be an object such as { allow: [\"https://analytics.example.com\"] }'\n\t\t)\n\t}\n\tonlyKeys(option, ['allow', 'allowPrivateNetwork'], 'providers.hosts')\n\tconst allowPrivateNetwork = option.allowPrivateNetwork ?? false\n\tif (typeof allowPrivateNetwork !== 'boolean') {\n\t\tthrow new Error('analytics: providers.hosts.allowPrivateNetwork must be a boolean')\n\t}\n\tconst allow = option.allow ?? []\n\tif (!Array.isArray(allow)) {\n\t\tthrow new Error('analytics: providers.hosts.allow must be a list of origins')\n\t}\n\treturn {\n\t\tallow: allow.map((entry: unknown) => parseHostPattern(entry, allowPrivateNetwork)),\n\t\tallowPrivateNetwork,\n\t}\n}\n\nconst matches = (pattern: HostPattern, url: URL): boolean =>\n\tpattern.kind === 'exact'\n\t\t? url.origin === pattern.origin\n\t\t: url.protocol === pattern.protocol &&\n\t\t\turl.port === pattern.port &&\n\t\t\turl.hostname.endsWith(`.${pattern.suffix}`)\n\n/** Whether a document's host may be reached, and the address it names; null for the vendor's cloud. */\nexport type DocumentHost =\n\t| { ok: true; address: string | null }\n\t| { ok: false; host: string; reason: string }\n\n/**\n * A document's `host` under the install's policy: blank is the vendor's cloud, anything else needs\n * an origin that is that cloud or in `allow`. The allowlist is about which server, not which path.\n */\nexport const checkDocumentHost = (\n\tprovider: HostedProvider,\n\traw: string | null | undefined,\n\tpolicy: ProviderHostPolicy\n): DocumentHost => {\n\tconst value = raw?.trim() ?? ''\n\tif (value === '') {\n\t\treturn { ok: true, address: null }\n\t}\n\tconst parsed = parseHostAddress(value, policy.allowPrivateNetwork)\n\tif ('problem' in parsed) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\thost: value,\n\t\t\treason:\n\t\t\t\tparsed.problem === 'insecure'\n\t\t\t\t\t? 'it uses http, which needs providers.hosts.allowPrivateNetwork'\n\t\t\t\t\t: 'it is not an address this install accepts',\n\t\t}\n\t}\n\tif (CLOUD_ORIGINS[provider].includes(parsed.origin)) {\n\t\treturn { ok: true, address: parsed.address }\n\t}\n\tconst url = new URL(parsed.origin)\n\tif (policy.allow.some((pattern) => matches(pattern, url))) {\n\t\treturn { ok: true, address: parsed.address }\n\t}\n\treturn { ok: false, host: parsed.origin, reason: 'it is not listed in providers.hosts.allow' }\n}\n\n/** The install's `providers.hosts.allow`, for the `host` field of one vendor. */\nexport type ListedHosts = { provider: HostedProvider; allow: readonly HostPattern[] }\n\n/**\n * The `validate` of every provider `host` field: blank, or the address of the service with an\n * optional base path and nothing else, over https unless the install allows private networks.\n * With `listed`, also the vendor's cloud or an address the allow list names, which reads would\n * otherwise refuse after the save.\n */\nexport const validateProviderHost =\n\t(allowPrivateNetwork: boolean, listed?: ListedHosts): TextFieldSingleValidation =>\n\t(value, { req }) => {\n\t\tif (!value || value.trim() === '') {\n\t\t\treturn true\n\t\t}\n\t\tconst parsed = parseHostAddress(value, allowPrivateNetwork)\n\t\tif ('problem' in parsed) {\n\t\t\treturn asTranslate(req.t)(\n\t\t\t\tparsed.problem === 'insecure'\n\t\t\t\t\t? keys.providerErrorHostInsecure\n\t\t\t\t\t: keys.providerErrorHostFormat\n\t\t\t)\n\t\t}\n\t\treturn listed &&\n\t\t\t!checkDocumentHost(listed.provider, value, { allow: listed.allow, allowPrivateNetwork }).ok\n\t\t\t? asTranslate(req.t)(keys.providerErrorHostNotAllowed)\n\t\t\t: true\n\t}\n\n/**\n * A PostHog document's Host, after `validateProviderHost`: a PostHog Cloud address must be the cloud\n * its Region names, or capture would go to one region and reads to the other.\n */\nexport const validatePosthogHost =\n\t(allowPrivateNetwork: boolean, listed?: ListedHosts): TextFieldSingleValidation =>\n\t(value, args) => {\n\t\tconst address = validateProviderHost(allowPrivateNetwork, listed)(value, args)\n\t\tif (address !== true || !value) {\n\t\t\treturn address\n\t\t}\n\t\tconst region = isRecord(args.siblingData) ? args.siblingData.region : undefined\n\t\tconst cloud = cloudRegionOf(value)\n\t\treturn cloud && (region === 'us' || region === 'eu') && cloud !== region\n\t\t\t? asTranslate(args.req.t)(keys.providerErrorPosthogHostRegion)\n\t\t\t: true\n\t}\n\n/**\n * A PostHog document's Region, required while Host is blank: then it alone decides where reads and\n * capture go, and an unset one would read from US Cloud without anyone choosing it.\n */\nexport const validatePosthogRegion: SelectFieldSingleValidation = (value, options) => {\n\tconst host = isRecord(options.siblingData) ? options.siblingData.host : undefined\n\treturn !value && (typeof host !== 'string' || host.trim() === '')\n\t\t? asTranslate(options.req.t)(keys.providerErrorPosthogRegionRequired)\n\t\t: validations.select(value, options)\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAa,gBAAqE;CACjF,WAAW,CAAC,sBAAsB;CAClC,OAAO,CAAC,wBAAwB,wBAAwB;CACxD,SAAS,OAAO,KAAK,mBAAmB,EAAE,KAAK,aAAa,WAAW,UAAU;AAClF;AAaA,MAAa,sBAA0C;CAAE,OAAO,CAAC;CAAG,qBAAqB;AAAM;;;;;AAc/F,MAAa,oBACZ,OACA,wBAC8C;CAC9C,MAAM,MAAM,aAAa,OAAO,mBAAmB;CACnD,IAAI,EAAE,eAAe,MACpB,OAAO;CAER,OAAO;EAAE,QAAQ,IAAI;EAAQ,SAAS,GAAG,IAAI,SAAS,IAAI,SAAS,QAAQ,QAAQ,EAAE;CAAI;AAC1F;AAEA,MAAM,WAAW;;;;;AAMjB,MAAa,oBAAoB,OAAgB,wBAA8C;CAC9F,MAAM,QAAQ,WAA0B;EACvC,MAAM,IAAI,MAAM,0CAA0C,KAAK,UAAU,KAAK,EAAE,GAAG,QAAQ;CAC5F;CACA,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAC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I,YAAY,QAAQ,CAAC,OACxB,OAAO;CAER,MAAM,SAAS,SAAS,KAAK,WAAW,IAAI,KAAK,YAAY,SAAS,KAAA;CACtE,MAAM,QAAQ,cAAc,KAAK;CACjC,OAAO,UAAU,WAAW,QAAQ,WAAW,SAAS,UAAU,SAC/D,YAAY,KAAK,IAAI,CAAC,EAAE,KAAK,8BAA8B,IAC3D;AACJ;;;;;AAMD,MAAa,yBAAsD,OAAO,YAAY;CACrF,MAAM,OAAO,SAAS,QAAQ,WAAW,IAAI,QAAQ,YAAY,OAAO,KAAA;CACxE,OAAO,CAAC,UAAU,OAAO,SAAS,YAAY,KAAK,KAAK,MAAM,MAC3D,YAAY,QAAQ,IAAI,CAAC,EAAE,KAAK,kCAAkC,IAClE,YAAY,OAAO,OAAO,OAAO;AACrC"}
@@ -0,0 +1,6 @@
1
+ //#region src/providers/ids.d.ts
2
+ type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog';
3
+ declare const PROVIDER_IDS: readonly ["native", "plausible", "umami", "ga4", "posthog"];
4
+ //#endregion
5
+ export { PROVIDER_IDS, ProviderId };
6
+ //# sourceMappingURL=ids.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { keys } from "../translations/keys.js";
2
+ //#region src/providers/ids.ts
3
+ const PROVIDER_IDS = [
4
+ "native",
5
+ "plausible",
6
+ "umami",
7
+ "ga4",
8
+ "posthog"
9
+ ];
10
+ /** Each provider type's name, as the Provider select and the Connection panel show it. */
11
+ const PROVIDER_NAMES = {
12
+ native: keys.providerNameNative,
13
+ plausible: keys.providerNamePlausible,
14
+ umami: keys.providerNameUmami,
15
+ ga4: keys.providerNameGa4,
16
+ posthog: keys.providerNamePosthog
17
+ };
18
+ /** The registry id of a provider document's adapter, which grants and stand-ins must match. */
19
+ const documentAdapterId = (provider, id) => `${String(provider)}:${String(id)}`;
20
+ /**
21
+ * The provider document a registry id names, the inverse of {@link documentAdapterId}; undefined
22
+ * for an id no document gives.
23
+ */
24
+ const documentIdOf = (adapterId) => {
25
+ const at = adapterId.indexOf(":");
26
+ const provider = adapterId.slice(0, at);
27
+ return at > 0 && at < adapterId.length - 1 && PROVIDER_IDS.some((id) => id === provider) ? adapterId.slice(at + 1) : void 0;
28
+ };
29
+ //#endregion
30
+ export { PROVIDER_IDS, PROVIDER_NAMES, documentAdapterId, documentIdOf };
31
+
32
+ //# sourceMappingURL=ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.js","names":[],"sources":["../../src/providers/ids.ts"],"sourcesContent":["import { keys, type TranslationKey } from '../translations/keys'\n\nexport type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog'\nexport const PROVIDER_IDS = [\n\t'native',\n\t'plausible',\n\t'umami',\n\t'ga4',\n\t'posthog',\n] as const satisfies readonly ProviderId[]\n\n/** Each provider type's name, as the Provider select and the Connection panel show it. */\nexport const PROVIDER_NAMES: Readonly<Record<ProviderId, TranslationKey>> = {\n\tnative: keys.providerNameNative,\n\tplausible: keys.providerNamePlausible,\n\tumami: keys.providerNameUmami,\n\tga4: keys.providerNameGa4,\n\tposthog: keys.providerNamePosthog,\n}\n\n/** The registry id of a provider document's adapter, which grants and stand-ins must match. */\nexport const documentAdapterId = (provider: unknown, id: unknown): string =>\n\t`${String(provider)}:${String(id)}`\n\n/**\n * The provider document a registry id names, the inverse of {@link documentAdapterId}; undefined\n * for an id no document gives.\n */\nexport const documentIdOf = (adapterId: string): string | undefined => {\n\tconst at = adapterId.indexOf(':')\n\tconst provider = adapterId.slice(0, at)\n\treturn at > 0 && at < adapterId.length - 1 && PROVIDER_IDS.some((id) => id === provider)\n\t\t? adapterId.slice(at + 1)\n\t\t: undefined\n}\n"],"mappings":";;AAGA,MAAa,eAAe;CAC3B;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAa,iBAA+D;CAC3E,QAAQ,KAAK;CACb,WAAW,KAAK;CAChB,OAAO,KAAK;CACZ,KAAK,KAAK;CACV,SAAS,KAAK;AACf;;AAGA,MAAa,qBAAqB,UAAmB,OACpD,GAAG,OAAO,QAAQ,EAAE,GAAG,OAAO,EAAE;;;;;AAMjC,MAAa,gBAAgB,cAA0C;CACtE,MAAM,KAAK,UAAU,QAAQ,GAAG;CAChC,MAAM,WAAW,UAAU,MAAM,GAAG,EAAE;CACtC,OAAO,KAAK,KAAK,KAAK,UAAU,SAAS,KAAK,aAAa,MAAM,OAAO,OAAO,QAAQ,IACpF,UAAU,MAAM,KAAK,CAAC,IACtB,KAAA;AACJ"}
@@ -0,0 +1,60 @@
1
+ "use client";
2
+ import { isOneOf } from "../core/values.js";
3
+ import { analyticsRoutes } from "../plugin/routes.js";
4
+ import { PROVIDER_IDS } from "./ids.js";
5
+ import { isProviderStatusResponse } from "./connectionState.js";
6
+ import { apiPath } from "../plugin/apiPath.js";
7
+ import { isAbortError, requestShaped } from "../ui/data/request.js";
8
+ import { useEffect, useState } from "react";
9
+ import { useConfig, useDocumentInfo } from "@payloadcms/ui";
10
+ //#region src/providers/providerStatusClient.ts
11
+ /**
12
+ * Who shows a document's status, keyed by its status URL: the Test connection button sits in the
13
+ * document controls and the Connection panel in the sidebar, so a check tells the panel this way.
14
+ */
15
+ const listeners = /* @__PURE__ */ new Map();
16
+ /** Hands a status a check answered to every panel showing that document. */
17
+ const publishProviderStatus = (url, status) => {
18
+ for (const listener of listeners.get(url) ?? []) listener(status);
19
+ };
20
+ /** Whether a provider has a connection to show and test: every vendor, not `native`. */
21
+ const hasConnection = (provider) => isOneOf(PROVIDER_IDS, provider) && provider !== "native";
22
+ /** The open document's status URL, undefined before its first save. */
23
+ const useProviderStatusUrl = () => {
24
+ const { config } = useConfig();
25
+ const { id } = useDocumentInfo();
26
+ if (id === void 0 || id === null) return;
27
+ return `${apiPath(config, analyticsRoutes(config).providerStatus)}?id=${encodeURIComponent(String(id))}`;
28
+ };
29
+ /**
30
+ * The open document's last connection result: read on mount and after each save, which may have
31
+ * reset it, and replaced by what a Test connection click answered. Undefined while it loads; a
32
+ * status that cannot be read shows as never checked.
33
+ */
34
+ const useProviderStatus = (url) => {
35
+ const { lastUpdateTime } = useDocumentInfo();
36
+ const [status, setStatus] = useState();
37
+ useEffect(() => {
38
+ if (url === void 0) return;
39
+ const controller = new AbortController();
40
+ requestShaped(url, isProviderStatusResponse, { signal: controller.signal }).then((answer) => setStatus(answer.status), (err) => {
41
+ if (!isAbortError(err)) setStatus({});
42
+ });
43
+ return () => controller.abort();
44
+ }, [url, lastUpdateTime]);
45
+ useEffect(() => {
46
+ if (url === void 0) return;
47
+ const subscribed = listeners.get(url) ?? /* @__PURE__ */ new Set();
48
+ listeners.set(url, subscribed);
49
+ subscribed.add(setStatus);
50
+ return () => {
51
+ subscribed.delete(setStatus);
52
+ if (subscribed.size === 0) listeners.delete(url);
53
+ };
54
+ }, [url]);
55
+ return status;
56
+ };
57
+ //#endregion
58
+ export { hasConnection, publishProviderStatus, useProviderStatus, useProviderStatusUrl };
59
+
60
+ //# sourceMappingURL=providerStatusClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providerStatusClient.js","names":[],"sources":["../../src/providers/providerStatusClient.ts"],"sourcesContent":["'use client'\n\nimport { useConfig, useDocumentInfo } from '@payloadcms/ui'\nimport { useEffect, useState } from 'react'\nimport { isOneOf } from '../core/values'\nimport { apiPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport { isAbortError, requestShaped } from '../ui/data/request'\nimport { isProviderStatusResponse, type ProviderStatus } from './connectionState'\nimport { PROVIDER_IDS } from './ids'\n\ntype Listener = (status: ProviderStatus) => void\n\n/**\n * Who shows a document's status, keyed by its status URL: the Test connection button sits in the\n * document controls and the Connection panel in the sidebar, so a check tells the panel this way.\n */\nconst listeners = new Map<string, Set<Listener>>()\n\n/** Hands a status a check answered to every panel showing that document. */\nexport const publishProviderStatus = (url: string, status: ProviderStatus): void => {\n\tfor (const listener of listeners.get(url) ?? []) {\n\t\tlistener(status)\n\t}\n}\n\n/** Whether a provider has a connection to show and test: every vendor, not `native`. */\nexport const hasConnection = (provider: unknown): boolean =>\n\tisOneOf(PROVIDER_IDS, provider) && provider !== 'native'\n\n/** The open document's status URL, undefined before its first save. */\nexport const useProviderStatusUrl = (): string | undefined => {\n\tconst { config } = useConfig()\n\tconst { id } = useDocumentInfo()\n\tif (id === undefined || id === null) {\n\t\treturn undefined\n\t}\n\treturn `${apiPath(config, analyticsRoutes(config).providerStatus)}?id=${encodeURIComponent(String(id))}`\n}\n\n/**\n * The open document's last connection result: read on mount and after each save, which may have\n * reset it, and replaced by what a Test connection click answered. Undefined while it loads; a\n * status that cannot be read shows as never checked.\n */\nexport const useProviderStatus = (url: string | undefined): ProviderStatus | undefined => {\n\tconst { lastUpdateTime } = useDocumentInfo()\n\tconst [status, setStatus] = useState<ProviderStatus>()\n\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: `lastUpdateTime` is the save that may have reset the status (a new key, another host), not a value it reads.\n\tuseEffect(() => {\n\t\tif (url === undefined) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\trequestShaped(url, isProviderStatusResponse, { signal: controller.signal }).then(\n\t\t\t(answer) => setStatus(answer.status),\n\t\t\t(err: unknown) => {\n\t\t\t\tif (!isAbortError(err)) {\n\t\t\t\t\tsetStatus({})\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\t\treturn () => controller.abort()\n\t}, [url, lastUpdateTime])\n\n\tuseEffect(() => {\n\t\tif (url === undefined) {\n\t\t\treturn\n\t\t}\n\t\tconst subscribed = listeners.get(url) ?? new Set<Listener>()\n\t\tlisteners.set(url, subscribed)\n\t\tsubscribed.add(setStatus)\n\t\treturn () => {\n\t\t\tsubscribed.delete(setStatus)\n\t\t\tif (subscribed.size === 0) {\n\t\t\t\tlisteners.delete(url)\n\t\t\t}\n\t\t}\n\t}, [url])\n\n\treturn status\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,4BAAY,IAAI,IAA2B;;AAGjD,MAAa,yBAAyB,KAAa,WAAiC;CACnF,KAAK,MAAM,YAAY,UAAU,IAAI,GAAG,KAAK,CAAC,GAC7C,SAAS,MAAM;AAEjB;;AAGA,MAAa,iBAAiB,aAC7B,QAAQ,cAAc,QAAQ,KAAK,aAAa;;AAGjD,MAAa,6BAAiD;CAC7D,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,EAAE,OAAO,gBAAgB;CAC/B,IAAI,OAAO,KAAA,KAAa,OAAO,MAC9B;CAED,OAAO,GAAG,QAAQ,QAAQ,gBAAgB,MAAM,EAAE,cAAc,EAAE,MAAM,mBAAmB,OAAO,EAAE,CAAC;AACtG;;;;;;AAOA,MAAa,qBAAqB,QAAwD;CACzF,MAAM,EAAE,mBAAmB,gBAAgB;CAC3C,MAAM,CAAC,QAAQ,aAAa,SAAyB;CAGrD,gBAAgB;EACf,IAAI,QAAQ,KAAA,GACX;EAED,MAAM,aAAa,IAAI,gBAAgB;EACvC,cAAc,KAAK,0BAA0B,EAAE,QAAQ,WAAW,OAAO,CAAC,EAAE,MAC1E,WAAW,UAAU,OAAO,MAAM,IAClC,QAAiB;GACjB,IAAI,CAAC,aAAa,GAAG,GACpB,UAAU,CAAC,CAAC;EAEd,CACD;EACA,aAAa,WAAW,MAAM;CAC/B,GAAG,CAAC,KAAK,cAAc,CAAC;CAExB,gBAAgB;EACf,IAAI,QAAQ,KAAA,GACX;EAED,MAAM,aAAa,UAAU,IAAI,GAAG,qBAAK,IAAI,IAAc;EAC3D,UAAU,IAAI,KAAK,UAAU;EAC7B,WAAW,IAAI,SAAS;EACxB,aAAa;GACZ,WAAW,OAAO,SAAS;GAC3B,IAAI,WAAW,SAAS,GACvB,UAAU,OAAO,GAAG;EAEtB;CACD,GAAG,CAAC,GAAG,CAAC;CAER,OAAO;AACR"}
@@ -5,18 +5,17 @@ import { combineRegistries, noGuardedConnection, providerScopeWhere } from "./re
5
5
  import { currentTime } from "../core/clock.js";
6
6
  import { remember } from "../surfacing/bounded.js";
7
7
  import { createEpochFallback } from "../surfacing/epoch.js";
8
- import { GA4_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
9
- import { PROVIDER_IDS, adapterFromProviderDoc, documentAdapterId, failingAdapter } from "./factory.js";
10
- import { SECRET_PATHS } from "./secrets.js";
8
+ import { PROVIDER_IDS, documentAdapterId } from "./ids.js";
11
9
  import { isCollectionSlug } from "../core/collectionSlug.js";
12
10
  import { createCollectionProbe, scopeOf, versionOf } from "./probe.js";
13
- import { throttled } from "../core/throttle.js";
11
+ import { SECRET_PATHS } from "./secrets.js";
12
+ import { WARN_EVERY_MS, throttled } from "../core/throttle.js";
13
+ import { GA4_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
14
14
  import { loadEncrypted } from "../plugin/encrypted.js";
15
15
  import { createAdapterPool } from "./adapterPool.js";
16
+ import { adapterFromProviderDoc, failingAdapter } from "./factory.js";
16
17
  import { createLocalReq } from "payload";
17
18
  //#region src/providers/registry.ts
18
- /** How often a failing probe is reported, at most. */
19
- const WARN_EVERY_MS = 6e4;
20
19
  /**
21
20
  * How long a document whose adapter could not be built (its secrets did not decrypt, its settings
22
21
  * threw) stands in as a failing source before its scope's registry reads it again.
@@ -154,6 +153,11 @@ const collectionRegistry = (options, plan) => {
154
153
  const idOf = (id) => {
155
154
  return ((isCollectionSlug(payload, slug) ? payload.collections[slug]?.customIDType : void 0) ?? payload.db.defaultIDType) === "number" && /^\d+$/.test(id) ? Number(id) : id;
156
155
  };
156
+ const versions = /* @__PURE__ */ new WeakMap();
157
+ const stamped = (adapter, version) => {
158
+ if (adapter) versions.set(adapter, version);
159
+ return adapter;
160
+ };
157
161
  const fromDocument = (doc) => adapterFromProviderDoc(doc, {
158
162
  ...plan.nativeAdapter ? { native: plan.nativeAdapter } : {},
159
163
  hosts: options.hosts,
@@ -161,18 +165,22 @@ const collectionRegistry = (options, plan) => {
161
165
  sdks: options.sdks,
162
166
  ...options.withoutConsent
163
167
  });
168
+ /** A stored document with its secrets decrypted in a copy. */
169
+ const decrypted = async (raw, decrypt) => {
170
+ const doc = structuredClone(raw);
171
+ for (const { path, value } of storedSecrets(doc)) {
172
+ const plain = await decrypt(payload, {
173
+ collection: slug,
174
+ path,
175
+ value
176
+ });
177
+ setAtPath(doc, path, typeof plain === "string" ? plain : "");
178
+ }
179
+ return doc;
180
+ };
164
181
  const adapterOf = async (raw, decrypt) => {
165
182
  try {
166
- const doc = structuredClone(raw);
167
- for (const { path, value } of storedSecrets(doc)) {
168
- const plain = await decrypt(payload, {
169
- collection: slug,
170
- path,
171
- value
172
- });
173
- setAtPath(doc, path, typeof plain === "string" ? plain : "");
174
- }
175
- const adapter = fromDocument(doc);
183
+ const adapter = fromDocument(await decrypted(raw, decrypt));
176
184
  if (raw.provider === "ga4" && !options.sdks.ga4 && !warnedGa4 && isProductionBuild()) {
177
185
  warnedGa4 = true;
178
186
  payload.logger?.warn(GA4_SDK_WARNING);
@@ -220,9 +228,11 @@ const collectionRegistry = (options, plan) => {
220
228
  scope
221
229
  };
222
230
  const outcome = await adapterOf(raw, decryptFieldValue);
223
- if (outcome.ok) built.set(doc.id, pool.put(doc, outcome.adapter, raw.provider !== "native"));
224
- else {
225
- built.set(doc.id, outcome.standIn);
231
+ if (outcome.ok) {
232
+ const pooled = pool.put(doc, outcome.adapter, raw.provider !== "native");
233
+ built.set(doc.id, pool.get(doc) === pooled ? stamped(pooled, doc.version) : pooled);
234
+ } else {
235
+ built.set(doc.id, stamped(outcome.standIn, doc.version));
226
236
  failed = true;
227
237
  }
228
238
  }
@@ -245,10 +255,15 @@ const collectionRegistry = (options, plan) => {
245
255
  }
246
256
  pool.retain(scope, new Set(docs.map((doc) => doc.id)));
247
257
  const combined = combineRegistries(options.base, extras);
258
+ const narrowed = options.narrow(combined.registry);
259
+ for (const adapter of narrowed.all()) {
260
+ const version = versions.get(combined.registry.get(adapter.id));
261
+ if (version !== void 0) versions.set(adapter, version);
262
+ }
248
263
  return {
249
264
  registry: {
250
265
  ...combined,
251
- registry: options.narrow(combined.registry)
266
+ registry: narrowed
252
267
  },
253
268
  failed: read?.failed === true
254
269
  };
@@ -311,6 +326,27 @@ const collectionRegistry = (options, plan) => {
311
326
  },
312
327
  changed: (scopes) => probe.expedite(scopes),
313
328
  refresh: async (scope) => probe.expedite([scope]),
329
+ documentAdapter: async (id) => {
330
+ if (!isCollectionSlug(payload, slug)) return null;
331
+ const { decryptFieldValue, withRawEncrypted } = await loadEncrypted();
332
+ const req = await createLocalReq({}, payload);
333
+ const raw = await withRawEncrypted(req, () => payload.findByID({
334
+ collection: slug,
335
+ id: idOf(id),
336
+ depth: 0,
337
+ overrideAccess: true,
338
+ disableErrors: true,
339
+ req
340
+ }));
341
+ if (!isRecord(raw)) return null;
342
+ const version = versionOf(raw.updatedAt);
343
+ try {
344
+ return stamped(fromDocument(await decrypted(raw, decryptFieldValue)), version);
345
+ } catch (err) {
346
+ return stamped(standInFor(raw, err, fromDocument), version);
347
+ }
348
+ },
349
+ versionOf: (adapter) => versions.get(adapter),
314
350
  close: () => pool.close()
315
351
  };
316
352
  };