@10x-media/analytics 1.0.0-beta.8 → 1.0.0-beta.9
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 +70 -0
- package/LICENSE +21 -21
- package/README.md +3 -3
- package/dist/adapters/ga4/eventName.d.ts +15 -0
- package/dist/adapters/ga4/eventName.js +19 -0
- package/dist/adapters/ga4/eventName.js.map +1 -0
- package/dist/adapters/ga4/ga4.d.ts +5 -0
- package/dist/adapters/ga4/ga4.js +178 -70
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +15 -0
- package/dist/adapters/ga4/measurementId.js.map +1 -0
- package/dist/adapters/goalRead.js +126 -0
- package/dist/adapters/goalRead.js.map +1 -0
- package/dist/adapters/plausible/plausible.d.ts +15 -0
- package/dist/adapters/plausible/plausible.js +110 -42
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +47 -25
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +8 -0
- package/dist/adapters/umami/umami.js +237 -28
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/BarList.js +8 -2
- package/dist/charts/BarList.js.map +1 -1
- package/dist/core/cacheKey.js +11 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/capabilities.js +7 -2
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +1 -1
- package/dist/core/contract.d.ts +32 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +8 -2
- package/dist/core/options.js +4 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/serverEvent.d.ts +4 -2
- package/dist/core/serverEvent.js.map +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/client.d.ts +5 -2
- package/dist/exports/client.js +4 -1
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/tracker.js +2 -1
- package/dist/exports/types.d.ts +2 -1
- package/dist/exports/types.js +2 -1
- package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
- package/dist/fields/config/FilterDimensionSelectField.js +77 -0
- package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
- package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
- package/dist/fields/config/FilterOperatorSelectField.js +75 -0
- package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
- package/dist/fields/config/MetricSelectField.js +1 -1
- package/dist/fields/config/SourceSelectField.js +1 -1
- package/dist/fields/config/sourcesState.js +19 -3
- package/dist/fields/config/sourcesState.js.map +1 -1
- package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
- package/dist/fields/config/useAnalyticsSources.js +9 -6
- package/dist/fields/config/useAnalyticsSources.js.map +1 -1
- package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
- package/dist/fields/config/useFilterCapabilities.js +52 -0
- package/dist/fields/config/useFilterCapabilities.js.map +1 -0
- package/dist/fields/readForDocument.js +16 -4
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +36 -0
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/eventScan.js +25 -0
- package/dist/native/eventScan.js.map +1 -0
- package/dist/native/ingest/browser.js +47 -0
- package/dist/native/ingest/browser.js.map +1 -0
- package/dist/native/ingest/flushBatch.js +26 -26
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/language.js +14 -0
- package/dist/native/ingest/language.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.d.ts +6 -0
- package/dist/native/ingest/normalizeEvent.js +32 -5
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/referrer.js +48 -0
- package/dist/native/ingest/referrer.js.map +1 -0
- package/dist/native/ingest/serverTrack.js +1 -0
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/source.d.ts +7 -0
- package/dist/native/ingest/source.js +139 -14
- package/dist/native/ingest/source.js.map +1 -1
- package/dist/native/ingest/utm.js +33 -0
- package/dist/native/ingest/utm.js.map +1 -0
- package/dist/native/nativeAdapter.js +32 -26
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +14 -1
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/rollups/bucketKey.js +15 -0
- package/dist/native/rollups/bucketKey.js.map +1 -0
- package/dist/native/rollups/bumpRollups.js +116 -0
- package/dist/native/rollups/bumpRollups.js.map +1 -0
- package/dist/native/rollups/deltas.js +30 -15
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/native/rollups/insertManyIfNew.js +93 -0
- package/dist/native/rollups/insertManyIfNew.js.map +1 -0
- package/dist/next/captureRewrites.d.ts +3 -2
- package/dist/next/captureRewrites.js +3 -2
- package/dist/next/captureRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +26 -7
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/goalHint.d.ts +1 -0
- package/dist/plugin/goalHint.js +24 -0
- package/dist/plugin/goalHint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +19 -12
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/realtimeEndpoint.js +40 -15
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/responses.js +17 -0
- package/dist/plugin/responses.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +10 -3
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/collection.js +14 -4
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +4 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/query/response.d.ts +4 -1
- package/dist/query/response.js +11 -0
- package/dist/query/response.js.map +1 -0
- package/dist/surfacing/engine.js +1 -1
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/testing/memoryAdapter.js +0 -1
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/createTracker.js +13 -1
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/sinks/ga4.d.ts +21 -0
- package/dist/tracker/sinks/ga4.js +26 -0
- package/dist/tracker/sinks/ga4.js.map +1 -0
- package/dist/tracker/types.d.ts +5 -0
- package/dist/translations/ar.js +30 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +30 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +30 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +30 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +30 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +30 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +29 -0
- package/dist/translations/keys.js +30 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +30 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +7 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +30 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +30 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +30 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +30 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsViewClient.js +13 -2
- package/dist/view/AnalyticsViewClient.js.map +1 -1
- package/dist/view/gating.js +40 -3
- package/dist/view/gating.js.map +1 -1
- package/dist/view/labels.js +21 -1
- package/dist/view/labels.js.map +1 -1
- package/dist/view/sections/Breakdowns.js +78 -38
- package/dist/view/sections/Breakdowns.js.map +1 -1
- package/dist/view/sections/FilterChips.js +8 -3
- package/dist/view/sections/FilterChips.js.map +1 -1
- package/dist/view/sections/GoalsPanel.js +2 -1
- package/dist/view/sections/GoalsPanel.js.map +1 -1
- package/dist/view/sections/RealtimeStrip.js +4 -1
- package/dist/view/sections/RealtimeStrip.js.map +1 -1
- package/dist/view/sections/Toolbar.js +10 -3
- package/dist/view/sections/Toolbar.js.map +1 -1
- package/dist/view/sections/Trend.js +8 -2
- package/dist/view/sections/Trend.js.map +1 -1
- package/dist/view/state.js +7 -2
- package/dist/view/state.js.map +1 -1
- package/dist/view/useViewQueries.js +6 -3
- package/dist/view/useViewQueries.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +30 -3
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +30 -3
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/RealtimeCounter.d.ts +4 -0
- package/dist/widgets/RealtimeCounter.js +10 -1
- package/dist/widgets/RealtimeCounter.js.map +1 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/comparison.js +15 -1
- package/dist/widgets/comparison.js.map +1 -1
- package/dist/widgets/defaults.d.ts +6 -2
- package/dist/widgets/defaults.js +72 -25
- package/dist/widgets/defaults.js.map +1 -1
- package/dist/widgets/filterCaption.js +27 -0
- package/dist/widgets/filterCaption.js.map +1 -0
- package/dist/widgets/filterField.d.ts +19 -0
- package/dist/widgets/filterField.js +75 -0
- package/dist/widgets/filterField.js.map +1 -0
- package/dist/widgets/prepareWidgetRead.d.ts +7 -0
- package/dist/widgets/prepareWidgetRead.js +74 -0
- package/dist/widgets/prepareWidgetRead.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +12 -2
- package/dist/widgets/readForWidget.js +34 -49
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
- package/dist/widgets/readForWidgetBreakdown.js +29 -42
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +11 -1
- package/dist/widgets/readForWidgetGoals.js +44 -30
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
- package/dist/widgets/readForWidgetRealtime.js +21 -20
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +11 -1
- package/dist/widgets/readForWidgetSeries.js +38 -49
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/readMeta.js +18 -0
- package/dist/widgets/readMeta.js.map +1 -0
- package/dist/widgets/registerWidgets.js +5 -2
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.js +5 -2
- package/dist/widgets/viewLink.js.map +1 -1
- package/package.json +5 -5
- package/dist/native/rollups/applyDistinctDeltas.js +0 -9
- package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
- package/dist/native/rollups/bumpRollup.js +0 -73
- package/dist/native/rollups/bumpRollup.js.map +0 -1
- package/dist/native/rollups/insertIfNew.js +0 -53
- package/dist/native/rollups/insertIfNew.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\tendDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAyBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;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AAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tFilterOperator,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tmergeGoalTotals,\n\tproviderMetricKeys,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { dayIso } from '../series'\nimport { ga4EventName } from './eventName'\nimport { MEASUREMENT_ID_PATTERN } from './measurementId'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Public measurement id (`G-XXXXXXX`). Setting it turns on capture: the tag is loaded\n\t * from googletagmanager.com and booted with gtag.\n\t */\n\tmeasurementId?: string\n}\n\n/**\n * Google's documented install snippet (https://developers.google.com/tag-platform/gtagjs/install):\n * the inline publishes `dataLayer` and `gtag` and configures the measurement id, then the tag\n * loads from googletagmanager.com. Inline first is Google's own ordering for consent mode, and\n * it leaves the queue defined even when the tag itself is blocked. The tag is served from\n * Google's CDN with the id in the query string, so there is nothing to proxy and `routes`\n * stays empty; the snippet is rendered from an absolute `src` and the slot's proxy mount\n * answers 404.\n */\nfunction buildCapture(measurementId: string): CaptureSupport {\n\tconst id = JSON.stringify(measurementId)\n\treturn {\n\t\tproxy: { routes: [] },\n\t\tsnippet: () => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag(\"js\",new Date());gtag(\"config\",${id})`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsrc: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,\n\t\t\t\t\tasync: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'ga4', measurementId },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n\tgoal: 'eventName',\n}\n\n/**\n * Metrics GA4 answers only for a goal-restricted read. A goal matches the GA4 event named by\n * its normalized slug, since GA4 refuses the kebab-case slug itself. `keyEvents` counts\n * events the property itself marks as key events, so an event that is a goal here but not\n * marked there reports 0.\n */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions'])\n\n/**\n * The hint's slugs keyed by the GA4 event name each one normalizes to, which is both the\n * `eventName` list the goal request sends and the way its rows map back. Two slugs can\n * normalize to one GA4 event, which GA4 counts once: the first hint slug owns those rows.\n */\nconst goalSlugsByEventName = (slugs: string[]): Map<string, string> => {\n\tconst byName = new Map<string, string>()\n\tfor (const slug of slugs) {\n\t\tconst name = ga4EventName(slug)\n\t\tif (!byName.has(name)) {\n\t\t\tbyName.set(name, slug)\n\t\t}\n\t}\n\treturn byName\n}\n\ntype StringMatchType = 'EXACT' | 'CONTAINS' | 'FULL_REGEXP'\n\n/**\n * FULL_REGEXP is a full match, so a pattern has to cover the whole value (`/docs/.*`, not\n * `^/docs`). PARTIAL_REGEXP exists but is not the contract's `matches`.\n */\nconst MATCH_TYPE_MAP: Record<FilterOperator, StringMatchType> = {\n\teq: 'EXACT',\n\tcontains: 'CONTAINS',\n\tmatches: 'FULL_REGEXP',\n}\n\n// caseSensitive is explicit on every string filter because the Data API defaults it to\n// false: `contains` stays insensitive, matching the native source and Umami's ilike, while\n// `eq` and `matches` compare literally.\nconst CASE_SENSITIVE: Record<StringMatchType, boolean> = {\n\tEXACT: true,\n\tCONTAINS: false,\n\tFULL_REGEXP: true,\n}\n\nconst stringFilter = (\n\tfieldName: string,\n\tmatchType: StringMatchType,\n\tvalue: string\n): protos.google.analytics.data.v1beta.IFilterExpression => ({\n\tfilter: {\n\t\tfieldName,\n\t\tstringFilter: { matchType, value, caseSensitive: CASE_SENSITIVE[matchType] },\n\t},\n})\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n// `goal` is a breakdown, not a filter: the read's own goal slugs own the eventName clause.\nconst ga4Filters: ReadonlySet<DimensionKey> = new Set(\n\t[...ga4Dimensions].filter((dimension) => dimension !== 'goal')\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Filters,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\tconst measurementId = config.measurementId\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\t// An id that is not a bare token is dropped rather than escaped: it lands in an inline\n\t\t// script and in the tag URL, and no legitimate measurement id needs anything else.\n\t\t...(measurementId && MEASUREMENT_ID_PATTERN.test(measurementId)\n\t\t\t? { capture: buildCapture(measurementId) }\n\t\t\t: {}),\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'ga4', q, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted,\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteKeys = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalKeys = providerMetricKeys(goalMetrics, METRIC_MAP)\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\t\t\t// Set when GA4 rejects a goal report the site report survived, so the rows keep their\n\t\t\t// site metrics and lose only their conversions.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'ga4',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst readMetrics = (\n\t\t\t\tms: MetricKey[],\n\t\t\t\tkeys: string[],\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of ms) {\n\t\t\t\t\tconst idx = keys.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push(stringFilter('pagePath', 'EXACT', q.path))\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push(stringFilter('hostName', 'EXACT', q.hostname))\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = ga4Filters.has(filter.dimension)\n\t\t\t\t\t? DIMENSION_MAP[filter.dimension]\n\t\t\t\t\t: undefined\n\t\t\t\tif (!fieldName) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push(stringFilter(fieldName, MATCH_TYPE_MAP[filter.operator], filter.value))\n\t\t\t}\n\t\t\tconst goalSlugs = slugs ? goalSlugsByEventName(slugs) : null\n\t\t\tconst goalExprs = goalSlugs\n\t\t\t\t? [\n\t\t\t\t\t\t...filterExprs,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfilter: {\n\t\t\t\t\t\t\t\tfieldName: 'eventName',\n\t\t\t\t\t\t\t\tinListFilter: { values: [...goalSlugs.keys()], caseSensitive: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: filterExprs\n\t\t\tconst asFilter = (\n\t\t\t\texprs: protos.google.analytics.data.v1beta.IFilterExpression[]\n\t\t\t): protos.google.analytics.data.v1beta.IFilterExpression | undefined =>\n\t\t\t\texprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: exprs.length === 1\n\t\t\t\t\t\t? exprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: exprs } }\n\n\t\t\tconst request = (\n\t\t\t\tmetrics: string[],\n\t\t\t\texprs: protos.google.analytics.data.v1beta.IFilterExpression[],\n\t\t\t\textra: protos.google.analytics.data.v1beta.IRunReportRequest\n\t\t\t): protos.google.analytics.data.v1beta.IRunReportRequest => {\n\t\t\t\tconst dimensionFilter = asFilter(exprs)\n\t\t\t\treturn {\n\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\tdateRanges: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstartDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tendDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tmetrics: metrics.map((name) => ({ name })),\n\t\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t\t\t...extra,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tinterface PairedReport {\n\t\t\t\trows: GoalKeyedRow[]\n\t\t\t\ttotals: Partial<Record<MetricKey, number>> | undefined\n\t\t\t}\n\n\t\t\tconst rowKeys = (row: protos.google.analytics.data.v1beta.IRow): string[] =>\n\t\t\t\t(row.dimensionValues ?? []).map((value) => value.value ?? '')\n\n\t\t\t/**\n\t\t\t * One report shape run twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal report has no counterpart for carries no conversions: no key event fired there.\n\t\t\t * `limit` is the site report's alone, since a goal ranked outside its top N would\n\t\t\t * otherwise be lost from the union.\n\t\t\t */\n\t\t\tconst runPair = async (\n\t\t\t\textra: protos.google.analytics.data.v1beta.IRunReportRequest,\n\t\t\t\tlimit?: number\n\t\t\t): Promise<PairedReport> => {\n\t\t\t\tconst runReport = async (\n\t\t\t\t\tmetrics: string[],\n\t\t\t\t\texprs: protos.google.analytics.data.v1beta.IFilterExpression[],\n\t\t\t\t\treportExtra: protos.google.analytics.data.v1beta.IRunReportRequest\n\t\t\t\t) => {\n\t\t\t\t\tconst [response] = await client.runReport(request(metrics, exprs, reportExtra))\n\t\t\t\t\treturn response\n\t\t\t\t}\n\t\t\t\t// A goal breakdown restricts its own rows, so its one report carries the hint too.\n\t\t\t\tconst siteExprs = goalBreakdown ? goalExprs : filterExprs\n\t\t\t\tconst siteExtra = limit ? { ...extra, limit } : extra\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteKeys.length ? () => runReport(siteKeys, siteExprs, siteExtra) : undefined,\n\t\t\t\t\tgoals: goalKeys.length ? () => runReport(goalKeys, goalExprs, extra) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\tconst keyed = (\n\t\t\t\t\tresponse: protos.google.analytics.data.v1beta.IRunReportResponse | undefined,\n\t\t\t\t\tms: MetricKey[],\n\t\t\t\t\tkeys: string[]\n\t\t\t\t): GoalKeyedRow[] | undefined =>\n\t\t\t\t\tresponse?.rows?.map((row) => ({\n\t\t\t\t\t\tkeys: rowKeys(row),\n\t\t\t\t\t\tmetrics: readMetrics(ms, keys, row),\n\t\t\t\t\t})) ?? (response ? [] : undefined)\n\t\t\t\tconst siteTotals = pair.site?.totals?.[0]\n\t\t\t\tconst goalTotals = pair.goals?.totals?.[0]\n\t\t\t\treturn {\n\t\t\t\t\trows: mergeGoalRows(\n\t\t\t\t\t\tkeyed(pair.site, siteMetrics, siteKeys),\n\t\t\t\t\t\tkeyed(pair.goals, goalMetrics, goalKeys)\n\t\t\t\t\t),\n\t\t\t\t\ttotals: mergeGoalTotals(\n\t\t\t\t\t\tsiteTotals ? readMetrics(siteMetrics, siteKeys, siteTotals) : undefined,\n\t\t\t\t\t\tgoalTotals ? readMetrics(goalMetrics, goalKeys, goalTotals) : undefined\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst report = await runPair({\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of report.rows) {\n\t\t\t\t\tconst ymd = row.keys[0] ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: row.metrics })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals: report.totals ?? {}, meta: meta() }\n\t\t\t}\n\n\t\t\tconst report = await runPair(\n\t\t\t\tproviderDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {},\n\t\t\t\tq.limit\n\t\t\t)\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = report.rows[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = report.rows.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tconst value = row.keys[idx] ?? ''\n\t\t\t\t\t// A `goal` row reports the slug it was asked for; an `event` row reports GA4's own\n\t\t\t\t\t// event name, even though both read the same dimension.\n\t\t\t\t\tdimValues[d] = d === 'goal' ? (goalSlugs?.get(value) ?? value) : value\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsDA,SAAS,aAAa,eAAuC;CAC5D,MAAM,KAAK,KAAK,UAAU,aAAa;CACvC,OAAO;EACN,OAAO,EAAE,QAAQ,CAAC,EAAE;EACpB,gBAAgB,EACf,SAAS,CACR,EACC,QAAQ,uHAAuH,GAAG,GACnI,GACA;GACC,KAAK,+CAA+C,mBAAmB,aAAa;GACpF,OAAO;EACR,CACD,EACD;EACA,QAAQ;GAAE,MAAM;GAAO;EAAc;CACtC;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;CACP,MAAM;AACP;;;;;;;AAQA,MAAM,eAAuC,IAAI,IAAI,CAAC,aAAa,CAAC;;;;;;AAOpE,MAAM,wBAAwB,UAAyC;CACtE,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,OAAO,aAAa,IAAI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AAM,IAAI,KAAK,MAAM;KAC3B,MAAM,KAAK,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,CAAC,GAAG;KAC5E,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,IAAI;KAAQ,CAAC;IAEnD;IACA,OAAO;KAAE;KAAM,QAAQ,OAAO,UAAU,CAAC;KAAG,MAAM,KAAK;IAAE;GAC1D;GAEA,MAAM,SAAS,MAAM,QACpB,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC,GAChF,EAAE,KACH;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,OAAO,KAAK,IAAI,WAAW,CAAC;IAC3C,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAaA,OAAO;IAAE,MAXoB,OAAO,KAAK,KAAK,QAAQ;KACrD,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,MAAM,QAAQ,IAAI,KAAK,QAAQ;MAG/B,UAAU,KAAK,MAAM,SAAU,WAAW,IAAI,KAAK,KAAK,QAAS;KAClE;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,IAAI;KAAQ;IACtD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { keys } from "../../translations/keys.js";
|
|
2
|
+
import { asTranslate } from "../../translations/server.js";
|
|
3
|
+
//#region src/adapters/ga4/measurementId.ts
|
|
4
|
+
/** What Google's own ids look like, and all the inline snippet and the tag URL may carry. */
|
|
5
|
+
const MEASUREMENT_ID_PATTERN = /^[A-Za-z0-9-]+$/;
|
|
6
|
+
/**
|
|
7
|
+
* Its own module so the providers collection can validate the id on the same terms the
|
|
8
|
+
* adapter admits it, without importing the adapter and its `@google-analytics/data` peer.
|
|
9
|
+
* Empty is allowed: the id is optional and only turns capture on.
|
|
10
|
+
*/
|
|
11
|
+
const validateMeasurementId = (value, { req }) => !value || MEASUREMENT_ID_PATTERN.test(value) ? true : asTranslate(req.t)(keys.providerErrorMeasurementId);
|
|
12
|
+
//#endregion
|
|
13
|
+
export { MEASUREMENT_ID_PATTERN, validateMeasurementId };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=measurementId.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"measurementId.js","names":[],"sources":["../../../src/adapters/ga4/measurementId.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** What Google's own ids look like, and all the inline snippet and the tag URL may carry. */\nexport const MEASUREMENT_ID_PATTERN = /^[A-Za-z0-9-]+$/\n\n/**\n * Its own module so the providers collection can validate the id on the same terms the\n * adapter admits it, without importing the adapter and its `@google-analytics/data` peer.\n * Empty is allowed: the id is optional and only turns capture on.\n */\nexport const validateMeasurementId: TextFieldSingleValidation = (value, { req }) =>\n\t!value || MEASUREMENT_ID_PATTERN.test(value)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.providerErrorMeasurementId)\n"],"mappings":";;;;AAKA,MAAa,yBAAyB;;;;;;AAOtC,MAAa,yBAAoD,OAAO,EAAE,UACzE,CAAC,SAAS,uBAAuB,KAAK,KAAK,IACxC,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,0BAA0B"}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
//#region src/adapters/goalRead.ts
|
|
2
|
+
const goalHint = (q) => {
|
|
3
|
+
if (q.goalSlugs === void 0) return null;
|
|
4
|
+
if (q.goalSlugs === "unresolved") return "unresolved";
|
|
5
|
+
return { slugs: [...new Set(q.goalSlugs.filter((slug) => slug.length > 0))] };
|
|
6
|
+
};
|
|
7
|
+
/** The slugs a provider request filters by, or null when the hint names none to filter by. */
|
|
8
|
+
const hintSlugs = (hint) => hint === null || hint === "unresolved" || hint.slugs.length === 0 ? null : hint.slugs;
|
|
9
|
+
/**
|
|
10
|
+
* Whether goal numbers are missing because the hint failed or was never set, rather than
|
|
11
|
+
* because the install configured no goals, which is an empty result and not a failure.
|
|
12
|
+
*/
|
|
13
|
+
const hintFailed = (hint) => hint === null || hint === "unresolved";
|
|
14
|
+
/** A `goal` breakdown a provider was asked for without the hint that defines its rows. */
|
|
15
|
+
const goalsUnresolvedResult = (provider, q, meta) => ({
|
|
16
|
+
rows: [],
|
|
17
|
+
meta: {
|
|
18
|
+
provider,
|
|
19
|
+
fetchedAt: q.dateRange.end.toISOString(),
|
|
20
|
+
...meta,
|
|
21
|
+
goalsUnresolved: true
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* The answer a `goal` breakdown owes before it reads, or null when its hint names rows to
|
|
26
|
+
* read. A failed or absent hint is reported with `goalsUnresolved`; an install that
|
|
27
|
+
* configured no goals gets the same empty rows without the flag.
|
|
28
|
+
*/
|
|
29
|
+
const emptyGoalBreakdown = ({ provider, q, hint, meta }) => {
|
|
30
|
+
if (hintSlugs(hint) !== null) return null;
|
|
31
|
+
return hintFailed(hint) ? goalsUnresolvedResult(provider, q, meta) : {
|
|
32
|
+
rows: [],
|
|
33
|
+
meta: {
|
|
34
|
+
provider,
|
|
35
|
+
fetchedAt: q.dateRange.end.toISOString(),
|
|
36
|
+
...meta
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* How a provider that serves goal metrics only under a goal filter splits one read in two.
|
|
42
|
+
* A goal breakdown restricts every row it returns, so its single request carries everything;
|
|
43
|
+
* anywhere else the goal metrics need a request of their own, because filtering the whole
|
|
44
|
+
* read would scope the site metrics to goal hits as well.
|
|
45
|
+
*/
|
|
46
|
+
const splitGoalMetrics = ({ wanted, goalOnly, goalBreakdown, hint }) => {
|
|
47
|
+
if (goalBreakdown) return {
|
|
48
|
+
siteMetrics: wanted,
|
|
49
|
+
goalMetrics: [],
|
|
50
|
+
unresolved: false
|
|
51
|
+
};
|
|
52
|
+
const goalMetrics = wanted.filter((m) => goalOnly.has(m));
|
|
53
|
+
return {
|
|
54
|
+
siteMetrics: wanted.filter((m) => !goalOnly.has(m)),
|
|
55
|
+
goalMetrics: hintSlugs(hint) === null ? [] : goalMetrics,
|
|
56
|
+
unresolved: goalMetrics.length > 0 && hintFailed(hint)
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Provider metric names for a contract metric list, deduped: several contract metrics can
|
|
61
|
+
* alias one provider metric (sessions and visits both map to Plausible's `visits`), so each
|
|
62
|
+
* is read back from its provider key's position rather than from the request index.
|
|
63
|
+
*/
|
|
64
|
+
const providerMetricKeys = (metrics, map) => [...new Set(metrics.map((m) => map[m]))];
|
|
65
|
+
/**
|
|
66
|
+
* The two halves of a pair read unioned by dimension key. A row only the site request
|
|
67
|
+
* returned keeps its conversions absent (no goal fired there); a row only the goal request
|
|
68
|
+
* returned is appended carrying its goal metrics alone, since the site request answers a
|
|
69
|
+
* different ranking and its own limit may have cut the row off.
|
|
70
|
+
*/
|
|
71
|
+
const mergeGoalRows = (site, goals) => {
|
|
72
|
+
if (!site) return goals ?? [];
|
|
73
|
+
if (!goals) return site;
|
|
74
|
+
const byKey = new Map(goals.map((row) => [JSON.stringify(row.keys), row]));
|
|
75
|
+
return [...site.map((row) => {
|
|
76
|
+
const key = JSON.stringify(row.keys);
|
|
77
|
+
const goalRow = byKey.get(key);
|
|
78
|
+
if (!goalRow) return row;
|
|
79
|
+
byKey.delete(key);
|
|
80
|
+
return {
|
|
81
|
+
keys: row.keys,
|
|
82
|
+
metrics: {
|
|
83
|
+
...row.metrics,
|
|
84
|
+
...goalRow.metrics
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}), ...byKey.values()];
|
|
88
|
+
};
|
|
89
|
+
/** The same union over a pair's totals rows, which carry no dimensions to key on. */
|
|
90
|
+
const mergeGoalTotals = (site, goals) => site || goals ? {
|
|
91
|
+
...site,
|
|
92
|
+
...goals
|
|
93
|
+
} : void 0;
|
|
94
|
+
/**
|
|
95
|
+
* One request shape issued twice, plainly and goal-filtered. Sequential rather than
|
|
96
|
+
* concurrent: the engine takes a single limiter permit per `adapter.query`, so a parallel
|
|
97
|
+
* pair would exceed the provider's declared concurrency. A goal request the provider rejects
|
|
98
|
+
* (a property with no key events, a site with no revenue goals) costs the read its
|
|
99
|
+
* conversions rather than all of it, unless there is no site half left to serve.
|
|
100
|
+
*/
|
|
101
|
+
const readGoalPair = async ({ site, goals }) => {
|
|
102
|
+
const siteResponse = site ? await site() : void 0;
|
|
103
|
+
if (!goals) return {
|
|
104
|
+
site: siteResponse,
|
|
105
|
+
goals: void 0,
|
|
106
|
+
failed: false
|
|
107
|
+
};
|
|
108
|
+
try {
|
|
109
|
+
return {
|
|
110
|
+
site: siteResponse,
|
|
111
|
+
goals: await goals(),
|
|
112
|
+
failed: false
|
|
113
|
+
};
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (!site) throw error;
|
|
116
|
+
return {
|
|
117
|
+
site: siteResponse,
|
|
118
|
+
goals: void 0,
|
|
119
|
+
failed: true
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
export { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs, mergeGoalRows, mergeGoalTotals, providerMetricKeys, readGoalPair, splitGoalMetrics };
|
|
125
|
+
|
|
126
|
+
//# sourceMappingURL=goalRead.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"goalRead.js","names":[],"sources":["../../src/adapters/goalRead.ts"],"sourcesContent":["import type { AnalyticsQuery, AnalyticsResult, MetricKey } from '../core/contract'\n\n/**\n * What a read tells a provider about this install's goals: the slugs its goal rows are\n * restricted to (possibly none, for an install that configured none), `'unresolved'` when\n * the resolver failed, or null when the caller set no hint at all. Nothing in a provider\n * marks which of its events are this install's goals, so a provider adapter counts\n * conversions for the hinted names and for no others.\n */\nexport type GoalHint = { slugs: string[] } | 'unresolved' | null\n\nexport const goalHint = (q: AnalyticsQuery): GoalHint => {\n\tif (q.goalSlugs === undefined) {\n\t\treturn null\n\t}\n\tif (q.goalSlugs === 'unresolved') {\n\t\treturn 'unresolved'\n\t}\n\treturn { slugs: [...new Set(q.goalSlugs.filter((slug) => slug.length > 0))] }\n}\n\n/** The slugs a provider request filters by, or null when the hint names none to filter by. */\nexport const hintSlugs = (hint: GoalHint): string[] | null =>\n\thint === null || hint === 'unresolved' || hint.slugs.length === 0 ? null : hint.slugs\n\n/**\n * Whether goal numbers are missing because the hint failed or was never set, rather than\n * because the install configured no goals, which is an empty result and not a failure.\n */\nexport const hintFailed = (hint: GoalHint): boolean => hint === null || hint === 'unresolved'\n\n/** Meta a goal read still has to report beside its empty rows (unapplied filters, sampling). */\ntype GoalsUnresolvedMeta = Omit<\n\tAnalyticsResult['meta'],\n\t'provider' | 'fetchedAt' | 'goalsUnresolved'\n>\n\n/** A `goal` breakdown a provider was asked for without the hint that defines its rows. */\nexport const goalsUnresolvedResult = (\n\tprovider: string,\n\tq: AnalyticsQuery,\n\tmeta?: GoalsUnresolvedMeta\n): AnalyticsResult => ({\n\trows: [],\n\tmeta: {\n\t\tprovider,\n\t\tfetchedAt: q.dateRange.end.toISOString(),\n\t\t...meta,\n\t\tgoalsUnresolved: true,\n\t},\n})\n\n/**\n * The answer a `goal` breakdown owes before it reads, or null when its hint names rows to\n * read. A failed or absent hint is reported with `goalsUnresolved`; an install that\n * configured no goals gets the same empty rows without the flag.\n */\nexport const emptyGoalBreakdown = ({\n\tprovider,\n\tq,\n\thint,\n\tmeta,\n}: {\n\tprovider: string\n\tq: AnalyticsQuery\n\thint: GoalHint\n\tmeta?: GoalsUnresolvedMeta\n}): AnalyticsResult | null => {\n\tif (hintSlugs(hint) !== null) {\n\t\treturn null\n\t}\n\treturn hintFailed(hint)\n\t\t? goalsUnresolvedResult(provider, q, meta)\n\t\t: { rows: [], meta: { provider, fetchedAt: q.dateRange.end.toISOString(), ...meta } }\n}\n\nexport interface GoalMetricSplit {\n\t/** Metrics the plain request asks for. */\n\tsiteMetrics: MetricKey[]\n\t/** Metrics only the goal-filtered request can answer; empty when the hint names no goal. */\n\tgoalMetrics: MetricKey[]\n\t/** The read wanted goal numbers it had no hint to ask for. */\n\tunresolved: boolean\n}\n\n/**\n * How a provider that serves goal metrics only under a goal filter splits one read in two.\n * A goal breakdown restricts every row it returns, so its single request carries everything;\n * anywhere else the goal metrics need a request of their own, because filtering the whole\n * read would scope the site metrics to goal hits as well.\n */\nexport const splitGoalMetrics = ({\n\twanted,\n\tgoalOnly,\n\tgoalBreakdown,\n\thint,\n}: {\n\twanted: MetricKey[]\n\tgoalOnly: ReadonlySet<MetricKey>\n\tgoalBreakdown: boolean\n\thint: GoalHint\n}): GoalMetricSplit => {\n\tif (goalBreakdown) {\n\t\treturn { siteMetrics: wanted, goalMetrics: [], unresolved: false }\n\t}\n\tconst goalMetrics = wanted.filter((m) => goalOnly.has(m))\n\treturn {\n\t\tsiteMetrics: wanted.filter((m) => !goalOnly.has(m)),\n\t\tgoalMetrics: hintSlugs(hint) === null ? [] : goalMetrics,\n\t\tunresolved: goalMetrics.length > 0 && hintFailed(hint),\n\t}\n}\n\n/**\n * Provider metric names for a contract metric list, deduped: several contract metrics can\n * alias one provider metric (sessions and visits both map to Plausible's `visits`), so each\n * is read back from its provider key's position rather than from the request index.\n */\nexport const providerMetricKeys = (\n\tmetrics: MetricKey[],\n\tmap: Partial<Record<MetricKey, string>>\n): string[] => [...new Set(metrics.map((m) => map[m] as string))]\n\nexport interface GoalKeyedRow {\n\t/** The row's dimension values in the request's dimension order; empty for a totals row. */\n\tkeys: string[]\n\tmetrics: Partial<Record<MetricKey, number>>\n}\n\n/**\n * The two halves of a pair read unioned by dimension key. A row only the site request\n * returned keeps its conversions absent (no goal fired there); a row only the goal request\n * returned is appended carrying its goal metrics alone, since the site request answers a\n * different ranking and its own limit may have cut the row off.\n */\nexport const mergeGoalRows = (\n\tsite: GoalKeyedRow[] | undefined,\n\tgoals: GoalKeyedRow[] | undefined\n): GoalKeyedRow[] => {\n\tif (!site) {\n\t\treturn goals ?? []\n\t}\n\tif (!goals) {\n\t\treturn site\n\t}\n\tconst byKey = new Map(goals.map((row) => [JSON.stringify(row.keys), row]))\n\tconst merged = site.map((row) => {\n\t\tconst key = JSON.stringify(row.keys)\n\t\tconst goalRow = byKey.get(key)\n\t\tif (!goalRow) {\n\t\t\treturn row\n\t\t}\n\t\tbyKey.delete(key)\n\t\treturn { keys: row.keys, metrics: { ...row.metrics, ...goalRow.metrics } }\n\t})\n\treturn [...merged, ...byKey.values()]\n}\n\n/** The same union over a pair's totals rows, which carry no dimensions to key on. */\nexport const mergeGoalTotals = (\n\tsite: Partial<Record<MetricKey, number>> | undefined,\n\tgoals: Partial<Record<MetricKey, number>> | undefined\n): Partial<Record<MetricKey, number>> | undefined =>\n\tsite || goals ? { ...site, ...goals } : undefined\n\nexport interface GoalPair<Response> {\n\tsite: Response | undefined\n\tgoals: Response | undefined\n\t/** The goal request failed, so the read is served without its goal numbers. */\n\tfailed: boolean\n}\n\n/**\n * One request shape issued twice, plainly and goal-filtered. Sequential rather than\n * concurrent: the engine takes a single limiter permit per `adapter.query`, so a parallel\n * pair would exceed the provider's declared concurrency. A goal request the provider rejects\n * (a property with no key events, a site with no revenue goals) costs the read its\n * conversions rather than all of it, unless there is no site half left to serve.\n */\nexport const readGoalPair = async <Response>({\n\tsite,\n\tgoals,\n}: {\n\tsite: (() => Promise<Response>) | undefined\n\tgoals: (() => Promise<Response>) | undefined\n}): Promise<GoalPair<Response>> => {\n\tconst siteResponse = site ? await site() : undefined\n\tif (!goals) {\n\t\treturn { site: siteResponse, goals: undefined, failed: false }\n\t}\n\ttry {\n\t\treturn { site: siteResponse, goals: await goals(), failed: false }\n\t} catch (error) {\n\t\tif (!site) {\n\t\t\tthrow error\n\t\t}\n\t\treturn { site: siteResponse, goals: undefined, failed: true }\n\t}\n}\n"],"mappings":";AAWA,MAAa,YAAY,MAAgC;CACxD,IAAI,EAAE,cAAc,KAAA,GACnB,OAAO;CAER,IAAI,EAAE,cAAc,cACnB,OAAO;CAER,OAAO,EAAE,OAAO,CAAC,GAAG,IAAI,IAAI,EAAE,UAAU,QAAQ,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE;AAC7E;;AAGA,MAAa,aAAa,SACzB,SAAS,QAAQ,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,OAAO,KAAK;;;;;AAMjF,MAAa,cAAc,SAA4B,SAAS,QAAQ,SAAS;;AASjF,MAAa,yBACZ,UACA,GACA,UACsB;CACtB,MAAM,CAAC;CACP,MAAM;EACL;EACA,WAAW,EAAE,UAAU,IAAI,YAAY;EACvC,GAAG;EACH,iBAAiB;CAClB;AACD;;;;;;AAOA,MAAa,sBAAsB,EAClC,UACA,GACA,MACA,WAM6B;CAC7B,IAAI,UAAU,IAAI,MAAM,MACvB,OAAO;CAER,OAAO,WAAW,IAAI,IACnB,sBAAsB,UAAU,GAAG,IAAI,IACvC;EAAE,MAAM,CAAC;EAAG,MAAM;GAAE;GAAU,WAAW,EAAE,UAAU,IAAI,YAAY;GAAG,GAAG;EAAK;CAAE;AACtF;;;;;;;AAiBA,MAAa,oBAAoB,EAChC,QACA,UACA,eACA,WAMsB;CACtB,IAAI,eACH,OAAO;EAAE,aAAa;EAAQ,aAAa,CAAC;EAAG,YAAY;CAAM;CAElE,MAAM,cAAc,OAAO,QAAQ,MAAM,SAAS,IAAI,CAAC,CAAC;CACxD,OAAO;EACN,aAAa,OAAO,QAAQ,MAAM,CAAC,SAAS,IAAI,CAAC,CAAC;EAClD,aAAa,UAAU,IAAI,MAAM,O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declares `capture` only when one of it and `domain` is set.
|
|
19
19
|
*/
|
|
20
20
|
scriptId?: string;
|
|
21
|
+
/**
|
|
22
|
+
* The ISO currency of the site's revenue goals. Declaring it turns on the `revenue`
|
|
23
|
+
* metric: Plausible serves `total_revenue` only where a revenue goal exists, and errors
|
|
24
|
+
* the whole request on a site that has none.
|
|
25
|
+
*/
|
|
26
|
+
revenueCurrency?: string;
|
|
21
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Plausible identifies a goal by its display name in the site's own goal list ("Signup",
|
|
30
|
+
* "Visit /thank-you"), so a plugin goal's slug must equal that name for its conversions to
|
|
31
|
+
* read. Conversions are the `events` metric on goal rows, which is the dashboard's Total
|
|
32
|
+
* Conversions; revenue is `total_revenue`, which Plausible serves only for a revenue goal
|
|
33
|
+
* and reports as an object whose `value` is null when the rows mix currencies. Revenue is
|
|
34
|
+
* offered only when `revenueCurrency` says the site has such a goal: asking for it on a site
|
|
35
|
+
* without one errors the request.
|
|
36
|
+
*/
|
|
22
37
|
declare function plausible(config: PlausibleConfig): AnalyticsAdapter;
|
|
23
38
|
//#endregion
|
|
24
39
|
export { PlausibleConfig, plausible };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { zonedCalendarDay } from "../../timeframe/tz.js";
|
|
2
|
+
import { emptyGoalBreakdown, goalHint, hintSlugs, mergeGoalRows, providerMetricKeys, readGoalPair, splitGoalMetrics } from "../goalRead.js";
|
|
2
3
|
import { dayIso } from "../series.js";
|
|
3
4
|
import { fetchJson } from "../http/fetchJson.js";
|
|
4
5
|
//#region src/adapters/plausible/plausible.ts
|
|
@@ -50,8 +51,11 @@ const METRIC_MAP = {
|
|
|
50
51
|
avgDuration: "visit_duration",
|
|
51
52
|
events: "events",
|
|
52
53
|
scrollDepth: "scroll_depth",
|
|
54
|
+
conversions: "events",
|
|
53
55
|
revenue: "total_revenue"
|
|
54
56
|
};
|
|
57
|
+
/** Metrics Plausible answers only for a goal-restricted read. */
|
|
58
|
+
const GOAL_METRICS = new Set(["conversions", "revenue"]);
|
|
55
59
|
const DIMENSION_MAP = {
|
|
56
60
|
page: "event:page",
|
|
57
61
|
source: "visit:source",
|
|
@@ -64,26 +68,55 @@ const DIMENSION_MAP = {
|
|
|
64
68
|
city: "visit:city",
|
|
65
69
|
utmSource: "visit:utm_source",
|
|
66
70
|
utmMedium: "visit:utm_medium",
|
|
67
|
-
utmCampaign: "visit:utm_campaign"
|
|
71
|
+
utmCampaign: "visit:utm_campaign",
|
|
72
|
+
goal: "event:goal"
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Stats API v2 filter operators, available on every dimension this adapter offers as a
|
|
76
|
+
* filter (event:goal is the grammar's one exception, taking `is` and `contains` only, and
|
|
77
|
+
* is a breakdown here rather than a filter). `matches` is an re2 full match, so a pattern
|
|
78
|
+
* has to cover the whole value (`/docs/.*`, not `^/docs`).
|
|
79
|
+
*/
|
|
80
|
+
const OPERATOR_MAP = {
|
|
81
|
+
eq: "is",
|
|
82
|
+
contains: "contains",
|
|
83
|
+
matches: "matches"
|
|
68
84
|
};
|
|
69
85
|
const plausibleMetrics = new Set(Object.keys(METRIC_MAP));
|
|
86
|
+
const plausibleMetricsNoRevenue = new Set([...plausibleMetrics].filter((m) => m !== "revenue"));
|
|
70
87
|
const plausibleDimensions = new Set(Object.keys(DIMENSION_MAP));
|
|
88
|
+
const plausibleFilters = new Set([...plausibleDimensions].filter((dimension) => dimension !== "goal"));
|
|
89
|
+
const revenueAmount = (raw) => typeof raw === "object" && raw !== null && typeof raw.value === "number" ? raw.value : void 0;
|
|
71
90
|
const toContractValue = (metric, raw) => metric === "avgDuration" ? Math.round(raw * 1e3) : raw;
|
|
91
|
+
/**
|
|
92
|
+
* Plausible identifies a goal by its display name in the site's own goal list ("Signup",
|
|
93
|
+
* "Visit /thank-you"), so a plugin goal's slug must equal that name for its conversions to
|
|
94
|
+
* read. Conversions are the `events` metric on goal rows, which is the dashboard's Total
|
|
95
|
+
* Conversions; revenue is `total_revenue`, which Plausible serves only for a revenue goal
|
|
96
|
+
* and reports as an object whose `value` is null when the rows mix currencies. Revenue is
|
|
97
|
+
* offered only when `revenueCurrency` says the site has such a goal: asking for it on a site
|
|
98
|
+
* without one errors the request.
|
|
99
|
+
*/
|
|
72
100
|
function plausible(config) {
|
|
73
101
|
const host = config.host ?? "https://plausible.io";
|
|
102
|
+
const maxLookbackDays = config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730;
|
|
103
|
+
const revenueGoals = Boolean(config.revenueCurrency);
|
|
74
104
|
return {
|
|
75
105
|
id: "plausible",
|
|
76
106
|
label: "Plausible",
|
|
77
107
|
capabilities: {
|
|
78
108
|
perPageQuery: true,
|
|
79
109
|
realtime: false,
|
|
80
|
-
comparison: false,
|
|
81
110
|
minGranularity: "day",
|
|
82
|
-
maxLookbackDays
|
|
83
|
-
metrics: plausibleMetrics,
|
|
111
|
+
maxLookbackDays,
|
|
112
|
+
metrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,
|
|
84
113
|
dimensions: plausibleDimensions,
|
|
85
|
-
filters:
|
|
86
|
-
filterOperators: new Set([
|
|
114
|
+
filters: plausibleFilters,
|
|
115
|
+
filterOperators: new Set([
|
|
116
|
+
"eq",
|
|
117
|
+
"contains",
|
|
118
|
+
"matches"
|
|
119
|
+
]),
|
|
87
120
|
batchPageReport: true,
|
|
88
121
|
rateLimit: { requestsPerHour: 600 },
|
|
89
122
|
recommendedTtl: {
|
|
@@ -95,9 +128,24 @@ function plausible(config) {
|
|
|
95
128
|
isConfigured: () => Boolean(config.siteId && config.apiKey),
|
|
96
129
|
async query(q, ctx) {
|
|
97
130
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
98
|
-
const wanted = q.metrics.filter((m) => METRIC_MAP[m]);
|
|
99
|
-
const providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m]))];
|
|
100
131
|
const dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d]);
|
|
132
|
+
const goalBreakdown = dims.includes("goal");
|
|
133
|
+
const hint = goalHint(q);
|
|
134
|
+
const slugs = hintSlugs(hint);
|
|
135
|
+
const empty = goalBreakdown ? emptyGoalBreakdown({
|
|
136
|
+
provider: "plausible",
|
|
137
|
+
q,
|
|
138
|
+
hint
|
|
139
|
+
}) : null;
|
|
140
|
+
if (empty) return empty;
|
|
141
|
+
const { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({
|
|
142
|
+
wanted: q.metrics.filter((m) => METRIC_MAP[m] && (revenueGoals || m !== "revenue")),
|
|
143
|
+
goalOnly: GOAL_METRICS,
|
|
144
|
+
goalBreakdown,
|
|
145
|
+
hint
|
|
146
|
+
});
|
|
147
|
+
const siteKeys = providerMetricKeys(siteMetrics, METRIC_MAP);
|
|
148
|
+
const goalKeys = providerMetricKeys(goalMetrics, METRIC_MAP);
|
|
101
149
|
const filters = [];
|
|
102
150
|
if (q.path) filters.push([
|
|
103
151
|
"is",
|
|
@@ -110,86 +158,106 @@ function plausible(config) {
|
|
|
110
158
|
[q.hostname]
|
|
111
159
|
]);
|
|
112
160
|
for (const filter of q.filters ?? []) {
|
|
113
|
-
const mapped = DIMENSION_MAP[filter.dimension];
|
|
114
|
-
if (!mapped
|
|
161
|
+
const mapped = plausibleFilters.has(filter.dimension) ? DIMENSION_MAP[filter.dimension] : void 0;
|
|
162
|
+
if (!mapped) continue;
|
|
115
163
|
filters.push([
|
|
116
|
-
|
|
164
|
+
OPERATOR_MAP[filter.operator],
|
|
117
165
|
mapped,
|
|
118
166
|
[filter.value]
|
|
119
167
|
]);
|
|
120
168
|
}
|
|
121
|
-
const
|
|
169
|
+
const goalFilters = slugs ? [...filters, [
|
|
170
|
+
"is",
|
|
171
|
+
"event:goal",
|
|
172
|
+
slugs
|
|
173
|
+
]] : filters;
|
|
174
|
+
const siteFilters = goalBreakdown ? goalFilters : filters;
|
|
175
|
+
let goalsFailed = false;
|
|
176
|
+
const meta = () => ({
|
|
177
|
+
provider: "plausible",
|
|
178
|
+
fetchedAt,
|
|
179
|
+
...unresolved || goalsFailed ? { goalsUnresolved: true } : {}
|
|
180
|
+
});
|
|
181
|
+
const readMetrics = (ms, keys, row) => {
|
|
122
182
|
const out = {};
|
|
123
|
-
for (const m of
|
|
124
|
-
const
|
|
125
|
-
|
|
183
|
+
for (const m of ms) {
|
|
184
|
+
const raw = row.metrics[keys.indexOf(METRIC_MAP[m])];
|
|
185
|
+
if (m === "revenue") {
|
|
186
|
+
const amount = revenueAmount(raw);
|
|
187
|
+
if (amount !== void 0) out.revenue = amount;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
out[m] = toContractValue(m, typeof raw === "number" ? raw : 0);
|
|
126
191
|
}
|
|
127
192
|
return out;
|
|
128
193
|
};
|
|
129
|
-
const postQuery = (extra) => fetchJson(`${host}/api/v2/query`, {
|
|
194
|
+
const postQuery = (metrics, clauses, extra) => fetchJson(`${host}/api/v2/query`, {
|
|
130
195
|
method: "POST",
|
|
131
196
|
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
132
197
|
body: {
|
|
133
198
|
site_id: config.siteId,
|
|
134
|
-
metrics
|
|
199
|
+
metrics,
|
|
135
200
|
date_range: [zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"), zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")],
|
|
136
|
-
...
|
|
201
|
+
...clauses.length ? { filters: clauses } : {},
|
|
137
202
|
...extra
|
|
138
203
|
},
|
|
139
204
|
signal: ctx.signal,
|
|
140
205
|
provider: "plausible"
|
|
141
206
|
});
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
207
|
+
const keyedRows = (response, ms, keys) => response?.results.map((row) => ({
|
|
208
|
+
keys: row.dimensions,
|
|
209
|
+
metrics: readMetrics(ms, keys, row)
|
|
210
|
+
}));
|
|
211
|
+
/**
|
|
212
|
+
* One request shape read twice, plainly and goal-filtered, unioned per row. A row the
|
|
213
|
+
* goal read has no counterpart for carries no conversions: no goal was completed there.
|
|
214
|
+
*/
|
|
215
|
+
const readPair = async (extra) => {
|
|
216
|
+
const pair = await readGoalPair({
|
|
217
|
+
site: siteKeys.length ? () => postQuery(siteKeys, siteFilters, extra) : void 0,
|
|
218
|
+
goals: goalKeys.length ? () => postQuery(goalKeys, goalFilters, extra) : void 0
|
|
219
|
+
});
|
|
220
|
+
if (pair.failed) goalsFailed = true;
|
|
221
|
+
return mergeGoalRows(keyedRows(pair.site, siteMetrics, siteKeys), keyedRows(pair.goals, goalMetrics, goalKeys));
|
|
145
222
|
};
|
|
146
223
|
if (q.granularity === "day" && !dims.length) {
|
|
147
|
-
const [
|
|
224
|
+
const [series, totalRows] = await Promise.all([readPair({ dimensions: ["time:day"] }), readPair({})]);
|
|
148
225
|
const rows = [];
|
|
149
|
-
for (const row of
|
|
150
|
-
const ts = dayIso(row.
|
|
226
|
+
for (const row of series) {
|
|
227
|
+
const ts = dayIso(row.keys[0] ?? "");
|
|
151
228
|
if (ts) rows.push({
|
|
152
229
|
timestamp: ts,
|
|
153
|
-
metrics:
|
|
230
|
+
metrics: row.metrics
|
|
154
231
|
});
|
|
155
232
|
}
|
|
156
233
|
return {
|
|
157
234
|
rows,
|
|
158
|
-
totals,
|
|
159
|
-
meta:
|
|
160
|
-
provider: "plausible",
|
|
161
|
-
fetchedAt
|
|
162
|
-
}
|
|
235
|
+
totals: totalRows[0]?.metrics ?? {},
|
|
236
|
+
meta: meta()
|
|
163
237
|
};
|
|
164
238
|
}
|
|
165
239
|
if (!dims.length) {
|
|
166
|
-
const totals = await
|
|
240
|
+
const totals = (await readPair({}))[0]?.metrics ?? {};
|
|
167
241
|
return {
|
|
168
242
|
rows: [{ metrics: totals }],
|
|
169
243
|
totals,
|
|
170
|
-
meta:
|
|
171
|
-
provider: "plausible",
|
|
172
|
-
fetchedAt
|
|
173
|
-
}
|
|
244
|
+
meta: meta()
|
|
174
245
|
};
|
|
175
246
|
}
|
|
176
247
|
return {
|
|
177
|
-
rows: (await
|
|
248
|
+
rows: (await readPair({ dimensions: dims.map((d) => DIMENSION_MAP[d]) })).map((row) => {
|
|
178
249
|
const dimValues = {};
|
|
179
250
|
for (let i = 0; i < dims.length; i++) {
|
|
180
251
|
const d = dims[i];
|
|
181
|
-
if (d !== void 0) dimValues[d] = row.
|
|
252
|
+
if (d !== void 0) dimValues[d] = row.keys[i] ?? "";
|
|
182
253
|
}
|
|
183
254
|
return {
|
|
184
255
|
dimensions: dimValues,
|
|
185
|
-
metrics:
|
|
256
|
+
metrics: row.metrics
|
|
186
257
|
};
|
|
187
258
|
}),
|
|
188
259
|
totals: void 0,
|
|
189
|
-
meta:
|
|
190
|
-
provider: "plausible",
|
|
191
|
-
fetchedAt
|
|
192
|
-
}
|
|
260
|
+
meta: meta()
|
|
193
261
|
};
|
|
194
262
|
}
|
|
195
263
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\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 * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\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 seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,OAAO,UACV,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,OAAO,SAAS;GAAM,OAAO;EAAK,GAC1D,EACC,QAAQ,GAAG,eAAe,2BAA2B,KAAK,UAAU,GAAG,KAAK,WAAW,EAAE,IAC1F,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAgB,UAAU,GAAG,KAAK;EAAc,GAC1D;GAAE,QAAQ;GAAc,UAAU,GAAG,KAAK;EAAY,CACvD,EACD;EACA,UAAU,EAAE,YAAY,EAAE,SAAS,QAAQ,IAAI,EAAE;EACjD,QAAQ,EAAE,MAAM,YAAY;CAC7B;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;C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MAAE,WAAW;MAAI,SAAS,QAAQ,GAAG;KAAE,CAAC;IAEpD;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GACnE;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,MAAM,YAAY;IACjC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GAC1F;GAaA,OAAO;IAAE,OAVoB,MADV,UAAU,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tFilterOperator,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tproviderMetricKeys,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\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 * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n\t/**\n\t * The ISO currency of the site's revenue goals. Declaring it turns on the `revenue`\n\t * metric: Plausible serves `total_revenue` only where a revenue goal exists, and errors\n\t * the whole request on a site that has none.\n\t */\n\trevenueCurrency?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n\tgoal: 'event:goal',\n}\n\n/**\n * Stats API v2 filter operators, available on every dimension this adapter offers as a\n * filter (event:goal is the grammar's one exception, taking `is` and `contains` only, and\n * is a breakdown here rather than a filter). `matches` is an re2 full match, so a pattern\n * has to cover the whole value (`/docs/.*`, not `^/docs`).\n */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n// `goal` is a breakdown, not a filter: the read's own goal slugs own the event:goal clause,\n// and the grammar allows no `matches` on it anyway.\nconst plausibleFilters: ReadonlySet<DimensionKey> = new Set(\n\t[...plausibleDimensions].filter((dimension) => dimension !== 'goal')\n)\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\n/**\n * Plausible identifies a goal by its display name in the site's own goal list (\"Signup\",\n * \"Visit /thank-you\"), so a plugin goal's slug must equal that name for its conversions to\n * read. Conversions are the `events` metric on goal rows, which is the dashboard's Total\n * Conversions; revenue is `total_revenue`, which Plausible serves only for a revenue goal\n * and reports as an object whose `value` is null when the rows mix currencies. Revenue is\n * offered only when `revenueCurrency` says the site has such a goal: asking for it on a site\n * without one errors the request.\n */\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst revenueGoals = Boolean(config.revenueCurrency)\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleFilters,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'plausible', q, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m] && (revenueGoals || m !== 'revenue'))\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted,\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteKeys = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalKeys = providerMetricKeys(goalMetrics, METRIC_MAP)\n\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = plausibleFilters.has(filter.dimension)\n\t\t\t\t\t? DIMENSION_MAP[filter.dimension]\n\t\t\t\t\t: undefined\n\t\t\t\tif (!mapped) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], mapped, [filter.value]])\n\t\t\t}\n\t\t\tconst goalFilters: Array<[string, string, string[]]> = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst readMetrics = (\n\t\t\t\tms: MetricKey[],\n\t\t\t\tkeys: string[],\n\t\t\t\trow: PlausibleResult\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of ms) {\n\t\t\t\t\tconst raw = row.metrics[keys.indexOf(METRIC_MAP[m] as string)]\n\t\t\t\t\tif (m === 'revenue') {\n\t\t\t\t\t\tconst amount = revenueAmount(raw)\n\t\t\t\t\t\tif (amount !== undefined) {\n\t\t\t\t\t\t\tout.revenue = amount\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tout[m] = toContractValue(m, typeof raw === 'number' ? raw : 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (\n\t\t\t\tmetrics: string[],\n\t\t\t\tclauses: Array<[string, string, string[]]>,\n\t\t\t\textra: Record<string, unknown>\n\t\t\t): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst keyedRows = (\n\t\t\t\tresponse: PlausibleResponse | undefined,\n\t\t\t\tms: MetricKey[],\n\t\t\t\tkeys: string[]\n\t\t\t): GoalKeyedRow[] | undefined =>\n\t\t\t\tresponse?.results.map((row) => ({\n\t\t\t\t\tkeys: row.dimensions,\n\t\t\t\t\tmetrics: readMetrics(ms, keys, row),\n\t\t\t\t}))\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (extra: Record<string, unknown>): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteKeys.length ? () => postQuery(siteKeys, siteFilters, extra) : undefined,\n\t\t\t\t\tgoals: goalKeys.length ? () => postQuery(goalKeys, goalFilters, extra) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteKeys),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalKeys)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series) {\n\t\t\t\t\tconst ts = dayIso(row.keys[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: row.metrics })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals: totalRows[0]?.metrics ?? {}, meta: meta() }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = merged.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.keys[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA4DA,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