@10x-media/analytics 1.0.0-beta.15 → 1.0.0-beta.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +1 -1
- package/dist/adapters/posthog/cloud.js +20 -0
- package/dist/adapters/posthog/cloud.js.map +1 -0
- package/dist/adapters/posthog/credentials.js +20 -0
- package/dist/adapters/posthog/credentials.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +3 -3
- package/dist/adapters/posthog/posthog.js +8 -8
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/providers/collection.js +14 -8
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/hosts.js +14 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/translations/ar.js +3 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +3 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +3 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +3 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +3 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +3 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +3 -0
- package/dist/translations/keys.js +3 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +3 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +3 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +3 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +3 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +3 -0
- package/dist/translations/zh.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.16
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- **Fixed (PostHog): hourly series read again.** The adapter bucketed hours with `toStartOfHour(timestamp, '<zone>')`, which HogQL refuses ("Function 'toStartOfHour' expects 1 argument, found 2"), so every hourly read failed, the platform source's included, and the today and 24-hour views showed nothing. Hours are now bucketed as `toStartOfHour(toTimeZone(timestamp, '<zone>'))`, still in the reporting timezone. Day series are unchanged.
|
|
8
|
+
|
|
9
|
+
**Behavioral (PostHog): with no `host`, reads go to the region's cloud.** `region` used to steer capture alone, and reads went to US Cloud whenever `host` was unset, so a provider document on EU Cloud with a blank **Host** sent its EU key to `us.posthog.com`, was refused with a 403 and was rested. Reads now go to `https://<region>.posthog.com`, the cloud capture already used; US Cloud stays the default with neither set. A stored document reads from its region as it is: nothing to migrate, and its key is kept.
|
|
10
|
+
|
|
11
|
+
**Additive: a PostHog provider document refuses three paste mistakes.** A **Host** on the other PostHog Cloud region than the **Region** picked, a project token (`phc_...`) in **API key**, and a private key (`phx_...`, `phs_...`) in **Project token**, which the browser receives, are refused with a field error in all 11 locales.
|
|
12
|
+
|
|
3
13
|
## 1.0.0-beta.15
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Analytics for Payload v3 behind one adapter contract: a self-hosted native engin
|
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/@10x-media/analytics)
|
|
8
8
|
|
|
9
|
-
Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-plugins) collection. In beta:
|
|
9
|
+
Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-plugins) collection. In beta until a stable 1.0: `-beta.N` releases on the `latest` dist-tag.
|
|
10
10
|
|
|
11
11
|
## What it does
|
|
12
12
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { hostnameOf } from "../http/baseUrl.js";
|
|
2
|
+
//#region src/adapters/posthog/cloud.ts
|
|
3
|
+
/**
|
|
4
|
+
* PostHog Cloud's app hosts and the region each serves: the region's own address, and the older US
|
|
5
|
+
* address `app.posthog.com`. Its own module so the providers collection checks a Host against its
|
|
6
|
+
* Region on the adapter's terms without loading the adapter.
|
|
7
|
+
*/
|
|
8
|
+
const POSTHOG_CLOUD_HOSTS = {
|
|
9
|
+
"us.posthog.com": "us",
|
|
10
|
+
"eu.posthog.com": "eu",
|
|
11
|
+
"app.posthog.com": "us"
|
|
12
|
+
};
|
|
13
|
+
/** The cloud region an address belongs to, or null for a self-hosted instance or no address. */
|
|
14
|
+
const cloudRegionOf = (address) => POSTHOG_CLOUD_HOSTS[hostnameOf(address)] ?? null;
|
|
15
|
+
/** Where a region's app and Query API answer. */
|
|
16
|
+
const cloudAppHost = (region) => `https://${region}.posthog.com`;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { POSTHOG_CLOUD_HOSTS, cloudAppHost, cloudRegionOf };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=cloud.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud.js","names":[],"sources":["../../../src/adapters/posthog/cloud.ts"],"sourcesContent":["import { hostnameOf } from '../http/baseUrl'\n\n/** A PostHog Cloud region. */\nexport type PosthogRegion = 'us' | 'eu'\n\n/**\n * PostHog Cloud's app hosts and the region each serves: the region's own address, and the older US\n * address `app.posthog.com`. Its own module so the providers collection checks a Host against its\n * Region on the adapter's terms without loading the adapter.\n */\nexport const POSTHOG_CLOUD_HOSTS: Readonly<Record<string, PosthogRegion>> = {\n\t'us.posthog.com': 'us',\n\t'eu.posthog.com': 'eu',\n\t'app.posthog.com': 'us',\n}\n\n/** The cloud region an address belongs to, or null for a self-hosted instance or no address. */\nexport const cloudRegionOf = (address: string): PosthogRegion | null =>\n\tPOSTHOG_CLOUD_HOSTS[hostnameOf(address)] ?? null\n\n/** Where a region's app and Query API answer. */\nexport const cloudAppHost = (region: PosthogRegion): string => `https://${region}.posthog.com`\n"],"mappings":";;;;;;;AAUA,MAAa,sBAA+D;CAC3E,kBAAkB;CAClB,kBAAkB;CAClB,mBAAmB;AACpB;;AAGA,MAAa,iBAAiB,YAC7B,oBAAoB,WAAW,OAAO,MAAM;;AAG7C,MAAa,gBAAgB,WAAkC,WAAW,OAAO"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { keys } from "../../translations/keys.js";
|
|
2
|
+
import { asTranslate } from "../../translations/server.js";
|
|
3
|
+
//#region src/adapters/posthog/credentials.ts
|
|
4
|
+
/** PostHog's key prefixes (posthog/models/utils.py): a project token is public, phx_ and phs_ keys are private. */
|
|
5
|
+
const PROJECT_TOKEN_PREFIX = "phc_";
|
|
6
|
+
const PRIVATE_KEY_PREFIXES = ["phx_", "phs_"];
|
|
7
|
+
/**
|
|
8
|
+
* Catches a project token pasted into the personal API key field. Empty passes: on a stored document
|
|
9
|
+
* it keeps the saved key.
|
|
10
|
+
*/
|
|
11
|
+
const validatePersonalApiKey = (value, { req }) => value?.trim().startsWith(PROJECT_TOKEN_PREFIX) ? asTranslate(req.t)(keys.providerErrorPosthogTokenAsApiKey) : true;
|
|
12
|
+
/**
|
|
13
|
+
* Catches a private key pasted into the project token field, which the tracker config serves to
|
|
14
|
+
* every visitor's browser.
|
|
15
|
+
*/
|
|
16
|
+
const validateProjectToken = (value, { req }) => PRIVATE_KEY_PREFIXES.some((prefix) => value?.trim().startsWith(prefix)) ? asTranslate(req.t)(keys.providerErrorPosthogKeyAsToken) : true;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { validatePersonalApiKey, validateProjectToken };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credentials.js","names":[],"sources":["../../../src/adapters/posthog/credentials.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** PostHog's key prefixes (posthog/models/utils.py): a project token is public, phx_ and phs_ keys are private. */\nconst PROJECT_TOKEN_PREFIX = 'phc_'\nconst PRIVATE_KEY_PREFIXES = ['phx_', 'phs_']\n\n/**\n * Catches a project token pasted into the personal API key field. Empty passes: on a stored document\n * it keeps the saved key.\n */\nexport const validatePersonalApiKey: TextFieldSingleValidation = (value, { req }) =>\n\tvalue?.trim().startsWith(PROJECT_TOKEN_PREFIX)\n\t\t? asTranslate(req.t)(keys.providerErrorPosthogTokenAsApiKey)\n\t\t: true\n\n/**\n * Catches a private key pasted into the project token field, which the tracker config serves to\n * every visitor's browser.\n */\nexport const validateProjectToken: TextFieldSingleValidation = (value, { req }) =>\n\tPRIVATE_KEY_PREFIXES.some((prefix) => value?.trim().startsWith(prefix))\n\t\t? asTranslate(req.t)(keys.providerErrorPosthogKeyAsToken)\n\t\t: true\n"],"mappings":";;;;AAKA,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB,CAAC,QAAQ,MAAM;;;;;AAM5C,MAAa,0BAAqD,OAAO,EAAE,UAC1E,OAAO,KAAK,EAAE,WAAW,oBAAoB,IAC1C,YAAY,IAAI,CAAC,EAAE,KAAK,iCAAiC,IACzD;;;;;AAMJ,MAAa,wBAAmD,OAAO,EAAE,UACxE,qBAAqB,MAAM,WAAW,OAAO,KAAK,EAAE,WAAW,MAAM,CAAC,IACnE,YAAY,IAAI,CAAC,EAAE,KAAK,8BAA8B,IACtD"}
|
|
@@ -15,7 +15,7 @@ interface PosthogConfig {
|
|
|
15
15
|
/** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
|
|
16
16
|
apiKey: string;
|
|
17
17
|
/**
|
|
18
|
-
* API address.
|
|
18
|
+
* API address. Unset, the `region`'s cloud, US Cloud without one; self-host is your instance's
|
|
19
19
|
* address, with the base path when a reverse proxy serves it under one.
|
|
20
20
|
*/
|
|
21
21
|
host?: string;
|
|
@@ -27,8 +27,8 @@ interface PosthogConfig {
|
|
|
27
27
|
*/
|
|
28
28
|
scopeProperty?: string;
|
|
29
29
|
/**
|
|
30
|
-
* PostHog Cloud region
|
|
31
|
-
* self-hosted `host` takes
|
|
30
|
+
* PostHog Cloud region: where capture goes and, with no `host`, where reads go. Derived from `host`
|
|
31
|
+
* when omitted. A self-hosted `host` takes both and ignores this.
|
|
32
32
|
*/
|
|
33
33
|
region?: 'us' | 'eu';
|
|
34
34
|
/**
|
|
@@ -10,12 +10,12 @@ import { readTime } from "../readTime.js";
|
|
|
10
10
|
import { dayIso, hourIso } from "../series.js";
|
|
11
11
|
import { upstreamJson } from "../upstream.js";
|
|
12
12
|
import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
|
|
13
|
+
import { cloudAppHost, cloudRegionOf } from "./cloud.js";
|
|
13
14
|
import { createProjectCheck } from "./projectCheck.js";
|
|
14
15
|
//#region src/adapters/posthog/posthog.ts
|
|
15
|
-
const US_CLOUD = "https://us.posthog.com";
|
|
16
16
|
const resolveRegion = (config) => {
|
|
17
17
|
if (config.region) return config.region;
|
|
18
|
-
return config.host
|
|
18
|
+
return config.host && cloudRegionOf(config.host) || "us";
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
21
|
* PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from
|
|
@@ -48,7 +48,7 @@ const captureHosts = (config) => {
|
|
|
48
48
|
assets: `https://${region}-assets.i.posthog.com`,
|
|
49
49
|
ingest: `https://${region}.i.posthog.com`,
|
|
50
50
|
cloud: true,
|
|
51
|
-
ui: ui ??
|
|
51
|
+
ui: ui ?? cloudAppHost(region)
|
|
52
52
|
};
|
|
53
53
|
};
|
|
54
54
|
/**
|
|
@@ -201,11 +201,11 @@ const FILTER_SQL = {
|
|
|
201
201
|
};
|
|
202
202
|
const SERIES_BUCKETS = {
|
|
203
203
|
day: {
|
|
204
|
-
|
|
204
|
+
expr: (zone) => `toStartOfDay(timestamp, ${zone})`,
|
|
205
205
|
isoOf: dayIso
|
|
206
206
|
},
|
|
207
207
|
hour: {
|
|
208
|
-
|
|
208
|
+
expr: (zone) => `toStartOfHour(toTimeZone(timestamp, ${zone}))`,
|
|
209
209
|
isoOf: hourIso
|
|
210
210
|
}
|
|
211
211
|
};
|
|
@@ -215,7 +215,7 @@ const SERIES_BUCKETS = {
|
|
|
215
215
|
*/
|
|
216
216
|
const utcDateTime = (d) => `toDateTime(${sqlString(d.toISOString().slice(0, 19).replace("T", " "))}, 'UTC')`;
|
|
217
217
|
function posthog(config) {
|
|
218
|
-
const host = withoutTrailingSlash(config.host ??
|
|
218
|
+
const host = withoutTrailingSlash(config.host ?? cloudAppHost(resolveRegion(config)));
|
|
219
219
|
const maxLookbackDays = config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730;
|
|
220
220
|
const withoutConsent = adapterWithoutConsent(config.withoutConsent, "posthog({ withoutConsent })", WITHOUT_CONSENT_LEVELS);
|
|
221
221
|
const capabilities = {
|
|
@@ -350,8 +350,8 @@ function posthog(config) {
|
|
|
350
350
|
};
|
|
351
351
|
const unit = !breakdown && (q.granularity === "day" || q.granularity === "hour") ? q.granularity : void 0;
|
|
352
352
|
if (unit) {
|
|
353
|
-
const {
|
|
354
|
-
const bucket =
|
|
353
|
+
const { expr, isoOf } = SERIES_BUCKETS[unit];
|
|
354
|
+
const bucket = expr(sqlString(q.timezone ?? "UTC"));
|
|
355
355
|
const [series, totals] = await Promise.all([runSql(`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`), fetchTotals()]);
|
|
356
356
|
const rows = [];
|
|
357
357
|
for (const row of series.results) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, ProxyRoute, SnippetMode } from '../../core/capture'\nimport { currentTime } from '../../core/clock'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { createProjectCheck } from './projectCheck'\n\nexport interface PosthogConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/**\n\t * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A\n\t * self-hosted `host` takes capture itself and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's\n\t * \"Cookieless tracking\" (Web analytics settings); `'off'` keeps PostHog opted out until then.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so\n * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded\n * posthog-js (no longer an array) is never replaced, so the client is initialised on it.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? `https://${region}.posthog.com`,\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview to the primary client.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first\n * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to\n * its own pageviews, is asked for outright.\n */\nconst NAMED_CLIENT_PAGEVIEWS = ['capture_pageview:false', 'capture_pageleave:true']\n\n/**\n * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to\n * rather than stopping. Started cookieless, it counts from the first pageview while opted out by\n * default, storing nothing, until the sink opts it in.\n */\nconst cookielessOptions = (mode: SnippetMode): string[] => [\n\t`cookieless_mode:${jsLiteral('on_reject')}`,\n\t...(mode === 'cookieless' ? ['opt_out_capturing_by_default:true'] : []),\n]\n\n/**\n * The scope stamped on each event as it is sent: switching between cookieless and full resets\n * PostHog's identity and every super-property `register` set with it.\n */\nconst scopeHook = (property: string, scope: string): string =>\n\t`before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined, named: boolean): string[] => [\n\t`api_host:${jsLiteral(path)}`,\n\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t'opt_out_persistence_by_default:true',\n]\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope, instance, mode = 'full', withoutConsent = false }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\tconst property = config.scopeProperty && scope ? config.scopeProperty : undefined\n\t\t\t// Stamped on every event rather than per call, so it rides the events a host captures itself,\n\t\t\t// which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tproperty && scope && !withoutConsent\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst options = [\n\t\t\t\t...initOptions(path, hosts.ui, named),\n\t\t\t\t...(withoutConsent ? cookielessOptions(mode) : []),\n\t\t\t\t...(withoutConsent && property && scope ? [scopeHook(property, scope)] : []),\n\t\t\t].join(',')\n\t\t\tconst name = named ? `,${jsLiteral(instance)}` : ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${options}}${name})${stamp}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t},\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\nconst METRIC_SQL_GOAL: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n\tevents: 'count()',\n}\n\n/**\n * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;\n * compared as text, it matches whether the project types the property as a boolean or not.\n */\nconst COOKIELESS_EVENT = \"toString(properties.$cookieless_mode) = 'true'\"\n\n/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** The HogQL function that buckets a timestamp. */\n\tfn: string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { fn: 'toStartOfDay', isoOf: dayIso },\n\thour: { fn: 'toStartOfHour', isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\n */\nconst utcDateTime = (d: Date): string =>\n\t`toDateTime(${sqlString(d.toISOString().slice(0, 19).replace('T', ' '))}, 'UTC')`\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? US_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'posthog({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\tlet fillsCountingSlot = true\n\tconst projectDropsCookieless = createProjectCheck({\n\t\thost,\n\t\tprojectId: config.projectId,\n\t\tapiKey: config.apiKey,\n\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t})\n\t/**\n\t * Whether a held slot this source fills may count cookielessly, which the project must accept:\n\t * the boot's answer for a config source, the factory's `withoutConsent` for a document's.\n\t */\n\tconst countsCookieless = (): boolean =>\n\t\tBoolean(config.projectToken) && withoutConsent !== 'off' && fillsCountingSlot\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(config, config.projectToken),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tregister(_config, context) {\n\t\t\tfillsCountingSlot = context?.adapterCountsWithoutConsent !== false\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dropped = countsCookieless()\n\t\t\t\t? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime())\n\t\t\t\t: Promise.resolve(undefined)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tlet cookieless = 0\n\t\t\t/** The result with what the read learnt about events counted without consent. */\n\t\t\tconst withConsentMeta = async (result: AnalyticsResult): Promise<AnalyticsResult> => {\n\t\t\t\tconst drops = await dropped\n\t\t\t\tconst counted = cookieless > 0\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\t...result.meta,\n\t\t\t\t\t\t...(counted && q.metrics.includes('visitors') ? { visitorsAre: 'sumOfDaily' } : {}),\n\t\t\t\t\t\t...(counted && !breakdown && q.metrics.includes('pageviews')\n\t\t\t\t\t\t\t? { withoutConsent: { pageviews: cookieless } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(drops ? { withoutConsentDropped: true } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn withConsentMeta(empty)\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tq.metrics.includes('conversions') ||\n\t\t\t\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(', ')})` : undefined\n\t\t\t// Counting the goals conditionally, rather than restricting the WHERE, keeps the\n\t\t\t// site metrics of a read that asks for both site-wide.\n\t\t\tconst metricSql: Partial<Record<MetricKey, string>> = {\n\t\t\t\t...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\n\t\t\tconst where = [\n\t\t\t\t...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\n\t\t\t\t`timestamp >= ${utcDateTime(q.dateRange.start)}`,\n\t\t\t\t`timestamp <= ${utcDateTime(q.dateRange.end)}`,\n\t\t\t]\n\t\t\t// Only the goal breakdown narrows the scan itself: its rows are the goals and\n\t\t\t// nothing else.\n\t\t\tif (goalBreakdown && eventInHint) {\n\t\t\t\twhere.push(eventInHint)\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\t\t\t// A column on the totals or breakdown query the read runs anyway, never a request of its\n\t\t\t// own. Visitors are counted on pageviews, except in a goal breakdown, which counts its rows.\n\t\t\tconst cookielessRows =\n\t\t\t\tscanAllEvents && !goalBreakdown\n\t\t\t\t\t? `event = '$pageview' AND ${COOKIELESS_EVENT}`\n\t\t\t\t\t: COOKIELESS_EVENT\n\t\t\tconst countsCookielessColumn =\n\t\t\t\tq.metrics.includes('visitors') || (!breakdown && q.metrics.includes('pageviews'))\n\t\t\tconst cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : ''\n\t\t\t/** Adds a result row's count of events counted without consent, after its metric columns. */\n\t\t\tconst tallyCookieless = (row: unknown[], offset: number): void => {\n\t\t\t\tif (countsCookielessColumn) {\n\t\t\t\t\tcookieless += vendorReading('pageviews', row[offset + exprs.length]) ?? 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns}${cookielessColumn} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn {}\n\t\t\t\t}\n\t\t\t\ttallyCookieless(row, 0)\n\t\t\t\treturn readRow(row, 0)\n\t\t\t}\n\n\t\t\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { fn, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? DEFAULT_TIMEZONE)})`\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn withConsentMeta({ rows, totals, meta })\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns}${cookielessColumn} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\t\ttallyCookieless(row, 1)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn withConsentMeta({ rows, totals: undefined, meta })\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn withConsentMeta({ rows: [{ metrics: totals }], totals, meta })\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAuFA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;AASA,MAAM,eACL;;AAGD,MAAM,eAAe,YAA6B;CACjD,MAAM,WAAW,WAAW,OAAO;CACnC,OAAO,aAAa,iBAAiB,SAAS,SAAS,cAAc;AACtE;;;;;AAaA,MAAM,gBAAgB,WAAwC;CAC7D,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,IAAI;CACrF,MAAM,KAAK,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,MAAM;CACvF,IAAI,SAAS,KAAA,KAAa,CAAC,YAAY,IAAI,GAC1C,OAAO;EAAE,QAAQ;EAAM,QAAQ;EAAM,OAAO;EAAO,GAAI,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,GAAG;CAAG;CAExF,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,QAAQ,WAAW,OAAO;EAC1B,QAAQ,WAAW,OAAO;EAC1B,OAAO;EACP,IAAI,MAAM,WAAW,OAAO;CAC7B;AACD;;;;;AAMA,MAAa,oCAAuD;CACnE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;AAEA,MAAM,cAAc,UACnB,MAAM,QACH,CAAC;CAAE,QAAQ;CAAQ,UAAU,GAAG,MAAM,OAAO;CAAO,MAAM;AAAO,CAAC,IAClE,kCAAkC,KAAK,UAAU;CACjD,QAAQ;CACR,UAAU,GAAG,MAAM,SAAS;CAC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,KAAK,CAAC;KAAE,CAAC;IAEnD;IACA,OAAO,gBAAgB;KAAE;KAAM;KAAQ;IAAK,CAAC;GAC9C;GAEA,IAAI,WAWH,OAAO,gBAAgB;IAAE,OAPI,MAHV,OAClB,UAAU,UAAU,MAAM,WAAW,UAAU,iBAAiB,GAAG,KAAK,uCAAuC,EAAE,SAAS,KAC3H,GACkC,QAAQ,KAAK,QAAQ;KACtD,gBAAgB,KAAK,CAAC;KACtB,OAAO;MACN,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;MAC1D,SAAS,QAAQ,KAAK,CAAC;KACxB;IACD,CAC4B;IAAG,QAAQ,KAAA;IAAW;GAAK,CAAC;GAGzD,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO,gBAAgB;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK,CAAC;EACrE;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, ProxyRoute, SnippetMode } from '../../core/capture'\nimport { currentTime } from '../../core/clock'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { cloudAppHost, cloudRegionOf, type PosthogRegion } from './cloud'\nimport { createProjectCheck } from './projectCheck'\n\nexport interface PosthogConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/**\n\t * API address. Unset, the `region`'s cloud, US Cloud without one; self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region: where capture goes and, with no `host`, where reads go. Derived from `host`\n\t * when omitted. A self-hosted `host` takes both and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's\n\t * \"Cookieless tracking\" (Web analytics settings); `'off'` keeps PostHog opted out until then.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\nconst resolveRegion = (config: PosthogConfig): PosthogRegion => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn (config.host && cloudRegionOf(config.host)) || 'us'\n}\n\n/**\n * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so\n * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded\n * posthog-js (no longer an array) is never replaced, so the client is initialised on it.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? cloudAppHost(region),\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview to the primary client.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first\n * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to\n * its own pageviews, is asked for outright.\n */\nconst NAMED_CLIENT_PAGEVIEWS = ['capture_pageview:false', 'capture_pageleave:true']\n\n/**\n * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to\n * rather than stopping. Started cookieless, it counts from the first pageview while opted out by\n * default, storing nothing, until the sink opts it in.\n */\nconst cookielessOptions = (mode: SnippetMode): string[] => [\n\t`cookieless_mode:${jsLiteral('on_reject')}`,\n\t...(mode === 'cookieless' ? ['opt_out_capturing_by_default:true'] : []),\n]\n\n/**\n * The scope stamped on each event as it is sent: switching between cookieless and full resets\n * PostHog's identity and every super-property `register` set with it.\n */\nconst scopeHook = (property: string, scope: string): string =>\n\t`before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined, named: boolean): string[] => [\n\t`api_host:${jsLiteral(path)}`,\n\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t'opt_out_persistence_by_default:true',\n]\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope, instance, mode = 'full', withoutConsent = false }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\tconst property = config.scopeProperty && scope ? config.scopeProperty : undefined\n\t\t\t// Stamped on every event rather than per call, so it rides the events a host captures itself,\n\t\t\t// which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tproperty && scope && !withoutConsent\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst options = [\n\t\t\t\t...initOptions(path, hosts.ui, named),\n\t\t\t\t...(withoutConsent ? cookielessOptions(mode) : []),\n\t\t\t\t...(withoutConsent && property && scope ? [scopeHook(property, scope)] : []),\n\t\t\t].join(',')\n\t\t\tconst name = named ? `,${jsLiteral(instance)}` : ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${options}}${name})${stamp}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t},\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\nconst METRIC_SQL_GOAL: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n\tevents: 'count()',\n}\n\n/**\n * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;\n * compared as text, it matches whether the project types the property as a boolean or not.\n */\nconst COOKIELESS_EVENT = \"toString(properties.$cookieless_mode) = 'true'\"\n\n/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** HogQL that buckets `timestamp` in the reporting zone, given as a quoted literal. */\n\texpr: (zone: string) => string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { expr: (zone) => `toStartOfDay(timestamp, ${zone})`, isoOf: dayIso },\n\t// HogQL's toStartOfHour takes one argument, unlike toStartOfDay, so the zone goes through toTimeZone.\n\thour: { expr: (zone) => `toStartOfHour(toTimeZone(timestamp, ${zone}))`, isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\n */\nconst utcDateTime = (d: Date): string =>\n\t`toDateTime(${sqlString(d.toISOString().slice(0, 19).replace('T', ' '))}, 'UTC')`\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? cloudAppHost(resolveRegion(config)))\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'posthog({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\tlet fillsCountingSlot = true\n\tconst projectDropsCookieless = createProjectCheck({\n\t\thost,\n\t\tprojectId: config.projectId,\n\t\tapiKey: config.apiKey,\n\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t})\n\t/**\n\t * Whether a held slot this source fills may count cookielessly, which the project must accept:\n\t * the boot's answer for a config source, the factory's `withoutConsent` for a document's.\n\t */\n\tconst countsCookieless = (): boolean =>\n\t\tBoolean(config.projectToken) && withoutConsent !== 'off' && fillsCountingSlot\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(config, config.projectToken),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tregister(_config, context) {\n\t\t\tfillsCountingSlot = context?.adapterCountsWithoutConsent !== false\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dropped = countsCookieless()\n\t\t\t\t? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime())\n\t\t\t\t: Promise.resolve(undefined)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tlet cookieless = 0\n\t\t\t/** The result with what the read learnt about events counted without consent. */\n\t\t\tconst withConsentMeta = async (result: AnalyticsResult): Promise<AnalyticsResult> => {\n\t\t\t\tconst drops = await dropped\n\t\t\t\tconst counted = cookieless > 0\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\t...result.meta,\n\t\t\t\t\t\t...(counted && q.metrics.includes('visitors') ? { visitorsAre: 'sumOfDaily' } : {}),\n\t\t\t\t\t\t...(counted && !breakdown && q.metrics.includes('pageviews')\n\t\t\t\t\t\t\t? { withoutConsent: { pageviews: cookieless } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(drops ? { withoutConsentDropped: true } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn withConsentMeta(empty)\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tq.metrics.includes('conversions') ||\n\t\t\t\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(', ')})` : undefined\n\t\t\t// Counting the goals conditionally, rather than restricting the WHERE, keeps the\n\t\t\t// site metrics of a read that asks for both site-wide.\n\t\t\tconst metricSql: Partial<Record<MetricKey, string>> = {\n\t\t\t\t...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\n\t\t\tconst where = [\n\t\t\t\t...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\n\t\t\t\t`timestamp >= ${utcDateTime(q.dateRange.start)}`,\n\t\t\t\t`timestamp <= ${utcDateTime(q.dateRange.end)}`,\n\t\t\t]\n\t\t\t// Only the goal breakdown narrows the scan itself: its rows are the goals and\n\t\t\t// nothing else.\n\t\t\tif (goalBreakdown && eventInHint) {\n\t\t\t\twhere.push(eventInHint)\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\t\t\t// A column on the totals or breakdown query the read runs anyway, never a request of its\n\t\t\t// own. Visitors are counted on pageviews, except in a goal breakdown, which counts its rows.\n\t\t\tconst cookielessRows =\n\t\t\t\tscanAllEvents && !goalBreakdown\n\t\t\t\t\t? `event = '$pageview' AND ${COOKIELESS_EVENT}`\n\t\t\t\t\t: COOKIELESS_EVENT\n\t\t\tconst countsCookielessColumn =\n\t\t\t\tq.metrics.includes('visitors') || (!breakdown && q.metrics.includes('pageviews'))\n\t\t\tconst cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : ''\n\t\t\t/** Adds a result row's count of events counted without consent, after its metric columns. */\n\t\t\tconst tallyCookieless = (row: unknown[], offset: number): void => {\n\t\t\t\tif (countsCookielessColumn) {\n\t\t\t\t\tcookieless += vendorReading('pageviews', row[offset + exprs.length]) ?? 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns}${cookielessColumn} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn {}\n\t\t\t\t}\n\t\t\t\ttallyCookieless(row, 0)\n\t\t\t\treturn readRow(row, 0)\n\t\t\t}\n\n\t\t\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { expr, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = expr(sqlString(q.timezone ?? DEFAULT_TIMEZONE))\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn withConsentMeta({ rows, totals, meta })\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns}${cookielessColumn} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\t\ttallyCookieless(row, 1)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn withConsentMeta({ rows, totals: undefined, meta })\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn withConsentMeta({ rows: [{ metrics: totals }], totals, meta })\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwFA,M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AAK,uCAAuC,EAAE,SAAS,KAC3H,GACkC,QAAQ,KAAK,QAAQ;KACtD,gBAAgB,KAAK,CAAC;KACtB,OAAO;MACN,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;MAC1D,SAAS,QAAQ,KAAK,CAAC;KACxB;IACD,CAC4B;IAAG,QAAQ,KAAA;IAAW;GAAK,CAAC;GAGzD,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO,gBAAgB;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK,CAAC;EACrE;CACD;AACD"}
|
|
@@ -6,10 +6,11 @@ import { asTranslate, labelForKey } from "../translations/server.js";
|
|
|
6
6
|
import { builtInStaticLabel } from "../translations/staticLabel.js";
|
|
7
7
|
import { validateMeasurementId } from "../adapters/ga4/measurementId.js";
|
|
8
8
|
import { validateScriptId } from "../adapters/plausible/scriptId.js";
|
|
9
|
+
import { validatePersonalApiKey, validateProjectToken } from "../adapters/posthog/credentials.js";
|
|
9
10
|
import { validateCurrency } from "../goals/currency.js";
|
|
10
11
|
import { overrideField } from "../plugin/collectionFields.js";
|
|
11
12
|
import { docScope } from "../plugin/scopeChange.js";
|
|
12
|
-
import { validateProviderHost } from "./hosts.js";
|
|
13
|
+
import { validatePosthogHost, validateProviderHost } from "./hosts.js";
|
|
13
14
|
import { PROVIDER_IDS } from "./factory.js";
|
|
14
15
|
import { retargetSecrets } from "./retarget.js";
|
|
15
16
|
import { takenInScope } from "./scopeUnique.js";
|
|
@@ -73,6 +74,7 @@ const secretField = (buildSecret, staticLabel, opts) => buildSecret({
|
|
|
73
74
|
name: opts.name,
|
|
74
75
|
type: "text",
|
|
75
76
|
label: labelForKey(opts.label),
|
|
77
|
+
...opts.validate ? { validate: opts.validate } : {},
|
|
76
78
|
admin: {
|
|
77
79
|
description: staticLabel(opts.help),
|
|
78
80
|
...opts.width ? { width: opts.width } : {}
|
|
@@ -103,11 +105,11 @@ const scopeField = (include) => include ? [{
|
|
|
103
105
|
label: labelForKey(keys.providerFieldScope),
|
|
104
106
|
admin: { hidden: true }
|
|
105
107
|
}] : [];
|
|
106
|
-
const hostField = (allowPrivateNetwork, access) => ({
|
|
108
|
+
const hostField = (allowPrivateNetwork, access, opts = {}) => ({
|
|
107
109
|
name: "host",
|
|
108
110
|
type: "text",
|
|
109
111
|
label: labelForKey(keys.providerFieldHost),
|
|
110
|
-
validate: validateProviderHost(allowPrivateNetwork),
|
|
112
|
+
validate: opts.validate ?? validateProviderHost(allowPrivateNetwork),
|
|
111
113
|
...access ? { access } : {},
|
|
112
114
|
admin: { description: labelForKey(keys.providerFieldHostHelp) }
|
|
113
115
|
});
|
|
@@ -264,11 +266,12 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
264
266
|
const buildSecret = options.buildSecret ?? plainSecret;
|
|
265
267
|
const access = connectionFieldAccess("analyticsProviderFields({ connectionAccess })", options.connectionAccess);
|
|
266
268
|
const allowPrivateNetwork = options.allowPrivateNetwork === true;
|
|
267
|
-
const apiKeyField = () => secretField(buildSecret, staticLabel, {
|
|
269
|
+
const apiKeyField = (validate) => secretField(buildSecret, staticLabel, {
|
|
268
270
|
name: "apiKey",
|
|
269
271
|
label: keys.providerFieldApiKey,
|
|
270
272
|
help: keys.providerFieldApiKeyHelp,
|
|
271
|
-
width: "50%"
|
|
273
|
+
width: "50%",
|
|
274
|
+
...validate ? { validate } : {}
|
|
272
275
|
});
|
|
273
276
|
return [
|
|
274
277
|
overrideField(nameField(), options.fields?.name),
|
|
@@ -349,11 +352,14 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
349
352
|
width: "50%",
|
|
350
353
|
help: keys.providerFieldProjectIdHelp,
|
|
351
354
|
access
|
|
352
|
-
}), ...apiKeyField()]
|
|
355
|
+
}), ...apiKeyField(validatePersonalApiKey)]
|
|
353
356
|
},
|
|
354
357
|
{
|
|
355
358
|
type: "row",
|
|
356
|
-
fields: [captureField("projectToken", keys.providerFieldProjectToken, {
|
|
359
|
+
fields: [captureField("projectToken", keys.providerFieldProjectToken, {
|
|
360
|
+
width: "50%",
|
|
361
|
+
validate: validateProjectToken
|
|
362
|
+
}), {
|
|
357
363
|
name: "region",
|
|
358
364
|
type: "select",
|
|
359
365
|
label: labelForKey(keys.providerFieldRegion),
|
|
@@ -375,7 +381,7 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
375
381
|
help: keys.providerFieldScopePropertyHelp,
|
|
376
382
|
access
|
|
377
383
|
}),
|
|
378
|
-
hostField(allowPrivateNetwork, access)
|
|
384
|
+
hostField(allowPrivateNetwork, access, { validate: validatePosthogHost(allowPrivateNetwork) })
|
|
379
385
|
]),
|
|
380
386
|
overrideField(withoutConsentField(staticLabel), options.fields?.withoutConsent)
|
|
381
387
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import {\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype Field,\n\ttype FieldAccess,\n\ttype PayloadRequest,\n\ttype SelectField,\n\ttype SelectFieldSingleValidation,\n\ttype TextareaField,\n\ttype TextField,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n\tvalidations,\n} from 'payload'\nimport { validateMeasurementId } from '../adapters/ga4/measurementId'\nimport { validateScriptId } from '../adapters/plausible/scriptId'\nimport { optionsObject } from '../core/optionChecks'\nimport { isOneOf, kindOf, listOf } from '../core/values'\nimport { validateCurrency } from '../goals/currency'\nimport { type CollectionFieldOverride, overrideField } from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport { keys, type SingularKey, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { type ProviderAccessArgs, providerCreateAccess, providerRowAccess } from './access'\nimport { PROVIDER_IDS, type ProviderId } from './factory'\nimport { validateProviderHost } from './hosts'\nimport { retargetSecrets } from './retarget'\nimport { takenInScope } from './scopeUnique'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** The list's note to a tenant reading the platform's source in `fallback`. */\nexport const PROVIDERS_LIST_NOTICE_COMPONENT = '@10x-media/analytics/client#ProvidersListNotice'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\n/**\n * Replaces a default field; it receives the plugin's own field to spread and may return any field\n * type (a `row`, a `collapsible`) that still holds a field of that name.\n */\nexport type ProviderFieldOverride = CollectionFieldOverride\n\nexport interface ProviderCollectionFieldOverrides {\n\tname?: ProviderFieldOverride\n\tprovider?: ProviderFieldOverride\n\tenabled?: ProviderFieldOverride\n\t/** The \"Default for this site\" checkbox, which only a scoped install's collection carries. */\n\tisDefault?: ProviderFieldOverride\n\t/** What a vendor source does without consent; empty follows `capture.withoutConsent`. */\n\twithoutConsent?: ProviderFieldOverride\n}\n\n/** Field access on the fields that decide where a provider document connects (`CONNECTION_PATHS`). */\nexport interface ConnectionFieldAccess {\n\tcreate?: FieldAccess\n\tupdate?: FieldAccess\n}\n\n/** One field access function for create and update alike, or `{ create, update }`. */\nexport type ConnectionAccess = FieldAccess | ConnectionFieldAccess\n\n/** `connectionAccess` in its object form, checked at boot; undefined while unset. */\nexport const connectionFieldAccess = (\n\tpath: string,\n\toption: ConnectionAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\tif (option === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof option === 'function') {\n\t\treturn { create: option, update: option }\n\t}\n\tconst halves = optionsObject(option, {\n\t\tpath,\n\t\tknown: ['create', 'update'],\n\t\texample: 'a function, or { create, update } with a function in each',\n\t})\n\tfor (const [half, access] of Object.entries(halves)) {\n\t\tif (access !== undefined && typeof access !== 'function') {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path}.${half} must be a field access function, got ${kindOf(access)}`\n\t\t\t)\n\t\t}\n\t}\n\tconst { create, update } = option\n\treturn { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n}\n\n/**\n * The provider types documents may be saved with: every type `available` serves, narrowed to\n * `option` in its order when given, checked at boot.\n */\nexport const servedProviderTypes = (\n\tpath: string,\n\toption: unknown,\n\tavailable: readonly ProviderId[] = PROVIDER_IDS\n): ProviderId[] => {\n\tif (option === undefined) {\n\t\treturn [...available]\n\t}\n\tif (!Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} must be a list of provider types such as ['plausible', 'umami'], got ${kindOf(option)}`\n\t\t)\n\t}\n\tconst listed: ProviderId[] = []\n\tfor (const type of option) {\n\t\tif (!isOneOf(PROVIDER_IDS, type)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path} lists ${kindOf(type)}, which is no provider type; use ${listOf(PROVIDER_IDS.map((id) => `\"${id}\"`))}`\n\t\t\t)\n\t\t}\n\t\tlisted.push(type)\n\t}\n\tconst served = [...new Set(listed)].filter((type) => available.includes(type))\n\tif (served.length === 0) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} leaves no provider type this install serves, which are ${listOf(available.map((id) => `\"${id}\"`))}; \"native\" needs native() in adapters`\n\t\t)\n\t}\n\treturn served\n}\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: ProviderCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\tbuildSecret: BuildSecretField\n\t/** The fields plugin's test for a sealed value, which tells a resent secret from a kept one. */\n\tisSealed: (value: unknown) => boolean\n\t/** `providers.hosts.allowPrivateNetwork`: the `host` fields accept `http://` too. */\n\tallowPrivateNetwork?: boolean\n\tconnectionAccess?: ConnectionFieldAccess\n\t/** The provider types a document may be saved with; every type when absent. */\n\ttypes?: readonly ProviderId[]\n\t/** Field access on `isDefault`, which a scoped install's collection carries. */\n\tdefaultAccess?: ConnectionFieldAccess\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n\t/** Mount the list's note on the platform fallback, for an install with a `fallback` policy. */\n\tlistNotice?: boolean\n}\n\nconst plainSecret: BuildSecretField = (source) => [source]\n\nconst textField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; help?: TranslationKey; access?: ConnectionFieldAccess } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.access ? { access: opts.access } : {}),\n\t...(opts.width || opts.help\n\t\t? {\n\t\t\t\tadmin: {\n\t\t\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\t\t\t...(opts.help ? { description: labelForKey(opts.help) } : {}),\n\t\t\t\t},\n\t\t\t}\n\t\t: {}),\n})\n\n/**\n * A sealed credential. Its help is a string per locale: Payload drops a function description from\n * the client field, which the write-only editor renders.\n */\nconst secretField = (\n\tbuildSecret: BuildSecretField,\n\tstaticLabel: StaticLabelFor,\n\topts: { name: string; label: TranslationKey; help: SingularKey; width?: string }\n): Field[] =>\n\tbuildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\tadmin: {\n\t\t\tdescription: staticLabel(opts.help),\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t},\n\t})\n\n/**\n * Public capture config, plain text because the tracker config serves it to the browser. An adapter\n * declares `capture` only once its public field is filled.\n */\nconst captureField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; validate?: TextFieldSingleValidation; help?: TranslationKey } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.validate ? { validate: opts.validate } : {}),\n\tadmin: {\n\t\tdescription: labelForKey(opts.help ?? keys.providerFieldCaptureHelp),\n\t\t...(opts.width ? { width: opts.width } : {}),\n\t},\n})\n\n/**\n * Only when `scopeField` names the plugin's own field: a host-owned scope field is the host's to\n * register, and shadowing it would store the scope twice.\n */\nconst scopeField = (include: boolean): Field[] =>\n\tinclude\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (\n\tallowPrivateNetwork: boolean,\n\taccess: ConnectionFieldAccess | undefined\n): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tvalidate: validateProviderHost(allowPrivateNetwork),\n\t...(access ? { access } : {}),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst currencyField = (name: string, help: TranslationKey): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldRevenueCurrency),\n\tvalidate: validateCurrency,\n\tadmin: { description: labelForKey(help) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The native choice configures nothing, so it gets a note in place of a settings group:\n * an unnamed group stores no data and reads as the section its siblings occupy.\n */\nconst nativeNote = (): Field => ({\n\ttype: 'group',\n\tlabel: labelForKey(keys.providerNameNative),\n\tadmin: {\n\t\tcondition: (data) => data?.provider === 'native',\n\t\tdescription: labelForKey(keys.providerNameNativeHelp),\n\t},\n\tfields: [],\n})\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.providerFieldName),\n\tadmin: { description: labelForKey(keys.providerFieldNameHelp) },\n})\n\nconst PROVIDER_NAMES: 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/**\n * Names the refusal of a stored type the install no longer serves (native() removed, `types`\n * narrowed), which the select's own check would only call an invalid selection.\n */\nconst validateServed =\n\t(types: readonly string[]): SelectFieldSingleValidation =>\n\t(value, options) =>\n\t\ttypeof value === 'string' && value !== '' && !types.includes(value)\n\t\t\t? asTranslate(options.req.t)(keys.providerErrorTypeUnserved)\n\t\t\t: validations.select(value, options)\n\n/**\n * The values a narrowed select offers: the served types, and a stored type no longer served so its\n * save is refused by name. Values only, since form state carries the result to the client, where\n * a label function cannot cross; Payload's select reads nothing else from it.\n */\nconst offeredTypes = (types: readonly ProviderId[], stored: unknown): ProviderId[] =>\n\tisOneOf(PROVIDER_IDS, stored) && !types.includes(stored) ? [...types, stored] : [...types]\n\n/**\n * Sits in the sidebar with `enabled`: every body field is conditional on the provider and\n * meaningless while `enabled` is off. The schema keeps every type (options, groups, a static\n * default while `native` leads), so narrowing the offer neither alters a column nor drops settings.\n */\nconst providerField = (\n\taccess: ConnectionFieldAccess | undefined,\n\tstaticLabel: StaticLabelFor,\n\ttypes: readonly ProviderId[]\n): SelectField => {\n\tconst [first = 'native'] = types\n\tconst narrowed = types.length < PROVIDER_IDS.length\n\treturn {\n\t\tname: 'provider',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\tdefaultValue: first === 'native' ? first : () => first,\n\t\t...(access ? { access } : {}),\n\t\t...(narrowed\n\t\t\t? {\n\t\t\t\t\tvalidate: validateServed(types),\n\t\t\t\t\tfilterOptions: ({ data }) => offeredTypes(types, data?.provider),\n\t\t\t\t}\n\t\t\t: {}),\n\t\toptions: PROVIDER_IDS.map((type) => ({\n\t\t\tlabel: labelForKey(PROVIDER_NAMES[type]),\n\t\t\tvalue: type,\n\t\t})),\n\t\t// `admin.description` on a select is read where a label function never runs.\n\t\tadmin: { position: 'sidebar', description: staticLabel(keys.providerFieldProviderHelp) },\n\t}\n}\n\n/**\n * A vendor document's own `withoutConsent`. Unset follows `capture.withoutConsent`; no option\n * stands for that, since an empty string is no portable enum value.\n */\nconst withoutConsentField = (staticLabel: StaticLabelFor): SelectField => ({\n\tname: 'withoutConsent',\n\ttype: 'select',\n\tlabel: labelForKey(keys.providerFieldWithoutConsent),\n\toptions: [\n\t\t{ label: staticLabel(keys.providerWithoutConsentCookieless), value: 'cookieless' },\n\t\t{ label: staticLabel(keys.providerWithoutConsentOff), value: 'off' },\n\t],\n\tadmin: {\n\t\tcondition: (data) => isOneOf(PROVIDER_IDS, data?.provider) && data?.provider !== 'native',\n\t\tdescription: staticLabel(keys.providerFieldWithoutConsentHelp),\n\t},\n})\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.providerFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldEnabledHelp) },\n})\n\nconst isDefaultField = (access: ConnectionFieldAccess | undefined): Field => ({\n\tname: 'isDefault',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t...(access ? { access } : {}),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldIsDefaultHelp) },\n})\n\n/**\n * At most one document per scope is the default, checked at collection level so a replaced\n * `isDefault` field keeps it. No index backs it: a unique one would also cover the unflagged rows.\n */\nconst checkSingleDefault = (args: BuildProvidersCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tif ((data?.isDefault ?? originalDoc?.isDefault) !== true) {\n\t\t\treturn data\n\t\t}\n\t\tif (await takenInScope(args, { data, originalDoc, req }, { isDefault: { equals: true } })) {\n\t\t\tthrow new ValidationError({\n\t\t\t\tcollection: args.slug,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.providerErrorDefaultTaken),\n\t\t\t\t\t\tpath: 'isDefault',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\treturn data\n\t}\n}\n\nexport interface ProviderFieldsOptions {\n\t/**\n\t * Seals each credential field, normally `encryptedField` from `@10x-media/fields` in write-only\n\t * mode. Left out, credentials are plain text and securing them is the host's job.\n\t */\n\tbuildSecret?: BuildSecretField\n\t/** Replaces one of the default fields, applied per field. */\n\tfields?: Omit<ProviderCollectionFieldOverrides, 'isDefault'>\n\t/** Adds the plugin's own hidden `scope` text field. Off by default. */\n\tscopeField?: boolean\n\t/**\n\t * Accepts `http://` in a `host` field, for a vendor on a private network. Set it together with\n\t * `providers.hosts.allowPrivateNetwork`, which lets the plugin connect there. Off, https only.\n\t */\n\tallowPrivateNetwork?: boolean\n\t/**\n\t * Field access on every `CONNECTION_PATHS` field except the scope field. One function for create\n\t * and update alike, or `{ create, update }`.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * The provider types the select offers, the first being its default; a document saved with any\n\t * other type is refused. Default: every type, `native` first.\n\t */\n\ttypes?: ProviderId[]\n}\n\n/** What the field list takes beyond the public options. */\ninterface FieldListArgs {\n\ttypes: readonly ProviderId[]\n\t/** The `isDefault` checkbox, overridden, placed after `enabled`; only a scoped collection has it. */\n\tisDefault?: Field\n}\n\n/**\n * Provider-settings fields alone, for a host that stores them elsewhere and feeds them back through\n * `providers.resolve`; {@link adapterFromProviderDoc} reads the result as is.\n */\nexport const analyticsProviderFields = (options: ProviderFieldsOptions = {}): Field[] =>\n\tproviderFields(options, builtInStaticLabel, {\n\t\ttypes: servedProviderTypes('analyticsProviderFields({ types })', options.types),\n\t})\n\nconst providerFields = (\n\toptions: ProviderFieldsOptions,\n\tstaticLabel: StaticLabelFor,\n\tlist: FieldListArgs\n): Field[] => {\n\tconst buildSecret = options.buildSecret ?? plainSecret\n\tconst access = connectionFieldAccess(\n\t\t'analyticsProviderFields({ connectionAccess })',\n\t\toptions.connectionAccess\n\t)\n\tconst allowPrivateNetwork = options.allowPrivateNetwork === true\n\tconst apiKeyField = (): Field[] =>\n\t\tsecretField(buildSecret, staticLabel, {\n\t\t\tname: 'apiKey',\n\t\t\tlabel: keys.providerFieldApiKey,\n\t\t\thelp: keys.providerFieldApiKeyHelp,\n\t\t\twidth: '50%',\n\t\t})\n\treturn [\n\t\toverrideField(nameField(), options.fields?.name),\n\t\toverrideField(providerField(access, staticLabel, list.types), options.fields?.provider),\n\t\toverrideField(enabledField(), options.fields?.enabled),\n\t\t...(list.isDefault ? [list.isDefault] : []),\n\t\t...scopeField(options.scopeField === true),\n\t\tnativeNote(),\n\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldSiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldDomainHelp,\n\t\t\t\t\t}),\n\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldScriptIdHelp,\n\t\t\t\t\t\tvalidate: validateScriptId,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\tcurrencyField('revenueCurrency', keys.providerFieldRevenueCurrencyHelp),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldWebsiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t...secretField(buildSecret, staticLabel, {\n\t\t\t\tname: 'token',\n\t\t\t\tlabel: keys.providerFieldToken,\n\t\t\t\thelp: keys.providerFieldTokenHelp,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldPropertyIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('clientEmail', keys.providerFieldClientEmail, {\n\t\t\t\thelp: keys.providerFieldClientEmailHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\tcaptureField('measurementId', keys.providerFieldMeasurementId, {\n\t\t\t\tvalidate: validateMeasurementId,\n\t\t\t}),\n\t\t\tcurrencyField('currency', keys.providerFieldGa4CurrencyHelp),\n\t\t\t...buildSecret({\n\t\t\t\tname: 'privateKey',\n\t\t\t\ttype: 'textarea',\n\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\tadmin: { description: staticLabel(keys.providerFieldPrivateKeyHelp) },\n\t\t\t}),\n\t\t]),\n\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, { width: '50%' }),\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(access ? { access } : {}),\n\t\t\t\t\t\tadmin: {\n\t\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\t\tdescription: staticLabel(keys.providerFieldRegionHelp),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('scopeProperty', keys.providerFieldScopeProperty, {\n\t\t\t\thelp: keys.providerFieldScopePropertyHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\toverrideField(withoutConsentField(staticLabel), options.fields?.withoutConsent),\n\t]\n}\n\n/**\n * Runtime provider-settings collection, one document per provider (and scope). Admin-only by\n * default; `access` overrides single operations, `overrides` reshapes the whole config last.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst staticLabel = args.staticLabel ?? builtInStaticLabel\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: staticLabel(keys.adminGroup),\n\t\t\tdescription: staticLabel(keys.providersCollectionDescription),\n\t\t\t...(args.listNotice ? { components: { beforeList: [PROVIDERS_LIST_NOTICE_COMPONENT] } } : {}),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\t...(args.scoped ? { beforeValidate: [checkSingleDefault(args)] } : {}),\n\t\t\tbeforeChange: [\n\t\t\t\tstampScope(args),\n\t\t\t\tretargetSecrets({ scopeField: args.scopeField, isSealed: args.isSealed }),\n\t\t\t],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: providerFields(\n\t\t\t{\n\t\t\t\tbuildSecret: args.buildSecret,\n\t\t\t\t...(args.fields ? { fields: args.fields } : {}),\n\t\t\t\tscopeField: args.scopeField === 'scope',\n\t\t\t\tallowPrivateNetwork: args.allowPrivateNetwork === true,\n\t\t\t\t...(args.connectionAccess ? { connectionAccess: args.connectionAccess } : {}),\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t\t{\n\t\t\t\ttypes: args.types ?? PROVIDER_IDS,\n\t\t\t\t// A default is picked per scope: an unscoped install has one site and nothing to pick.\n\t\t\t\t...(args.scoped\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tisDefault: overrideField(isDefaultField(args.defaultAccess), args.fields?.isDefault),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t}\n\t\t),\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+BA,MAAa,iBAAiB;;AAG9B,MAAa,kCAAkC;;AA+B/C,MAAa,yBACZ,MACA,WACuC;CACvC,IAAI,WAAW,KAAA,GACd;CAED,IAAI,OAAO,WAAW,YACrB,OAAO;EAAE,QAAQ;EAAQ,QAAQ;CAAO;CAEzC,MAAM,SAAS,cAAc,QAAQ;EACpC;EACA,OAAO,CAAC,UAAU,QAAQ;EAC1B,SAAS;CACV,CAAC;CACD,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,GACjD,IAAI,WAAW,KAAA,KAAa,OAAO,WAAW,YAC7C,MAAM,IAAI,MACT,cAAc,KAAK,GAAG,KAAK,wCAAwC,OAAO,MAAM,GACjF;CAGF,MAAM,EAAE,QAAQ,WAAW;CAC3B,OAAO;EAAE,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAI,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAAG;AACvE;;;;;AAMA,MAAa,uBACZ,MACA,QACA,YAAmC,iBACjB;CAClB,IAAI,WAAW,KAAA,GACd,OAAO,CAAC,GAAG,SAAS;CA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OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
|
|
1
|
+
{"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import {\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype Field,\n\ttype FieldAccess,\n\ttype PayloadRequest,\n\ttype SelectField,\n\ttype SelectFieldSingleValidation,\n\ttype TextareaField,\n\ttype TextField,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n\tvalidations,\n} from 'payload'\nimport { validateMeasurementId } from '../adapters/ga4/measurementId'\nimport { validateScriptId } from '../adapters/plausible/scriptId'\nimport { validatePersonalApiKey, validateProjectToken } from '../adapters/posthog/credentials'\nimport { optionsObject } from '../core/optionChecks'\nimport { isOneOf, kindOf, listOf } from '../core/values'\nimport { validateCurrency } from '../goals/currency'\nimport { type CollectionFieldOverride, overrideField } from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport { keys, type SingularKey, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { type ProviderAccessArgs, providerCreateAccess, providerRowAccess } from './access'\nimport { PROVIDER_IDS, type ProviderId } from './factory'\nimport { validatePosthogHost, validateProviderHost } from './hosts'\nimport { retargetSecrets } from './retarget'\nimport { takenInScope } from './scopeUnique'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** The list's note to a tenant reading the platform's source in `fallback`. */\nexport const PROVIDERS_LIST_NOTICE_COMPONENT = '@10x-media/analytics/client#ProvidersListNotice'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\n/**\n * Replaces a default field; it receives the plugin's own field to spread and may return any field\n * type (a `row`, a `collapsible`) that still holds a field of that name.\n */\nexport type ProviderFieldOverride = CollectionFieldOverride\n\nexport interface ProviderCollectionFieldOverrides {\n\tname?: ProviderFieldOverride\n\tprovider?: ProviderFieldOverride\n\tenabled?: ProviderFieldOverride\n\t/** The \"Default for this site\" checkbox, which only a scoped install's collection carries. */\n\tisDefault?: ProviderFieldOverride\n\t/** What a vendor source does without consent; empty follows `capture.withoutConsent`. */\n\twithoutConsent?: ProviderFieldOverride\n}\n\n/** Field access on the fields that decide where a provider document connects (`CONNECTION_PATHS`). */\nexport interface ConnectionFieldAccess {\n\tcreate?: FieldAccess\n\tupdate?: FieldAccess\n}\n\n/** One field access function for create and update alike, or `{ create, update }`. */\nexport type ConnectionAccess = FieldAccess | ConnectionFieldAccess\n\n/** `connectionAccess` in its object form, checked at boot; undefined while unset. */\nexport const connectionFieldAccess = (\n\tpath: string,\n\toption: ConnectionAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\tif (option === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof option === 'function') {\n\t\treturn { create: option, update: option }\n\t}\n\tconst halves = optionsObject(option, {\n\t\tpath,\n\t\tknown: ['create', 'update'],\n\t\texample: 'a function, or { create, update } with a function in each',\n\t})\n\tfor (const [half, access] of Object.entries(halves)) {\n\t\tif (access !== undefined && typeof access !== 'function') {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path}.${half} must be a field access function, got ${kindOf(access)}`\n\t\t\t)\n\t\t}\n\t}\n\tconst { create, update } = option\n\treturn { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n}\n\n/**\n * The provider types documents may be saved with: every type `available` serves, narrowed to\n * `option` in its order when given, checked at boot.\n */\nexport const servedProviderTypes = (\n\tpath: string,\n\toption: unknown,\n\tavailable: readonly ProviderId[] = PROVIDER_IDS\n): ProviderId[] => {\n\tif (option === undefined) {\n\t\treturn [...available]\n\t}\n\tif (!Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} must be a list of provider types such as ['plausible', 'umami'], got ${kindOf(option)}`\n\t\t)\n\t}\n\tconst listed: ProviderId[] = []\n\tfor (const type of option) {\n\t\tif (!isOneOf(PROVIDER_IDS, type)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path} lists ${kindOf(type)}, which is no provider type; use ${listOf(PROVIDER_IDS.map((id) => `\"${id}\"`))}`\n\t\t\t)\n\t\t}\n\t\tlisted.push(type)\n\t}\n\tconst served = [...new Set(listed)].filter((type) => available.includes(type))\n\tif (served.length === 0) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} leaves no provider type this install serves, which are ${listOf(available.map((id) => `\"${id}\"`))}; \"native\" needs native() in adapters`\n\t\t)\n\t}\n\treturn served\n}\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: ProviderCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\tbuildSecret: BuildSecretField\n\t/** The fields plugin's test for a sealed value, which tells a resent secret from a kept one. */\n\tisSealed: (value: unknown) => boolean\n\t/** `providers.hosts.allowPrivateNetwork`: the `host` fields accept `http://` too. */\n\tallowPrivateNetwork?: boolean\n\tconnectionAccess?: ConnectionFieldAccess\n\t/** The provider types a document may be saved with; every type when absent. */\n\ttypes?: readonly ProviderId[]\n\t/** Field access on `isDefault`, which a scoped install's collection carries. */\n\tdefaultAccess?: ConnectionFieldAccess\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n\t/** Mount the list's note on the platform fallback, for an install with a `fallback` policy. */\n\tlistNotice?: boolean\n}\n\nconst plainSecret: BuildSecretField = (source) => [source]\n\nconst textField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; help?: TranslationKey; access?: ConnectionFieldAccess } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.access ? { access: opts.access } : {}),\n\t...(opts.width || opts.help\n\t\t? {\n\t\t\t\tadmin: {\n\t\t\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\t\t\t...(opts.help ? { description: labelForKey(opts.help) } : {}),\n\t\t\t\t},\n\t\t\t}\n\t\t: {}),\n})\n\n/**\n * A sealed credential. Its help is a string per locale: Payload drops a function description from\n * the client field, which the write-only editor renders.\n */\nconst secretField = (\n\tbuildSecret: BuildSecretField,\n\tstaticLabel: StaticLabelFor,\n\topts: {\n\t\tname: string\n\t\tlabel: TranslationKey\n\t\thelp: SingularKey\n\t\twidth?: string\n\t\tvalidate?: TextFieldSingleValidation\n\t}\n): Field[] =>\n\tbuildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\t...(opts.validate ? { validate: opts.validate } : {}),\n\t\tadmin: {\n\t\t\tdescription: staticLabel(opts.help),\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t},\n\t})\n\n/**\n * Public capture config, plain text because the tracker config serves it to the browser. An adapter\n * declares `capture` only once its public field is filled.\n */\nconst captureField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; validate?: TextFieldSingleValidation; help?: TranslationKey } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.validate ? { validate: opts.validate } : {}),\n\tadmin: {\n\t\tdescription: labelForKey(opts.help ?? keys.providerFieldCaptureHelp),\n\t\t...(opts.width ? { width: opts.width } : {}),\n\t},\n})\n\n/**\n * Only when `scopeField` names the plugin's own field: a host-owned scope field is the host's to\n * register, and shadowing it would store the scope twice.\n */\nconst scopeField = (include: boolean): Field[] =>\n\tinclude\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (\n\tallowPrivateNetwork: boolean,\n\taccess: ConnectionFieldAccess | undefined,\n\topts: { validate?: TextFieldSingleValidation } = {}\n): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tvalidate: opts.validate ?? validateProviderHost(allowPrivateNetwork),\n\t...(access ? { access } : {}),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst currencyField = (name: string, help: TranslationKey): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldRevenueCurrency),\n\tvalidate: validateCurrency,\n\tadmin: { description: labelForKey(help) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The native choice configures nothing, so it gets a note in place of a settings group:\n * an unnamed group stores no data and reads as the section its siblings occupy.\n */\nconst nativeNote = (): Field => ({\n\ttype: 'group',\n\tlabel: labelForKey(keys.providerNameNative),\n\tadmin: {\n\t\tcondition: (data) => data?.provider === 'native',\n\t\tdescription: labelForKey(keys.providerNameNativeHelp),\n\t},\n\tfields: [],\n})\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.providerFieldName),\n\tadmin: { description: labelForKey(keys.providerFieldNameHelp) },\n})\n\nconst PROVIDER_NAMES: 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/**\n * Names the refusal of a stored type the install no longer serves (native() removed, `types`\n * narrowed), which the select's own check would only call an invalid selection.\n */\nconst validateServed =\n\t(types: readonly string[]): SelectFieldSingleValidation =>\n\t(value, options) =>\n\t\ttypeof value === 'string' && value !== '' && !types.includes(value)\n\t\t\t? asTranslate(options.req.t)(keys.providerErrorTypeUnserved)\n\t\t\t: validations.select(value, options)\n\n/**\n * The values a narrowed select offers: the served types, and a stored type no longer served so its\n * save is refused by name. Values only, since form state carries the result to the client, where\n * a label function cannot cross; Payload's select reads nothing else from it.\n */\nconst offeredTypes = (types: readonly ProviderId[], stored: unknown): ProviderId[] =>\n\tisOneOf(PROVIDER_IDS, stored) && !types.includes(stored) ? [...types, stored] : [...types]\n\n/**\n * Sits in the sidebar with `enabled`: every body field is conditional on the provider and\n * meaningless while `enabled` is off. The schema keeps every type (options, groups, a static\n * default while `native` leads), so narrowing the offer neither alters a column nor drops settings.\n */\nconst providerField = (\n\taccess: ConnectionFieldAccess | undefined,\n\tstaticLabel: StaticLabelFor,\n\ttypes: readonly ProviderId[]\n): SelectField => {\n\tconst [first = 'native'] = types\n\tconst narrowed = types.length < PROVIDER_IDS.length\n\treturn {\n\t\tname: 'provider',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\tdefaultValue: first === 'native' ? first : () => first,\n\t\t...(access ? { access } : {}),\n\t\t...(narrowed\n\t\t\t? {\n\t\t\t\t\tvalidate: validateServed(types),\n\t\t\t\t\tfilterOptions: ({ data }) => offeredTypes(types, data?.provider),\n\t\t\t\t}\n\t\t\t: {}),\n\t\toptions: PROVIDER_IDS.map((type) => ({\n\t\t\tlabel: labelForKey(PROVIDER_NAMES[type]),\n\t\t\tvalue: type,\n\t\t})),\n\t\t// `admin.description` on a select is read where a label function never runs.\n\t\tadmin: { position: 'sidebar', description: staticLabel(keys.providerFieldProviderHelp) },\n\t}\n}\n\n/**\n * A vendor document's own `withoutConsent`. Unset follows `capture.withoutConsent`; no option\n * stands for that, since an empty string is no portable enum value.\n */\nconst withoutConsentField = (staticLabel: StaticLabelFor): SelectField => ({\n\tname: 'withoutConsent',\n\ttype: 'select',\n\tlabel: labelForKey(keys.providerFieldWithoutConsent),\n\toptions: [\n\t\t{ label: staticLabel(keys.providerWithoutConsentCookieless), value: 'cookieless' },\n\t\t{ label: staticLabel(keys.providerWithoutConsentOff), value: 'off' },\n\t],\n\tadmin: {\n\t\tcondition: (data) => isOneOf(PROVIDER_IDS, data?.provider) && data?.provider !== 'native',\n\t\tdescription: staticLabel(keys.providerFieldWithoutConsentHelp),\n\t},\n})\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.providerFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldEnabledHelp) },\n})\n\nconst isDefaultField = (access: ConnectionFieldAccess | undefined): Field => ({\n\tname: 'isDefault',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t...(access ? { access } : {}),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldIsDefaultHelp) },\n})\n\n/**\n * At most one document per scope is the default, checked at collection level so a replaced\n * `isDefault` field keeps it. No index backs it: a unique one would also cover the unflagged rows.\n */\nconst checkSingleDefault = (args: BuildProvidersCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tif ((data?.isDefault ?? originalDoc?.isDefault) !== true) {\n\t\t\treturn data\n\t\t}\n\t\tif (await takenInScope(args, { data, originalDoc, req }, { isDefault: { equals: true } })) {\n\t\t\tthrow new ValidationError({\n\t\t\t\tcollection: args.slug,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.providerErrorDefaultTaken),\n\t\t\t\t\t\tpath: 'isDefault',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\treturn data\n\t}\n}\n\nexport interface ProviderFieldsOptions {\n\t/**\n\t * Seals each credential field, normally `encryptedField` from `@10x-media/fields` in write-only\n\t * mode. Left out, credentials are plain text and securing them is the host's job.\n\t */\n\tbuildSecret?: BuildSecretField\n\t/** Replaces one of the default fields, applied per field. */\n\tfields?: Omit<ProviderCollectionFieldOverrides, 'isDefault'>\n\t/** Adds the plugin's own hidden `scope` text field. Off by default. */\n\tscopeField?: boolean\n\t/**\n\t * Accepts `http://` in a `host` field, for a vendor on a private network. Set it together with\n\t * `providers.hosts.allowPrivateNetwork`, which lets the plugin connect there. Off, https only.\n\t */\n\tallowPrivateNetwork?: boolean\n\t/**\n\t * Field access on every `CONNECTION_PATHS` field except the scope field. One function for create\n\t * and update alike, or `{ create, update }`.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * The provider types the select offers, the first being its default; a document saved with any\n\t * other type is refused. Default: every type, `native` first.\n\t */\n\ttypes?: ProviderId[]\n}\n\n/** What the field list takes beyond the public options. */\ninterface FieldListArgs {\n\ttypes: readonly ProviderId[]\n\t/** The `isDefault` checkbox, overridden, placed after `enabled`; only a scoped collection has it. */\n\tisDefault?: Field\n}\n\n/**\n * Provider-settings fields alone, for a host that stores them elsewhere and feeds them back through\n * `providers.resolve`; {@link adapterFromProviderDoc} reads the result as is.\n */\nexport const analyticsProviderFields = (options: ProviderFieldsOptions = {}): Field[] =>\n\tproviderFields(options, builtInStaticLabel, {\n\t\ttypes: servedProviderTypes('analyticsProviderFields({ types })', options.types),\n\t})\n\nconst providerFields = (\n\toptions: ProviderFieldsOptions,\n\tstaticLabel: StaticLabelFor,\n\tlist: FieldListArgs\n): Field[] => {\n\tconst buildSecret = options.buildSecret ?? plainSecret\n\tconst access = connectionFieldAccess(\n\t\t'analyticsProviderFields({ connectionAccess })',\n\t\toptions.connectionAccess\n\t)\n\tconst allowPrivateNetwork = options.allowPrivateNetwork === true\n\tconst apiKeyField = (validate?: TextFieldSingleValidation): Field[] =>\n\t\tsecretField(buildSecret, staticLabel, {\n\t\t\tname: 'apiKey',\n\t\t\tlabel: keys.providerFieldApiKey,\n\t\t\thelp: keys.providerFieldApiKeyHelp,\n\t\t\twidth: '50%',\n\t\t\t...(validate ? { validate } : {}),\n\t\t})\n\treturn [\n\t\toverrideField(nameField(), options.fields?.name),\n\t\toverrideField(providerField(access, staticLabel, list.types), options.fields?.provider),\n\t\toverrideField(enabledField(), options.fields?.enabled),\n\t\t...(list.isDefault ? [list.isDefault] : []),\n\t\t...scopeField(options.scopeField === true),\n\t\tnativeNote(),\n\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldSiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldDomainHelp,\n\t\t\t\t\t}),\n\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldScriptIdHelp,\n\t\t\t\t\t\tvalidate: validateScriptId,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\tcurrencyField('revenueCurrency', keys.providerFieldRevenueCurrencyHelp),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldWebsiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t...secretField(buildSecret, staticLabel, {\n\t\t\t\tname: 'token',\n\t\t\t\tlabel: keys.providerFieldToken,\n\t\t\t\thelp: keys.providerFieldTokenHelp,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldPropertyIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('clientEmail', keys.providerFieldClientEmail, {\n\t\t\t\thelp: keys.providerFieldClientEmailHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\tcaptureField('measurementId', keys.providerFieldMeasurementId, {\n\t\t\t\tvalidate: validateMeasurementId,\n\t\t\t}),\n\t\t\tcurrencyField('currency', keys.providerFieldGa4CurrencyHelp),\n\t\t\t...buildSecret({\n\t\t\t\tname: 'privateKey',\n\t\t\t\ttype: 'textarea',\n\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\tadmin: { description: staticLabel(keys.providerFieldPrivateKeyHelp) },\n\t\t\t}),\n\t\t]),\n\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(validatePersonalApiKey),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\tvalidate: validateProjectToken,\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(access ? { access } : {}),\n\t\t\t\t\t\tadmin: {\n\t\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\t\tdescription: staticLabel(keys.providerFieldRegionHelp),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('scopeProperty', keys.providerFieldScopeProperty, {\n\t\t\t\thelp: keys.providerFieldScopePropertyHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access, {\n\t\t\t\tvalidate: validatePosthogHost(allowPrivateNetwork),\n\t\t\t}),\n\t\t]),\n\t\toverrideField(withoutConsentField(staticLabel), options.fields?.withoutConsent),\n\t]\n}\n\n/**\n * Runtime provider-settings collection, one document per provider (and scope). Admin-only by\n * default; `access` overrides single operations, `overrides` reshapes the whole config last.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst staticLabel = args.staticLabel ?? builtInStaticLabel\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: staticLabel(keys.adminGroup),\n\t\t\tdescription: staticLabel(keys.providersCollectionDescription),\n\t\t\t...(args.listNotice ? { components: { beforeList: [PROVIDERS_LIST_NOTICE_COMPONENT] } } : {}),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\t...(args.scoped ? { beforeValidate: [checkSingleDefault(args)] } : {}),\n\t\t\tbeforeChange: [\n\t\t\t\tstampScope(args),\n\t\t\t\tretargetSecrets({ scopeField: args.scopeField, isSealed: args.isSealed }),\n\t\t\t],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: providerFields(\n\t\t\t{\n\t\t\t\tbuildSecret: args.buildSecret,\n\t\t\t\t...(args.fields ? { fields: args.fields } : {}),\n\t\t\t\tscopeField: args.scopeField === 'scope',\n\t\t\t\tallowPrivateNetwork: args.allowPrivateNetwork === true,\n\t\t\t\t...(args.connectionAccess ? { connectionAccess: args.connectionAccess } : {}),\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t\t{\n\t\t\t\ttypes: args.types ?? PROVIDER_IDS,\n\t\t\t\t// A default is picked per scope: an unscoped install has one site and nothing to pick.\n\t\t\t\t...(args.scoped\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tisDefault: overrideField(isDefaultField(args.defaultAccess), args.fields?.isDefault),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t}\n\t\t),\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,MAAa,iBAAiB;;AAG9B,MAAa,kCAAkC;;AA+B/C,MAAa,yBACZ,MACA,WACuC;CACvC,IAAI,WAAW,KAAA,GACd;CAED,IAAI,OAAO,WAAW,YACrB,OAAO;EAAE,QAAQ;EAAQ,QAAQ;CAAO;CAEzC,MAAM,SAAS,cAAc,QAAQ;EACpC;EACA,OAAO,CAAC,UAAU,QAAQ;EAC1B,SAAS;CACV,CAAC;CACD,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,GACjD,IAAI,WAAW,KAAA,KAAa,OAAO,WAAW,YAC7C,MAAM,IAAI,MACT,cAAc,KAAK,GAAG,KAAK,wCAAwC,OAAO,MAAM,GACjF;CAGF,MAAM,EAAE,QAAQ,WAAW;CAC3B,OAAO;EAAE,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAI,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAAG;AACvE;;;;;AAMA,MAAa,uBACZ,MACA,QACA,YAAmC,iBACjB;CAClB,IAAI,WAAW,KAAA,GACd,OAAO,CAAC,GAAG,SAAS;CAErB,IAAI,CAAC,MAAM,QAAQ,MAAM,GACxB,MAAM,IAAI,MACT,cAAc,KAAK,wEAAwE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;GAErB,GAAI,KAAK,SACN,EACA,WAAW,cAAc,eAAe,KAAK,aAAa,GAAG,KAAK,QAAQ,SAAS,EACpF,IACC,CAAC;EACL,CACD;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
|
package/dist/providers/hosts.js
CHANGED
|
@@ -2,6 +2,7 @@ import { isRecord, onlyKeys } from "../core/values.js";
|
|
|
2
2
|
import { keys } from "../translations/keys.js";
|
|
3
3
|
import { parseHttpUrl, parseOrigin } from "../net/origin.js";
|
|
4
4
|
import { asTranslate } from "../translations/server.js";
|
|
5
|
+
import { POSTHOG_CLOUD_HOSTS, cloudRegionOf } from "../adapters/posthog/cloud.js";
|
|
5
6
|
//#region src/providers/hosts.ts
|
|
6
7
|
/**
|
|
7
8
|
* Each vendor's own cloud, always allowed: its default origin, Umami Cloud's app address, and
|
|
@@ -10,11 +11,7 @@ import { asTranslate } from "../translations/server.js";
|
|
|
10
11
|
const CLOUD_ORIGINS = {
|
|
11
12
|
plausible: ["https://plausible.io"],
|
|
12
13
|
umami: ["https://api.umami.is", "https://cloud.umami.is"],
|
|
13
|
-
posthog:
|
|
14
|
-
"https://us.posthog.com",
|
|
15
|
-
"https://eu.posthog.com",
|
|
16
|
-
"https://app.posthog.com"
|
|
17
|
-
]
|
|
14
|
+
posthog: Object.keys(POSTHOG_CLOUD_HOSTS).map((hostname) => `https://${hostname}`)
|
|
18
15
|
};
|
|
19
16
|
const DEFAULT_HOST_POLICY = {
|
|
20
17
|
allow: [],
|
|
@@ -122,7 +119,18 @@ const validateProviderHost = (allowPrivateNetwork) => (value, { req }) => {
|
|
|
122
119
|
if (!("problem" in parsed)) return true;
|
|
123
120
|
return asTranslate(req.t)(parsed.problem === "insecure" ? keys.providerErrorHostInsecure : keys.providerErrorHostFormat);
|
|
124
121
|
};
|
|
122
|
+
/**
|
|
123
|
+
* A PostHog document's Host, after `validateProviderHost`: a PostHog Cloud address must be the cloud
|
|
124
|
+
* its Region names, or capture would go to one region and reads to the other.
|
|
125
|
+
*/
|
|
126
|
+
const validatePosthogHost = (allowPrivateNetwork) => (value, args) => {
|
|
127
|
+
const address = validateProviderHost(allowPrivateNetwork)(value, args);
|
|
128
|
+
if (address !== true || !value) return address;
|
|
129
|
+
const region = isRecord(args.siblingData) ? args.siblingData.region : void 0;
|
|
130
|
+
const cloud = cloudRegionOf(value);
|
|
131
|
+
return cloud && (region === "us" || region === "eu") && cloud !== region ? asTranslate(args.req.t)(keys.providerErrorPosthogHostRegion) : true;
|
|
132
|
+
};
|
|
125
133
|
//#endregion
|
|
126
|
-
export { checkDocumentHost, resolveHostPolicy, validateProviderHost };
|
|
134
|
+
export { checkDocumentHost, resolveHostPolicy, validatePosthogHost, validateProviderHost };
|
|
127
135
|
|
|
128
136
|
//# sourceMappingURL=hosts.js.map
|