@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.13
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 +67 -0
- package/dist/adapters/ga4/ga4.d.ts +6 -0
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +6 -0
- package/dist/adapters/posthog/posthog.js +21 -8
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +2 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/exclusionEndpoint.js +1 -1
- package/dist/capture/exclusionEndpoint.js.map +1 -1
- package/dist/capture/slots.js +3 -3
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.js +11 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/adminOptions.js +6 -1
- package/dist/core/adminOptions.js.map +1 -1
- package/dist/core/capture.d.ts +3 -1
- package/dist/core/contract.d.ts +13 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +37 -5
- package/dist/core/options.js +6 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.js.map +1 -1
- package/dist/core/scopeOptions.js +2 -0
- package/dist/core/scopeOptions.js.map +1 -1
- package/dist/core/scopedRead.js +170 -21
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceLabel.d.ts +10 -0
- package/dist/core/sourceLabel.js +63 -0
- package/dist/core/sourceLabel.js.map +1 -0
- package/dist/core/sourceOptions.js +18 -6
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +55 -0
- package/dist/core/sourcePolicy.js +51 -0
- package/dist/core/sourcePolicy.js.map +1 -0
- package/dist/exports/adapters/contract.d.ts +2 -1
- package/dist/exports/adapters/ga4.d.ts +3 -2
- package/dist/exports/adapters/native.d.ts +3 -2
- package/dist/exports/adapters/plausible.d.ts +3 -2
- package/dist/exports/adapters/posthog.d.ts +3 -2
- package/dist/exports/adapters/umami.d.ts +3 -2
- package/dist/exports/client.d.ts +7 -5
- package/dist/exports/client.js +2 -1
- package/dist/exports/next.d.ts +3 -2
- package/dist/exports/rsc.d.ts +7 -6
- package/dist/exports/testing.d.ts +3 -2
- package/dist/exports/types.d.ts +12 -8
- package/dist/fields/AnalyticsPanelClient.js.map +1 -1
- package/dist/fields/AnalyticsPanelField.d.ts +1 -1
- package/dist/fields/AnalyticsPanelField.js +3 -1
- package/dist/fields/AnalyticsPanelField.js.map +1 -1
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +1 -1
- package/dist/fields/PanelContent.js +6 -1
- package/dist/fields/PanelContent.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +3 -0
- package/dist/fields/config/fetchSources.js +5 -3
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +5 -4
- package/dist/fields/readForDocument.js +6 -2
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/collection.js +4 -31
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +2 -2
- package/dist/goals/trackGoalAction.js +1 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/ingest/normalizeEvent.js +1 -1
- package/dist/native/nativeAdapter.d.ts +6 -0
- package/dist/native/nativeAdapter.js +3 -2
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/plugin/createRuntime.js +6 -3
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -0
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/pluginCollections.js +11 -5
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +11 -0
- package/dist/plugin/readContextForRequest.js +25 -15
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/runtime.js +13 -5
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +8 -9
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/ProvidersListNotice.d.ts +11 -0
- package/dist/providers/ProvidersListNotice.js +36 -0
- package/dist/providers/ProvidersListNotice.js.map +1 -0
- package/dist/providers/collection.d.ts +9 -1
- package/dist/providers/collection.js +107 -42
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +1 -1
- package/dist/providers/factory.js +8 -11
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/probe.js +5 -1
- package/dist/providers/probe.js.map +1 -1
- package/dist/providers/registry.js +49 -39
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/resolver.js +6 -3
- package/dist/providers/resolver.js.map +1 -1
- package/dist/providers/scopeUnique.js +41 -0
- package/dist/providers/scopeUnique.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/tracker/config.d.ts +5 -0
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +4 -1
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/tracker/sinks/posthog.js +30 -2
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +2 -2
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +7 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +5 -0
- package/dist/ui/components/SourcesNoticeBanner.js +20 -0
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
- package/dist/view/ViewRoot.js +2 -0
- package/dist/view/ViewRoot.js.map +1 -1
- package/dist/view/registerView.js +5 -4
- package/dist/view/registerView.js.map +1 -1
- package/dist/view/viewContext.d.ts +1 -1
- package/dist/view/viewProps.d.ts +1 -1
- package/dist/view/viewProps.js +3 -2
- package/dist/view/viewProps.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +1 -0
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +1 -0
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/defaultLayout.d.ts +26 -0
- package/dist/widgets/defaultLayout.js +51 -0
- package/dist/widgets/defaultLayout.js.map +1 -0
- package/dist/widgets/notices.js +1 -0
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/prepareWidgetRead.d.ts +14 -1
- package/dist/widgets/prepareWidgetRead.js +6 -2
- package/dist/widgets/prepareWidgetRead.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +4 -4
- package/dist/widgets/readForWidget.js +3 -1
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
- package/dist/widgets/readForWidgetBreakdown.js +3 -1
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +4 -4
- package/dist/widgets/readForWidgetGoals.js +3 -1
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
- package/dist/widgets/readForWidgetRealtime.js +3 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +4 -4
- package/dist/widgets/readForWidgetSeries.js +3 -1
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +3 -1
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentEndpoint.js","names":[],"sources":["../../src/plugin/documentEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { readReportMode, reportModes } from '../binding/report'\nimport { currentDate } from '../core/clock'\nimport type { DateRange, MetricKey } from '../core/contract'\nimport { isMetricKey } from '../core/guards'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { wholeNumberParam } from '../core/values'\nimport { ITEM_PANEL_METRICS, ITEM_PANEL_OPTIONAL_METRICS } from '../fields/itemReport'\nimport { engineReads, readFieldWith } from '../fields/readForDocument'\nimport { parseDayOrInstant } from '../query/dates'\nimport { exceedsRangeCap, MAX_QUERY_RANGE_DAYS } from '../query/limits'\nimport { readDimensionList } from '../query/parse'\nimport { isTimeframePreset, type TimeframePreset } from '../timeframe/presets'\nimport { resolveBoundDocument, unloadedDocumentResponse } from './boundDocument'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { queryParams } from './queryParams'\nimport { type AnalyticsRuntime, getRuntime, requestTimezone } from './runtime'\n\nconst MAX_METRICS = 8\n/** A panel row holds three small lists; more would stop being a panel. */\nconst MAX_PANEL_DIMENSIONS = 3\nconst MAX_PANEL_ROWS = 25\n/** A source with no time per pageview (most vendors) leaves that card out without a warning. */\nconst PAGE_PANEL_OPTIONAL_METRICS: MetricKey[] = ['avgDuration']\n\nconst parseMetrics = (raw: string | null): MetricKey[] | null => {\n\tif (!raw) {\n\t\treturn null\n\t}\n\tconst metrics = raw\n\t\t.split(',')\n\t\t.map((m) => m.trim())\n\t\t.filter(isMetricKey)\n\treturn metrics.length > 0 ? metrics.slice(0, MAX_METRICS) : null\n}\n\ntype RangeResult =\n\t| { ok: true; range: DateRange }\n\t| { ok: false; param: 'from' | 'to'; tooLong?: true }\n\n/**\n * A custom window read like the query endpoint's, capped at `MAX_QUERY_RANGE_DAYS`; a `YYYY-MM-DD`\n * day spans the whole day in the reporting timezone. An inverted window blames `to`, picked second.\n */\nconst parseRange = (from: string | null, to: string | null, timezone: string): RangeResult => {\n\tif (!from) {\n\t\treturn { ok: false, param: 'from' }\n\t}\n\tif (!to) {\n\t\treturn { ok: false, param: 'to' }\n\t}\n\tconst start = parseDayOrInstant(from, { timezone, edge: 'start' })\n\tif (!start) {\n\t\treturn { ok: false, param: 'from' }\n\t}\n\tconst end = parseDayOrInstant(to, { timezone, edge: 'end' })\n\tif (!end || end.getTime() <= start.getTime()) {\n\t\treturn { ok: false, param: 'to' }\n\t}\n\tif (exceedsRangeCap({ start, end })) {\n\t\treturn { ok: false, param: 'to', tooLong: true }\n\t}\n\treturn { ok: true, range: { start, end } }\n}\n\n/**\n * Authenticated GET behind the document panel, in the document's own scope (no parameter names\n * one). Unreadable and missing are one 404; other failures are a logged 500, never a masking 404.\n */\nexport const makeDocumentHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\ttry {\n\t\treturn await answerDocument(req, runtime)\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: document read failed: ${describeWithCauses(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: document read failed'))\n\t}\n}\n\nconst answerDocument = async (\n\treq: PayloadRequest,\n\truntime: AnalyticsRuntime\n): Promise<Response> => {\n\tif (!(await readGate(runtime, req))) {\n\t\treturn readDeniedResponse()\n\t}\n\tconst params = queryParams(req)\n\tconst collection = params.get('collection') ?? ''\n\tconst id = params.get('id') ?? ''\n\tif (!runtime.bindings[collection] || !id) {\n\t\treturn unloadedDocumentResponse(404)\n\t}\n\tconst rawTimeframe = params.get('timeframe') ?? 'last30days'\n\tlet timezone: string | undefined\n\tlet range: DateRange | undefined\n\tif (rawTimeframe === 'custom') {\n\t\t// Custom bounds name calendar days, so the reporting timezone must resolve before they are\n\t\t// read; a preset resolves its window inside `readForField`.\n\t\ttimezone = await requestTimezone(req)\n\t\tconst parsed = parseRange(params.get('from'), params.get('to'), timezone)\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tparsed.tooLong\n\t\t\t\t\t? analyticsError(\n\t\t\t\t\t\t\t'range_too_long',\n\t\t\t\t\t\t\t`analytics: the range must not exceed ${MAX_QUERY_RANGE_DAYS} days`,\n\t\t\t\t\t\t\tparsed.param\n\t\t\t\t\t\t)\n\t\t\t\t\t: analyticsError(\n\t\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t\t'analytics: the custom range could not be read',\n\t\t\t\t\t\t\tparsed.param\n\t\t\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\trange = parsed.range\n\t}\n\tconst timeframe: TimeframePreset = isTimeframePreset(rawTimeframe) ? rawTimeframe : 'last30days'\n\tconst report =\n\t\treadReportMode(params.get('report')) ?? reportModes(runtime.bindings[collection])[0] ?? 'page'\n\tconst requested = parseMetrics(params.get('metrics'))\n\tconst metrics =\n\t\trequested ??\n\t\t(report === 'item' ? ITEM_PANEL_METRICS : ['pageviews', 'visitors', 'sessions', 'avgDuration'])\n\t// Metrics the panel asked for on spec, so a source serving none of them warns nobody.\n\tconst optionalMetrics =\n\t\tparseMetrics(params.get('optional')) ??\n\t\t(requested === null\n\t\t\t? report === 'item'\n\t\t\t\t? ITEM_PANEL_OPTIONAL_METRICS\n\t\t\t\t: PAGE_PANEL_OPTIONAL_METRICS\n\t\t\t: [])\n\tconst dimensions = readDimensionList(params.get('dimensions'), MAX_PANEL_DIMENSIONS)\n\tconst rawLimit = wholeNumberParam(params.get('limit'))\n\tconst limit = rawLimit === undefined ? undefined : Math.min(Math.max(rawLimit, 1), MAX_PANEL_ROWS)\n\tconst bound = await resolveBoundDocument({ req, collection, id })\n\tif (!bound.ok) {\n\t\treturn unloadedDocumentResponse(bound.status)\n\t}\n\t// `fresh=1` waits for the source rather than answering with an expired entry: the panel asks it\n\t// when its first render could only show saved numbers, and falls back to them if the source fails.\n\tconst reads = engineReads({\n\t\tpriority: 'interactive',\n\t\t...(params.get('fresh') === '1' ? { allowStale: false } : {}),\n\t})\n\tconst result = await readFieldWith(\n\t\t{\n\t\t\treq,\n\t\t\tcollectionSlug: collection,\n\t\t\tdata: bound.data,\n\t\t\tmetrics,\n\t\t\toptionalMetrics,\n\t\t\ttimeframe,\n\t\t\trange,\n\t\t\t...(timezone !== undefined ? { timezone } : {}),\n\t\t\t...(dimensions.length > 0 ? { dimensions } : {}),\n\t\t\t...(limit === undefined ? {} : { limit }),\n\t\t\tadapterId: params.get('dataSource') ?? undefined,\n\t\t\tnow: currentDate(),\n\t\t\tcompare: params.get('compare') === '1',\n\t\t\tseries: params.get('series') === '1',\n\t\t\treport,\n\t\t},\n\t\treads\n\t)\n\tif (result.untrustedScope) {\n\t\treturn untrustedScopeResponse()\n\t}\n\treturn Response.json(result, { headers: NO_STORE })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;;AAEpB,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;;AAEvB,MAAM,8BAA2C,CAAC,aAAa;AAE/D,MAAM,gBAAgB,QAA2C;CAChE,IAAI,CAAC,KACJ,OAAO;CAER,MAAM,UAAU,IACd,MAAM,GAAG,EACT,KAAK,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,WAAW;CACpB,OAAO,QAAQ,SAAS,IAAI,QAAQ,MAAM,GAAG,WAAW,IAAI;AAC7D;;;;;AAUA,MAAM,cAAc,MAAqB,IAAmB,aAAkC;CAC7F,IAAI,CAAC,MACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAO;CAEnC,IAAI,CAAC,IACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAK;CAEjC,MAAM,QAAQ,kBAAkB,MAAM;EAAE;EAAU,MAAM;CAAQ,CAAC;CACjE,IAAI,CAAC,OACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAO;CAEnC,MAAM,MAAM,kBAAkB,IAAI;EAAE;EAAU,MAAM;CAAM,CAAC;CAC3D,IAAI,CAAC,OAAO,IAAI,QAAQ,KAAK,MAAM,QAAQ,GAC1C,OAAO;EAAE,IAAI;EAAO,OAAO;CAAK;CAEjC,IAAI,gBAAgB;EAAE;EAAO;CAAI,CAAC,GACjC,OAAO;EAAE,IAAI;EAAO,OAAO;EAAM,SAAS;CAAK;CAEhD,OAAO;EAAE,IAAI;EAAM,OAAO;GAAE;GAAO;EAAI;CAAE;AAC1C;;;;;AAMA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;CAE9F,MAAM,kBACL,aAAa,OAAO,IAAI,UAAU,CAAC,MAClC,cAAc,OACZ,WAAW,SACV,8BACA,8BACD,CAAC;CACL,MAAM,aAAa,kBAAkB,OAAO,IAAI,YAAY,GAAG,oBAAoB;CACnF,MAAM,WAAW,iBAAiB,OAAO,IAAI,OAAO,CAAC;CACrD,MAAM,QAAQ,aAAa,KAAA,IAAY,KAAA,IAAY,KAAK,IAAI,KAAK,IAAI,UAAU,CAAC,GAAG,cAAc;CACjG,MAAM,QAAQ,MAAM,qBAAqB;EAAE;EAAK;EAAY;CAAG,CAAC;CAChE,IAAI,CAAC,MAAM,IACV,OAAO,yBAAyB,MAAM,MAAM;CAI7C,MAAM,QAAQ,YAAY;EACzB,UAAU;EACV,GAAI,OAAO,IAAI,OAAO,MAAM,MAAM,EAAE,YAAY,MAAM,IAAI,CAAC;CAC5D,CAAC;CACD,MAAM,SAAS,MAAM,cACpB;EACC;EACA,gBAAgB;EAChB,MAAM,MAAM;EACZ;EACA;EACA;EACA;EACA,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;EAC7C,GAAI,WAAW,SAAS,IAAI,EAAE,WAAW,IAAI,CAAC;EAC9C,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,WAAW,OAAO,IAAI,YAAY,KAAK,KAAA;EACvC,KAAK,YAAY;EACjB,SAAS,OAAO,IAAI,SAAS,MAAM;EACnC,QAAQ,OAAO,IAAI,QAAQ,MAAM;EACjC;CACD,GACA,KACD;CACA,IAAI,OAAO,gBACV,OAAO,uBAAuB;CAE/B,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;AACnD"}
|
|
1
|
+
{"version":3,"file":"documentEndpoint.js","names":[],"sources":["../../src/plugin/documentEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { readReportMode, reportModes } from '../binding/report'\nimport { currentDate } from '../core/clock'\nimport type { DateRange, MetricKey } from '../core/contract'\nimport { isMetricKey } from '../core/guards'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { wholeNumberParam } from '../core/values'\nimport { ITEM_PANEL_METRICS, ITEM_PANEL_OPTIONAL_METRICS } from '../fields/itemReport'\nimport { engineReads, readFieldWith } from '../fields/readForDocument'\nimport { parseDayOrInstant } from '../query/dates'\nimport { exceedsRangeCap, MAX_QUERY_RANGE_DAYS } from '../query/limits'\nimport { readDimensionList } from '../query/parse'\nimport { isTimeframePreset, type TimeframePreset } from '../timeframe/presets'\nimport { resolveBoundDocument, unloadedDocumentResponse } from './boundDocument'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { queryParams } from './queryParams'\nimport { type AnalyticsRuntime, getRuntime, requestTimezone } from './runtime'\n\nconst MAX_METRICS = 8\n/** A panel row holds three small lists; more would stop being a panel. */\nconst MAX_PANEL_DIMENSIONS = 3\nconst MAX_PANEL_ROWS = 25\n/** A source with no time per pageview (most vendors) leaves that card out without a warning. */\nconst PAGE_PANEL_OPTIONAL_METRICS: MetricKey[] = ['avgDuration']\n\nconst parseMetrics = (raw: string | null): MetricKey[] | null => {\n\tif (!raw) {\n\t\treturn null\n\t}\n\tconst metrics = raw\n\t\t.split(',')\n\t\t.map((m) => m.trim())\n\t\t.filter(isMetricKey)\n\treturn metrics.length > 0 ? metrics.slice(0, MAX_METRICS) : null\n}\n\ntype RangeResult =\n\t| { ok: true; range: DateRange }\n\t| { ok: false; param: 'from' | 'to'; tooLong?: true }\n\n/**\n * A custom window read like the query endpoint's, capped at `MAX_QUERY_RANGE_DAYS`; a `YYYY-MM-DD`\n * day spans the whole day in the reporting timezone. An inverted window blames `to`, picked second.\n */\nconst parseRange = (from: string | null, to: string | null, timezone: string): RangeResult => {\n\tif (!from) {\n\t\treturn { ok: false, param: 'from' }\n\t}\n\tif (!to) {\n\t\treturn { ok: false, param: 'to' }\n\t}\n\tconst start = parseDayOrInstant(from, { timezone, edge: 'start' })\n\tif (!start) {\n\t\treturn { ok: false, param: 'from' }\n\t}\n\tconst end = parseDayOrInstant(to, { timezone, edge: 'end' })\n\tif (!end || end.getTime() <= start.getTime()) {\n\t\treturn { ok: false, param: 'to' }\n\t}\n\tif (exceedsRangeCap({ start, end })) {\n\t\treturn { ok: false, param: 'to', tooLong: true }\n\t}\n\treturn { ok: true, range: { start, end } }\n}\n\n/**\n * Authenticated GET behind the document panel, in the document's own scope (no parameter names\n * one). Unreadable and missing are one 404; other failures are a logged 500, never a masking 404.\n */\nexport const makeDocumentHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\ttry {\n\t\treturn await answerDocument(req, runtime)\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: document read failed: ${describeWithCauses(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: document read failed'))\n\t}\n}\n\nconst answerDocument = async (\n\treq: PayloadRequest,\n\truntime: AnalyticsRuntime\n): Promise<Response> => {\n\tif (!(await readGate(runtime, req))) {\n\t\treturn readDeniedResponse()\n\t}\n\tconst params = queryParams(req)\n\tconst collection = params.get('collection') ?? ''\n\tconst id = params.get('id') ?? ''\n\tif (!runtime.bindings[collection] || !id) {\n\t\treturn unloadedDocumentResponse(404)\n\t}\n\tconst rawTimeframe = params.get('timeframe') ?? 'last30days'\n\tlet timezone: string | undefined\n\tlet range: DateRange | undefined\n\tif (rawTimeframe === 'custom') {\n\t\t// Custom bounds name calendar days, so the reporting timezone must resolve before they are\n\t\t// read; a preset resolves its window inside `readForField`.\n\t\ttimezone = await requestTimezone(req)\n\t\tconst parsed = parseRange(params.get('from'), params.get('to'), timezone)\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tparsed.tooLong\n\t\t\t\t\t? analyticsError(\n\t\t\t\t\t\t\t'range_too_long',\n\t\t\t\t\t\t\t`analytics: the range must not exceed ${MAX_QUERY_RANGE_DAYS} days`,\n\t\t\t\t\t\t\tparsed.param\n\t\t\t\t\t\t)\n\t\t\t\t\t: analyticsError(\n\t\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t\t'analytics: the custom range could not be read',\n\t\t\t\t\t\t\tparsed.param\n\t\t\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\trange = parsed.range\n\t}\n\tconst timeframe: TimeframePreset = isTimeframePreset(rawTimeframe) ? rawTimeframe : 'last30days'\n\tconst report =\n\t\treadReportMode(params.get('report')) ?? reportModes(runtime.bindings[collection])[0] ?? 'page'\n\tconst requested = parseMetrics(params.get('metrics'))\n\tconst metrics =\n\t\trequested ??\n\t\t(report === 'item' ? ITEM_PANEL_METRICS : ['pageviews', 'visitors', 'sessions', 'avgDuration'])\n\t// Metrics the panel asked for on spec, so a source serving none of them warns nobody.\n\tconst optionalMetrics =\n\t\tparseMetrics(params.get('optional')) ??\n\t\t(requested === null\n\t\t\t? report === 'item'\n\t\t\t\t? ITEM_PANEL_OPTIONAL_METRICS\n\t\t\t\t: PAGE_PANEL_OPTIONAL_METRICS\n\t\t\t: [])\n\tconst dimensions = readDimensionList(params.get('dimensions'), MAX_PANEL_DIMENSIONS)\n\tconst rawLimit = wholeNumberParam(params.get('limit'))\n\tconst limit = rawLimit === undefined ? undefined : Math.min(Math.max(rawLimit, 1), MAX_PANEL_ROWS)\n\tconst bound = await resolveBoundDocument({ req, collection, id })\n\tif (!bound.ok) {\n\t\treturn unloadedDocumentResponse(bound.status)\n\t}\n\t// `fresh=1` waits for the source rather than answering with an expired entry: the panel asks it\n\t// when its first render could only show saved numbers, and falls back to them if the source fails.\n\tconst reads = engineReads({\n\t\tpriority: 'interactive',\n\t\t...(params.get('fresh') === '1' ? { allowStale: false } : {}),\n\t})\n\tconst result = await readFieldWith(\n\t\t{\n\t\t\treq,\n\t\t\tcollectionSlug: collection,\n\t\t\tdata: bound.data,\n\t\t\tmetrics,\n\t\t\toptionalMetrics,\n\t\t\ttimeframe,\n\t\t\trange,\n\t\t\t...(timezone !== undefined ? { timezone } : {}),\n\t\t\t...(dimensions.length > 0 ? { dimensions } : {}),\n\t\t\t...(limit === undefined ? {} : { limit }),\n\t\t\tadapterId: params.get('dataSource') ?? undefined,\n\t\t\t// The panel sends the source its field stores until the reader picks another.\n\t\t\tfallbackWhenUnreadable: true,\n\t\t\tnow: currentDate(),\n\t\t\tcompare: params.get('compare') === '1',\n\t\t\tseries: params.get('series') === '1',\n\t\t\treport,\n\t\t},\n\t\treads\n\t)\n\tif (result.untrustedScope) {\n\t\treturn untrustedScopeResponse()\n\t}\n\treturn Response.json(result, { headers: NO_STORE })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;;AAEpB,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;;AAEvB,MAAM,8BAA2C,CAAC,aAAa;AAE/D,MAAM,gBAAgB,QAA2C;CAChE,IAAI,CAAC,KACJ,OAAO;CAER,MAAM,UAAU,IACd,MAAM,GAAG,EACT,KAAK,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,WAAW;CACpB,OAAO,QAAQ,SAAS,IAAI,QAAQ,MAAM,GAAG,WAAW,IAAI;AAC7D;;;;;AAUA,MAAM,cAAc,MAAqB,IAAmB,aAAkC;CAC7F,IAAI,CAAC,MACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAO;CAEnC,IAAI,CAAC,IACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAK;CAEjC,MAAM,QAAQ,kBAAkB,MAAM;EAAE;EAAU,MAAM;CAAQ,CAAC;CACjE,IAAI,CAAC,OACJ,OAAO;EAAE,IAAI;EAAO,OAAO;CAAO;CAEnC,MAAM,MAAM,kBAAkB,IAAI;EAAE;EAAU,MAAM;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AM;EACjC;CACD,GACA,KACD;CACA,IAAI,OAAO,gBACV,OAAO,uBAAuB;CAE/B,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;AACnD"}
|
|
@@ -12,9 +12,11 @@ const noticed = (shaped, context) => {
|
|
|
12
12
|
for (const message of shaped.notices) context.notice(message);
|
|
13
13
|
return shaped.collection;
|
|
14
14
|
};
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Who may write a guarded provider field (the connection fields, `isDefault`), when anything
|
|
17
|
+
* narrows the field's own access.
|
|
18
|
+
*/
|
|
19
|
+
const guardedFieldAccessOf = (resolved, own) => {
|
|
18
20
|
const update = own?.update ?? (resolved.scoped ? resolved.access.crossScope.named : void 0);
|
|
19
21
|
const create = own?.create;
|
|
20
22
|
return create || update ? {
|
|
@@ -32,7 +34,8 @@ const providersCollectionOf = async (resolved, callbacks, context) => {
|
|
|
32
34
|
...source.type === "text" ? { hint: { suffix: 4 } } : {},
|
|
33
35
|
...keys ? { keys } : {}
|
|
34
36
|
});
|
|
35
|
-
const connectionAccess =
|
|
37
|
+
const connectionAccess = guardedFieldAccessOf(resolved, providers.connectionAccess);
|
|
38
|
+
const defaultAccess = guardedFieldAccessOf(resolved, providers.defaultAccess ?? providers.connectionAccess);
|
|
36
39
|
return withEncryptedQueryRewrite(checkEditorCollection(buildProvidersCollection({
|
|
37
40
|
slug: providers.slug,
|
|
38
41
|
access: providers.access,
|
|
@@ -48,7 +51,10 @@ const providersCollectionOf = async (resolved, callbacks, context) => {
|
|
|
48
51
|
isSealed,
|
|
49
52
|
allowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,
|
|
50
53
|
...connectionAccess ? { connectionAccess } : {},
|
|
51
|
-
|
|
54
|
+
...defaultAccess ? { defaultAccess } : {},
|
|
55
|
+
types: providers.types,
|
|
56
|
+
staticLabel: context.staticLabel,
|
|
57
|
+
listNotice: [...resolved.sources.policies.values()].includes("fallback")
|
|
52
58
|
}), {
|
|
53
59
|
role: "providers",
|
|
54
60
|
option: "providers.collection",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pluginCollections.js","names":[],"sources":["../../src/plugin/pluginCollections.ts"],"sourcesContent":["import type { CollectionConfig, Config, PayloadRequest } from 'payload'\nimport type { ResolvedOptions } from '../core/options'\nimport { buildGoalsCollection } from '../goals/collection'\nimport { STATE_SLUG } from '../native/collections/slugs'\nimport { stateCollection } from '../native/collections/state'\nimport type { BuildSecretField, ConnectionFieldAccess } from '../providers/collection'\nimport { buildProvidersCollection } from '../providers/collection'\nimport { cacheCollection } from '../surfacing/cacheCollection'\nimport { syncCollection } from '../sync/collection'\nimport type { StaticLabelFor } from '../translations/staticLabel'\nimport {\n\tcheckEditorCollection,\n\ttype ShapedCollection,\n\tshapeCollection,\n\tslugOfRole,\n} from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport type { ScopeChange } from './scopeChange'\n\n/** What the plugin's collections are registered against. */\nexport interface CollectionContext {\n\t/** `config.db.name`, which decides whether Postgres' identifier limit applies. */\n\tdb: string | undefined\n\t/** Keeps what the boot warns about until the instance can log it. */\n\tnotice: (message: string) => void\n\t/** The install's static labels, its own strings over the built-in ones. */\n\tstaticLabel: StaticLabelFor\n}\n\n/** The collection a shaping produced, its notices handed on. */\nconst noticed = (shaped: ShapedCollection, context: CollectionContext): CollectionConfig => {\n\tfor (const message of shaped.notices) {\n\t\tcontext.notice(message)\n\t}\n\treturn shaped.collection\n}\n\n/** What the providers and goals collections call back into, the same whether the plugin runs or not. */\ninterface CollectionCallbacks {\n\tresolveAdminScope: (req: PayloadRequest) => Promise<string | null>\n\t/** Told what a save to either collection changed; a switched-off install's runtime is absent. */\n\tonChange: (\n\t\tcollection: 'providers' | 'goals'\n\t) => (change: ScopeChange, req: PayloadRequest) => void\n}\n\n/** Who may write a provider's connection fields, when anything narrows the field's own access. */\nconst connectionAccessOf = (resolved: ResolvedOptions): ConnectionFieldAccess | undefined => {\n\tconst own = resolved.providers.collection.connectionAccess\n\t// A new document has no stored key to redirect, so only a host's own `connectionAccess`\n\t// gates create; an update on a scoped install takes the named cross-scope gate.\n\tconst update = own?.update ?? (resolved.scoped ? resolved.access.crossScope.named : undefined)\n\tconst create = own?.create\n\treturn create || update\n\t\t? { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n\t\t: undefined\n}\n\nconst providersCollectionOf = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig> => {\n\tconst { encryptedField, isSealed, withEncryptedQueryRewrite } = await loadEncrypted()\n\tconst providers = resolved.providers.collection\n\tconst keys = providers.encryption?.keys\n\tconst buildSecret: BuildSecretField = (source) =>\n\t\tencryptedField(source, {\n\t\t\tprotection: 'writeOnly',\n\t\t\taadScope: '10x-analytics:providers',\n\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t...(keys ? { keys } : {}),\n\t\t})\n\tconst connectionAccess = connectionAccessOf(resolved)\n\tconst built = buildProvidersCollection({\n\t\tslug: providers.slug,\n\t\taccess: providers.access,\n\t\tfields: providers.fields,\n\t\toverrides: providers.overrides,\n\t\tonChange: callbacks.onChange('providers'),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: providers.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tbuildSecret,\n\t\tisSealed,\n\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t...(connectionAccess ? { connectionAccess } : {}),\n\t\tstaticLabel: context.staticLabel,\n\t})\n\tconst checked = checkEditorCollection(built, {\n\t\trole: 'providers',\n\t\toption: 'providers.collection',\n\t\tslug: providers.slug,\n\t\tdb: context.db,\n\t})\n\t// Always wrapped: a second wrap by the host's fields plugin is inert (writeOnly has no blind\n\t// index), while skipping leaks ciphertext when fields() runs before this collection exists.\n\treturn withEncryptedQueryRewrite(checked)\n}\n\nconst goalsCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): CollectionConfig => {\n\tconst goals = resolved.goalsCollection\n\tconst built = buildGoalsCollection({\n\t\tslug: goals.slug,\n\t\taccess: goals.access,\n\t\tfields: goals.fields,\n\t\toverrides: goals.overrides,\n\t\tonChange: callbacks.onChange('goals'),\n\t\trevenue: resolved.revenue.enabled,\n\t\t// A per-scope resolver has no request to answer for here, so only a fixed code is\n\t\t// offered as the default.\n\t\t...(typeof resolved.revenue.currency === 'string'\n\t\t\t? { defaultCurrency: resolved.revenue.currency }\n\t\t\t: {}),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: goals.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn checkEditorCollection(built, {\n\t\trole: 'goals',\n\t\toption: 'goals.collection',\n\t\tslug: goals.slug,\n\t\tdb: context.db,\n\t})\n}\n\n/**\n * The providers and goals collections an install turned on, built exactly alike whether the plugin\n * runs or only keeps its schema (`disabled: true`), so neither drops a field or an index.\n */\nexport const configCollections = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig[]> => [\n\t...(resolved.providers.collection.enabled\n\t\t? [await providersCollectionOf(resolved, callbacks, context)]\n\t\t: []),\n\t...(resolved.goalsCollection.enabled ? [goalsCollectionOf(resolved, callbacks, context)] : []),\n]\n\n/**\n * The sync collection when sync is on, after the host's overrides, built alike whether the plugin\n * runs or not.\n */\nexport const syncCollectionOf = (\n\tresolved: ResolvedOptions,\n\tresolveAdminScope: CollectionCallbacks['resolveAdminScope'],\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (!resolved.sync.enabled) {\n\t\treturn undefined\n\t}\n\tconst { slug, hidden, overrides } = resolved.sync.collection\n\tconst built = syncCollection(slug, {\n\t\thidden,\n\t\taccess: {\n\t\t\tscoped: resolved.scoped,\n\t\t\tscopeField: 'scope',\n\t\t\tresolveScope: resolveAdminScope,\n\t\t\tmember: resolved.scope.member,\n\t\t\tcrossScope: resolved.access.crossScope.named,\n\t\t},\n\t\tread: resolved.access.read,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'sync',\n\t\t\toption: 'sync.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/** The read cache collection after the host's overrides, unless a `cache.store` replaces it. */\nexport const cacheCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (resolved.cache.store) {\n\t\treturn undefined\n\t}\n\tconst { slug, overrides } = resolved.cache.collection\n\tconst built = cacheCollection({ slug, mongo: context.db === 'mongoose' })\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'cache',\n\t\t\toption: 'cache.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/**\n * Whether the install registers a task that takes a lease and stamps a heartbeat, which live in\n * `analytics-state`: sync or warming, while `jobs` registers tasks.\n */\nconst needsStateCollection = (resolved: ResolvedOptions): boolean =>\n\tresolved.jobs !== false && (resolved.sync.enabled || resolved.cache.warm.enabled)\n\n/**\n * `analytics-state` for the sync and warm tasks, after `jobs.state`, unless an adapter (the native\n * engine) registered its own. Refuses `jobs.state` wherever it would shape nothing.\n */\nexport const addStateCollection = (\n\tconfig: Config,\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): void => {\n\tconst option = resolved.jobs === false ? undefined : resolved.jobs.state\n\tconst registered = slugOfRole(config.collections, 'state')\n\tif (option && registered !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: jobs.state shapes the analytics-state collection of an install without native(), but native() registers its own (\"${registered}\"). Rename or reshape it with native({ collections: { state } }) instead.`\n\t\t)\n\t}\n\tif (!needsStateCollection(resolved)) {\n\t\tif (option) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: jobs.state shapes the collection the sync and warm tasks keep their leases in, and this install runs neither. Turn sync or cache.warm on, or remove it.'\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\tif (registered !== undefined) {\n\t\treturn\n\t}\n\tconst state = noticed(\n\t\tshapeCollection(stateCollection(option?.slug ?? STATE_SLUG), {\n\t\t\trole: 'state',\n\t\t\toption: 'jobs.state',\n\t\t\tdb: context.db,\n\t\t\t...(option?.overrides ? { overrides: option.overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n\tconfig.collections = [...(config.collections ?? []), state]\n}\n"],"mappings":";;;;;;;;;;AA8BA,MAAM,WAAW,QAA0B,YAAiD;CAC3F,KAAK,MAAM,WAAW,OAAO,SAC5B,QAAQ,OAAO,OAAO;CAEvB,OAAO,OAAO;AACf;;AAYA,MAAM,sBAAsB,aAAiE;CAC5F,MAAM,MAAM,SAAS,UAAU,WAAW;CAG1C,MAAM,SAAS,KAAK,WAAW,SAAS,SAAS,SAAS,OAAO,WAAW,QAAQ,KAAA;CACpF,MAAM,SAAS,KAAK;CACpB,OAAO,UAAU,SACd;EAAE,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAI,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAAG,IAC/D,KAAA;AACJ;AAEA,MAAM,wBAAwB,OAC7B,UACA,WACA,YAC+B;CAC/B,MAAM,EAAE,gBAAgB,UAAU,8BAA8B,MAAM,cAAc;CACpF,MAAM,YAAY,SAAS,UAAU;CACrC,MAAM,OAAO,UAAU,YAAY;CACnC,MAAM,eAAiC,WACtC,eAAe,QAAQ;EACtB,YAAY;EACZ,UAAU;EACV,GAAI,OAAO,SAAS,SAAS,EAAE,MAAM,EAAE,Q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AM,IAAI,MACT,oKACD;EAED;CACD;CACA,IAAI,eAAe,KAAA,GAClB;CAED,MAAM,QAAQ,QACb,gBAAgB,gBAAgB,QAAQ,QAAA,iBAAkB,GAAG;EAC5D,MAAM;EACN,QAAQ;EACR,IAAI,QAAQ;EACZ,GAAI,QAAQ,YAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;CAC5D,CAAC,GACD,OACD;CACA,OAAO,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,GAAI,KAAK;AAC3D"}
|
|
1
|
+
{"version":3,"file":"pluginCollections.js","names":[],"sources":["../../src/plugin/pluginCollections.ts"],"sourcesContent":["import type { CollectionConfig, Config, PayloadRequest } from 'payload'\nimport type { ResolvedOptions } from '../core/options'\nimport { buildGoalsCollection } from '../goals/collection'\nimport { STATE_SLUG } from '../native/collections/slugs'\nimport { stateCollection } from '../native/collections/state'\nimport type { BuildSecretField, ConnectionFieldAccess } from '../providers/collection'\nimport { buildProvidersCollection } from '../providers/collection'\nimport { cacheCollection } from '../surfacing/cacheCollection'\nimport { syncCollection } from '../sync/collection'\nimport type { StaticLabelFor } from '../translations/staticLabel'\nimport {\n\tcheckEditorCollection,\n\ttype ShapedCollection,\n\tshapeCollection,\n\tslugOfRole,\n} from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport type { ScopeChange } from './scopeChange'\n\n/** What the plugin's collections are registered against. */\nexport interface CollectionContext {\n\t/** `config.db.name`, which decides whether Postgres' identifier limit applies. */\n\tdb: string | undefined\n\t/** Keeps what the boot warns about until the instance can log it. */\n\tnotice: (message: string) => void\n\t/** The install's static labels, its own strings over the built-in ones. */\n\tstaticLabel: StaticLabelFor\n}\n\n/** The collection a shaping produced, its notices handed on. */\nconst noticed = (shaped: ShapedCollection, context: CollectionContext): CollectionConfig => {\n\tfor (const message of shaped.notices) {\n\t\tcontext.notice(message)\n\t}\n\treturn shaped.collection\n}\n\n/** What the providers and goals collections call back into, the same whether the plugin runs or not. */\ninterface CollectionCallbacks {\n\tresolveAdminScope: (req: PayloadRequest) => Promise<string | null>\n\t/** Told what a save to either collection changed; a switched-off install's runtime is absent. */\n\tonChange: (\n\t\tcollection: 'providers' | 'goals'\n\t) => (change: ScopeChange, req: PayloadRequest) => void\n}\n\n/**\n * Who may write a guarded provider field (the connection fields, `isDefault`), when anything\n * narrows the field's own access.\n */\nconst guardedFieldAccessOf = (\n\tresolved: ResolvedOptions,\n\town: ConnectionFieldAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\t// A new document has no stored key to redirect, so only a host's own option gates create; an\n\t// update on a scoped install takes the named cross-scope gate.\n\tconst update = own?.update ?? (resolved.scoped ? resolved.access.crossScope.named : undefined)\n\tconst create = own?.create\n\treturn create || update\n\t\t? { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n\t\t: undefined\n}\n\nconst providersCollectionOf = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig> => {\n\tconst { encryptedField, isSealed, withEncryptedQueryRewrite } = await loadEncrypted()\n\tconst providers = resolved.providers.collection\n\tconst keys = providers.encryption?.keys\n\tconst buildSecret: BuildSecretField = (source) =>\n\t\tencryptedField(source, {\n\t\t\tprotection: 'writeOnly',\n\t\t\taadScope: '10x-analytics:providers',\n\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t...(keys ? { keys } : {}),\n\t\t})\n\tconst connectionAccess = guardedFieldAccessOf(resolved, providers.connectionAccess)\n\tconst defaultAccess = guardedFieldAccessOf(\n\t\tresolved,\n\t\tproviders.defaultAccess ?? providers.connectionAccess\n\t)\n\tconst built = buildProvidersCollection({\n\t\tslug: providers.slug,\n\t\taccess: providers.access,\n\t\tfields: providers.fields,\n\t\toverrides: providers.overrides,\n\t\tonChange: callbacks.onChange('providers'),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: providers.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tbuildSecret,\n\t\tisSealed,\n\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t...(connectionAccess ? { connectionAccess } : {}),\n\t\t...(defaultAccess ? { defaultAccess } : {}),\n\t\ttypes: providers.types,\n\t\tstaticLabel: context.staticLabel,\n\t\tlistNotice: [...resolved.sources.policies.values()].includes('fallback'),\n\t})\n\tconst checked = checkEditorCollection(built, {\n\t\trole: 'providers',\n\t\toption: 'providers.collection',\n\t\tslug: providers.slug,\n\t\tdb: context.db,\n\t})\n\t// Always wrapped: a second wrap by the host's fields plugin is inert (writeOnly has no blind\n\t// index), while skipping leaks ciphertext when fields() runs before this collection exists.\n\treturn withEncryptedQueryRewrite(checked)\n}\n\nconst goalsCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): CollectionConfig => {\n\tconst goals = resolved.goalsCollection\n\tconst built = buildGoalsCollection({\n\t\tslug: goals.slug,\n\t\taccess: goals.access,\n\t\tfields: goals.fields,\n\t\toverrides: goals.overrides,\n\t\tonChange: callbacks.onChange('goals'),\n\t\trevenue: resolved.revenue.enabled,\n\t\t// A per-scope resolver has no request to answer for here, so only a fixed code is\n\t\t// offered as the default.\n\t\t...(typeof resolved.revenue.currency === 'string'\n\t\t\t? { defaultCurrency: resolved.revenue.currency }\n\t\t\t: {}),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: goals.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn checkEditorCollection(built, {\n\t\trole: 'goals',\n\t\toption: 'goals.collection',\n\t\tslug: goals.slug,\n\t\tdb: context.db,\n\t})\n}\n\n/**\n * The providers and goals collections an install turned on, built exactly alike whether the plugin\n * runs or only keeps its schema (`disabled: true`), so neither drops a field or an index.\n */\nexport const configCollections = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig[]> => [\n\t...(resolved.providers.collection.enabled\n\t\t? [await providersCollectionOf(resolved, callbacks, context)]\n\t\t: []),\n\t...(resolved.goalsCollection.enabled ? [goalsCollectionOf(resolved, callbacks, context)] : []),\n]\n\n/**\n * The sync collection when sync is on, after the host's overrides, built alike whether the plugin\n * runs or not.\n */\nexport const syncCollectionOf = (\n\tresolved: ResolvedOptions,\n\tresolveAdminScope: CollectionCallbacks['resolveAdminScope'],\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (!resolved.sync.enabled) {\n\t\treturn undefined\n\t}\n\tconst { slug, hidden, overrides } = resolved.sync.collection\n\tconst built = syncCollection(slug, {\n\t\thidden,\n\t\taccess: {\n\t\t\tscoped: resolved.scoped,\n\t\t\tscopeField: 'scope',\n\t\t\tresolveScope: resolveAdminScope,\n\t\t\tmember: resolved.scope.member,\n\t\t\tcrossScope: resolved.access.crossScope.named,\n\t\t},\n\t\tread: resolved.access.read,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'sync',\n\t\t\toption: 'sync.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/** The read cache collection after the host's overrides, unless a `cache.store` replaces it. */\nexport const cacheCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (resolved.cache.store) {\n\t\treturn undefined\n\t}\n\tconst { slug, overrides } = resolved.cache.collection\n\tconst built = cacheCollection({ slug, mongo: context.db === 'mongoose' })\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'cache',\n\t\t\toption: 'cache.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/**\n * Whether the install registers a task that takes a lease and stamps a heartbeat, which live in\n * `analytics-state`: sync or warming, while `jobs` registers tasks.\n */\nconst needsStateCollection = (resolved: ResolvedOptions): boolean =>\n\tresolved.jobs !== false && (resolved.sync.enabled || resolved.cache.warm.enabled)\n\n/**\n * `analytics-state` for the sync and warm tasks, after `jobs.state`, unless an adapter (the native\n * engine) registered its own. Refuses `jobs.state` wherever it would shape nothing.\n */\nexport const addStateCollection = (\n\tconfig: Config,\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): void => {\n\tconst option = resolved.jobs === false ? undefined : resolved.jobs.state\n\tconst registered = slugOfRole(config.collections, 'state')\n\tif (option && registered !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: jobs.state shapes the analytics-state collection of an install without native(), but native() registers its own (\"${registered}\"). Rename or reshape it with native({ collections: { state } }) instead.`\n\t\t)\n\t}\n\tif (!needsStateCollection(resolved)) {\n\t\tif (option) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: jobs.state shapes the collection the sync and warm tasks keep their leases in, and this install runs neither. Turn sync or cache.warm on, or remove it.'\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\tif (registered !== undefined) {\n\t\treturn\n\t}\n\tconst state = noticed(\n\t\tshapeCollection(stateCollection(option?.slug ?? STATE_SLUG), {\n\t\t\trole: 'state',\n\t\t\toption: 'jobs.state',\n\t\t\tdb: context.db,\n\t\t\t...(option?.overrides ? { overrides: option.overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n\tconfig.collections = [...(config.collections ?? []), state]\n}\n"],"mappings":";;;;;;;;;;AA8BA,MAAM,WAAW,QAA0B,YAAiD;CAC3F,KAAK,MAAM,WAAW,OAAO,SAC5B,QAAQ,OAAO,OAAO;CAEvB,OAAO,OAAO;AACf;;;;;AAeA,MAAM,wBACL,UACA,QACuC;CAGvC,MAAM,SAAS,KAAK,WAAW,SAAS,SAAS,SAAS,OAAO,WAAW,QAAQ,KAAA;CACpF,MA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C,IAAI,SAAS,MAAM,OAClB;CAED,MAAM,EAAE,MAAM,cAAc,SAAS,MAAM;CAE3C,OAAO,QACN,gBAFa,gBAAgB;EAAE;EAAM,OAAO,QAAQ,OAAO;CAAW,CAElD,GAAG;EACtB,MAAM;EACN,QAAQ;EACR,IAAI,QAAQ;EACZ,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CAClC,CAAC,GACD,OACD;AACD;;;;;AAMA,MAAM,wBAAwB,aAC7B,SAAS,SAAS,UAAU,SAAS,KAAK,WAAW,SAAS,MAAM,KAAK;;;;;AAM1E,MAAa,sBACZ,QACA,UACA,YACU;CACV,MAAM,SAAS,SAAS,SAAS,QAAQ,KAAA,IAAY,SAAS,KAAK;CACnE,MAAM,aAAa,WAAW,OAAO,aAAa,OAAO;CACzD,IAAI,UAAU,eAAe,KAAA,GAC5B,MAAM,IAAI,MACT,gIAAgI,WAAW,0EAC5I;CAED,IAAI,CAAC,qBAAqB,QAAQ,GAAG;EACpC,IAAI,QACH,MAAM,IAAI,MACT,oKACD;EAED;CACD;CACA,IAAI,eAAe,KAAA,GAClB;CAED,MAAM,QAAQ,QACb,gBAAgB,gBAAgB,QAAQ,QAAA,iBAAkB,GAAG;EAC5D,MAAM;EACN,QAAQ;EACR,IAAI,QAAQ;EACZ,GAAI,QAAQ,YAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;CAC5D,CAAC,GACD,OACD;CACA,OAAO,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,GAAI,KAAK;AAC3D"}
|
|
@@ -129,7 +129,7 @@ const makeQueryHandler = () => async (req) => {
|
|
|
129
129
|
...currency ? { currency } : {},
|
|
130
130
|
source: {
|
|
131
131
|
id: adapter.id,
|
|
132
|
-
label: adapter.label,
|
|
132
|
+
label: context.sources.find((source) => source.id === adapter.id)?.label ?? adapter.label,
|
|
133
133
|
kind: runtime.configAdapterIds.has(adapter.id) ? "config" : "runtime"
|
|
134
134
|
},
|
|
135
135
|
capabilities,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { currentDate } from '../core/clock'\nimport type { AnalyticsQuery, AnalyticsResult, DateRange } from '../core/contract'\nimport { aliasMetrics, askedResult, servedQuery } from '../core/metricAliases'\nimport { resolveQueryScope, resolveRequestedScope } from '../core/scopedRead'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { revenueCurrencyOf } from '../goals/currency'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport type { ReadOptions } from '../surfacing/engine'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { goalHintFor } from './goalHint'\nimport { itemRefsOf, resolveItemLabels } from './itemLabels'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { readFailureResponse } from './readFailure'\nimport {\n\tgetRuntime,\n\tresolvableScope,\n\tresolveCurrencyFor,\n\tresolveTimezoneFor,\n\tscopeGates,\n} from './runtime'\n\n/**\n * The query as the response echoes it, the range as ISO strings. `goalSlugs` rides along: the\n * scope's slugs, `[]` for no goals, or `'unresolved'` when the resolver failed.\n */\nexport const serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\nconst noSourceResponse = (): Response =>\n\terrorResponse(\n\t\t404,\n\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t)\n\n/**\n * Authenticated GET over the surfacing engine, gated in order (auth, `access.read`, scope, source,\n * capabilities) so no answer leaks past the caller's entitlement. Upstream error text never leaks.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn readDeniedResponse()\n\t\t}\n\t\tconst params = queryParams(req)\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\traw: params.get('scope'),\n\t\t\tgates,\n\t\t})\n\t\tif (!requested.ok) {\n\t\t\t// A request whose own scope will not resolve answers like a scope with no sources.\n\t\t\t// A scope the caller named, or one its user does not belong to, is refused as such.\n\t\t\treturn requested.reason === 'named' || requested.reason === 'not-member'\n\t\t\t\t? untrustedScopeResponse('scope')\n\t\t\t\t: noSourceResponse()\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, { gates, scope: requested.gated })\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn noSourceResponse()\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tanalyticsError('unknown_source', 'analytics: unknown source', 'source')\n\t\t\t)\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'forbidden',\n\t\t\t\t\t'analytics: this source cannot be read for your scope',\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst ownScope = resolvableScope(context.scope)\n\t\tconst timezone = await resolveTimezoneFor(runtime, req, ownScope)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst hint = await goalHintFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: ownScope,\n\t\t\tmetrics: parsed.value.query.metrics,\n\t\t\tdimensions: parsed.value.query.dimensions,\n\t\t})\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t\t...(hint === undefined ? {} : { goalSlugs: hint.slugs }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\t// The view decides this same predicate on the browser clock, so a client near the\n\t\t\t// floor or with a skewed clock must lose only its delta, never the whole read.\n\t\t\tif (\n\t\t\t\t!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, {\n\t\t\t\t\ttz: query.timezone,\n\t\t\t\t\tnow: currentDate(),\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\t// The view names the preset its days came from, so the engine can store the read for the warm\n\t\t// task when those days are the preset's today; any other window stores nothing.\n\t\tconst readOptions: ReadOptions = {\n\t\t\twhenBusy: 'refuse',\n\t\t\tpriority: 'interactive',\n\t\t\t...(parsed.value.timeframe === null ? {} : { timeframe: parsed.value.timeframe }),\n\t\t}\n\t\t// Read under the source's own names and answered under the caller's: `visits` from native.\n\t\tconst aliased = aliasMetrics(query.metrics, adapter.capabilities.metrics)\n\t\tconst served = servedQuery(query, aliased)\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\tconst [read, previous] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, served, readOptions),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...served, dateRange: comparisonRange }, readOptions)\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t\tresult = askedResult(read, aliased)\n\t\t\tcomparison = previous && askedResult(previous, aliased)\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${describeWithCauses(err)}`\n\t\t\t)\n\t\t\treturn readFailureResponse(err)\n\t\t}\n\t\t// A shallow copy, since the cached entry is shared between requests and reporting currency\n\t\t// resolves per scope. A source naming its own revenue currency keeps it.\n\t\tconst reporting = revenueCurrencyOf(\n\t\t\tquery.filters,\n\t\t\tawait resolveCurrencyFor(runtime, req, ownScope)\n\t\t)\n\t\tconst withCurrency = (read: AnalyticsResult): AnalyticsResult =>\n\t\t\treporting && read.meta.currency === undefined\n\t\t\t\t? { ...read, meta: { ...read.meta, currency: reporting } }\n\t\t\t\t: read\n\t\tconst currency = result.meta.currency ?? reporting\n\t\t// Resolved per request rather than cached with the read: a title is whatever this reader\n\t\t// may see of the document, and the cached rows are shared by every reader of the scope.\n\t\tconst refs = itemRefsOf(query, [result, comparison])\n\t\tconst itemLabels = refs.length > 0 ? await resolveItemLabels(req, refs) : undefined\n\t\tconst body: QueryResponse = {\n\t\t\tresult: withCurrency(result),\n\t\t\t...(comparison ? { comparison: withCurrency(comparison) } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t\t...(hint && hint.builtin.length > 0 ? { builtinGoalSlugs: hint.builtin } : {}),\n\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBAAkB,WAAqD;CACnF,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;AAEA,MAAM,yBACL,cACC,KACA,eAAe,kBAAkB,oDAAoD,CACtF;;;;;AAMD,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,qBAAqB;CAE7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,qBAAqB;CAE7B,IAAI,YAAY;CAChB,IAAI;EACH,IAAI,CAAE,MAAM,SAAS,SAAS,GAAG,GAChC,OAAO,mBAAmB;EAE3B,MAAM,SAAS,YAAY,GAAG;EAC9B,MAAM,QAAQ,WAAW,SAAS,GAAG;EACrC,MAAM,YAAY,MAAM,sBAAsB;GAC7C;GACA;GACA,KAAK,OAAO,IAAI,OAAO;GACvB;EACD,CAAC;EACD,IAAI,CAAC,UAAU,IAGd,OAAO,UAAU,WAAW,WAAW,UAAU,WAAW,eACzD,uBAAuB,OAAO,IAC9B,iBAAiB;EAErB,MAAM,UAAU,MAAM,yBAAyB,KAAK;GAAE;GAAO,OAAO,UAAU;EAAM,CAAC;EACrF,IAAI,QAAQ,SAAS,SAAS,GAC7B,OAAO,iBAAiB;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,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;GAC3B,GAAI,QAAQ,KAAK,QAAQ,SAAS,IAAI,EAAE,kBAAkB,KAAK,QAAQ,IAAI,CAAC;GAC5E,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACpC;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,MAAM,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC9F,OAAO,cAAc,KAAK,eAAe,YAAY,yBAAyB,CAAC;CAChF;AACD"}
|
|
1
|
+
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { currentDate } from '../core/clock'\nimport type { AnalyticsQuery, AnalyticsResult, DateRange } from '../core/contract'\nimport { aliasMetrics, askedResult, servedQuery } from '../core/metricAliases'\nimport { resolveQueryScope, resolveRequestedScope } from '../core/scopedRead'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { revenueCurrencyOf } from '../goals/currency'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport type { ReadOptions } from '../surfacing/engine'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { goalHintFor } from './goalHint'\nimport { itemRefsOf, resolveItemLabels } from './itemLabels'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { readFailureResponse } from './readFailure'\nimport {\n\tgetRuntime,\n\tresolvableScope,\n\tresolveCurrencyFor,\n\tresolveTimezoneFor,\n\tscopeGates,\n} from './runtime'\n\n/**\n * The query as the response echoes it, the range as ISO strings. `goalSlugs` rides along: the\n * scope's slugs, `[]` for no goals, or `'unresolved'` when the resolver failed.\n */\nexport const serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\nconst noSourceResponse = (): Response =>\n\terrorResponse(\n\t\t404,\n\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t)\n\n/**\n * Authenticated GET over the surfacing engine, gated in order (auth, `access.read`, scope, source,\n * capabilities) so no answer leaks past the caller's entitlement. Upstream error text never leaks.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn readDeniedResponse()\n\t\t}\n\t\tconst params = queryParams(req)\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\traw: params.get('scope'),\n\t\t\tgates,\n\t\t})\n\t\tif (!requested.ok) {\n\t\t\t// A request whose own scope will not resolve answers like a scope with no sources.\n\t\t\t// A scope the caller named, or one its user does not belong to, is refused as such.\n\t\t\treturn requested.reason === 'named' || requested.reason === 'not-member'\n\t\t\t\t? untrustedScopeResponse('scope')\n\t\t\t\t: noSourceResponse()\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, { gates, scope: requested.gated })\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn noSourceResponse()\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tanalyticsError('unknown_source', 'analytics: unknown source', 'source')\n\t\t\t)\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'forbidden',\n\t\t\t\t\t'analytics: this source cannot be read for your scope',\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst ownScope = resolvableScope(context.scope)\n\t\tconst timezone = await resolveTimezoneFor(runtime, req, ownScope)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst hint = await goalHintFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: ownScope,\n\t\t\tmetrics: parsed.value.query.metrics,\n\t\t\tdimensions: parsed.value.query.dimensions,\n\t\t})\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t\t...(hint === undefined ? {} : { goalSlugs: hint.slugs }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\t// The view decides this same predicate on the browser clock, so a client near the\n\t\t\t// floor or with a skewed clock must lose only its delta, never the whole read.\n\t\t\tif (\n\t\t\t\t!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, {\n\t\t\t\t\ttz: query.timezone,\n\t\t\t\t\tnow: currentDate(),\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\t// The view names the preset its days came from, so the engine can store the read for the warm\n\t\t// task when those days are the preset's today; any other window stores nothing.\n\t\tconst readOptions: ReadOptions = {\n\t\t\twhenBusy: 'refuse',\n\t\t\tpriority: 'interactive',\n\t\t\t...(parsed.value.timeframe === null ? {} : { timeframe: parsed.value.timeframe }),\n\t\t}\n\t\t// Read under the source's own names and answered under the caller's: `visits` from native.\n\t\tconst aliased = aliasMetrics(query.metrics, adapter.capabilities.metrics)\n\t\tconst served = servedQuery(query, aliased)\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\tconst [read, previous] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, served, readOptions),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...served, dateRange: comparisonRange }, readOptions)\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t\tresult = askedResult(read, aliased)\n\t\t\tcomparison = previous && askedResult(previous, aliased)\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${describeWithCauses(err)}`\n\t\t\t)\n\t\t\treturn readFailureResponse(err)\n\t\t}\n\t\t// A shallow copy, since the cached entry is shared between requests and reporting currency\n\t\t// resolves per scope. A source naming its own revenue currency keeps it.\n\t\tconst reporting = revenueCurrencyOf(\n\t\t\tquery.filters,\n\t\t\tawait resolveCurrencyFor(runtime, req, ownScope)\n\t\t)\n\t\tconst withCurrency = (read: AnalyticsResult): AnalyticsResult =>\n\t\t\treporting && read.meta.currency === undefined\n\t\t\t\t? { ...read, meta: { ...read.meta, currency: reporting } }\n\t\t\t\t: read\n\t\tconst currency = result.meta.currency ?? reporting\n\t\t// Resolved per request rather than cached with the read: a title is whatever this reader\n\t\t// may see of the document, and the cached rows are shared by every reader of the scope.\n\t\tconst refs = itemRefsOf(query, [result, comparison])\n\t\tconst itemLabels = refs.length > 0 ? await resolveItemLabels(req, refs) : undefined\n\t\tconst body: QueryResponse = {\n\t\t\tresult: withCurrency(result),\n\t\t\t...(comparison ? { comparison: withCurrency(comparison) } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: context.sources.find((source) => source.id === adapter.id)?.label ?? adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t\t...(hint && hint.builtin.length > 0 ? { builtinGoalSlugs: hint.builtin } : {}),\n\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBAAkB,WAAqD;CACnF,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;AAEA,MAAM,yBACL,cACC,KACA,eAAe,kBAAkB,oDAAoD,CACtF;;;;;AAMD,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,qBAAqB;CAE7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,qBAAqB;CAE7B,IAAI,YAAY;CAChB,IAAI;EACH,IAAI,CAAE,MAAM,SAAS,SAAS,GAAG,GAChC,O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AAW,OAAO,KAAK,YAAY;EAGzC,MAAM,OAAO,WAAW,OAAO,CAAC,QAAQ,UAAU,CAAC;EACnD,MAAM,aAAa,KAAK,SAAS,IAAI,MAAM,kBAAkB,KAAK,IAAI,IAAI,KAAA;EAC1E,MAAM,OAAsB;GAC3B,QAAQ,aAAa,MAAM;GAC3B,GAAI,aAAa,EAAE,YAAY,aAAa,UAAU,EAAE,IAAI,CAAC;GAC7D,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;GAC/B,QAAQ;IACP,IAAI,QAAQ;IACZ,OAAO,QAAQ,QAAQ,MAAM,WAAW,OAAO,OAAO,QAAQ,EAAE,GAAG,SAAS,QAAQ;IACpF,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;GAC3B,GAAI,QAAQ,KAAK,QAAQ,SAAS,IAAI,EAAE,kBAAkB,KAAK,QAAQ,IAAI,CAAC;GAC5E,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACpC;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,MAAM,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC9F,OAAO,cAAc,KAAK,eAAe,YAAY,yBAAyB,CAAC;CAChF;AACD"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { PayloadRequest } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/plugin/readContextForRequest.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* What a listing tells its reader about itself: `platformFallback` when a shared source is listed
|
|
6
|
+
* only because the scope has no source of its own yet (`sources.<id>.tenants: 'fallback'`).
|
|
7
|
+
*/
|
|
8
|
+
type SourcesNotice = 'platformFallback';
|
|
9
|
+
//#endregion
|
|
10
|
+
export { SourcesNotice };
|
|
11
|
+
//# sourceMappingURL=readContextForRequest.d.ts.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { readGate } from "../access/readGate.js";
|
|
2
2
|
import { isGatedScope } from "../access/principal.js";
|
|
3
3
|
import { getRuntime, resolvableScope, resolveRegistryFor, scopeGates } from "./runtime.js";
|
|
4
|
-
import {
|
|
4
|
+
import { sourceRefFor } from "../core/sourceLabel.js";
|
|
5
|
+
import { needsUnscopedSourceAccess, resolveRequestedScope, visibleSourcesFor } from "../core/scopedRead.js";
|
|
5
6
|
import { serializeCapabilities } from "../core/capabilities.js";
|
|
6
7
|
//#region src/plugin/readContextForRequest.ts
|
|
7
8
|
const empty = () => ({
|
|
@@ -10,16 +11,18 @@ const empty = () => ({
|
|
|
10
11
|
adapters: /* @__PURE__ */ new Map(),
|
|
11
12
|
scope: null
|
|
12
13
|
});
|
|
13
|
-
const fromRegistry = (args) => {
|
|
14
|
-
const { runtime, registry, scope } = args;
|
|
14
|
+
const fromRegistry = async (args) => {
|
|
15
|
+
const { runtime, req, registry, scope } = args;
|
|
15
16
|
const adapters = registry.all();
|
|
16
17
|
return {
|
|
17
|
-
sources: adapters.map((adapter) => ({
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
sources: await Promise.all(adapters.map(async (adapter) => ({
|
|
19
|
+
...await sourceRefFor(adapter, {
|
|
20
|
+
req,
|
|
21
|
+
scope,
|
|
22
|
+
configIds: runtime.configAdapterIds
|
|
23
|
+
}),
|
|
21
24
|
capabilities: serializeCapabilities(adapter.capabilities)
|
|
22
|
-
})),
|
|
25
|
+
}))),
|
|
23
26
|
defaultId: registry.default().id,
|
|
24
27
|
adapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),
|
|
25
28
|
scope
|
|
@@ -59,8 +62,9 @@ const resolveSourcesForRequest = async (req, args = {}) => {
|
|
|
59
62
|
return empty();
|
|
60
63
|
}
|
|
61
64
|
const gates = args.gates ?? scopeGates(runtime, req);
|
|
62
|
-
const degrade = () => runtime.scoped ? empty() : fromRegistry({
|
|
65
|
+
const degrade = async () => runtime.scoped ? empty() : fromRegistry({
|
|
63
66
|
runtime,
|
|
67
|
+
req,
|
|
64
68
|
registry: runtime.registry,
|
|
65
69
|
scope: null
|
|
66
70
|
});
|
|
@@ -78,7 +82,7 @@ const resolveSourcesForRequest = async (req, args = {}) => {
|
|
|
78
82
|
if (!requested.ok) return requested.reason === "failed" ? degrade() : empty();
|
|
79
83
|
scope = requested.scope;
|
|
80
84
|
}
|
|
81
|
-
const registry = await
|
|
85
|
+
const { registry, fallbackAdmitted } = await visibleSourcesFor({
|
|
82
86
|
runtime,
|
|
83
87
|
req,
|
|
84
88
|
resolved: await resolveRegistryFor(runtime, {
|
|
@@ -89,14 +93,20 @@ const resolveSourcesForRequest = async (req, args = {}) => {
|
|
|
89
93
|
scope,
|
|
90
94
|
gates
|
|
91
95
|
});
|
|
92
|
-
|
|
93
|
-
runtime,
|
|
94
|
-
registry,
|
|
95
|
-
scope
|
|
96
|
-
})) : {
|
|
96
|
+
if (!registry) return {
|
|
97
97
|
...empty(),
|
|
98
98
|
scope
|
|
99
99
|
};
|
|
100
|
+
const listed = narrowToScope(runtime, await fromRegistry({
|
|
101
|
+
runtime,
|
|
102
|
+
req,
|
|
103
|
+
registry,
|
|
104
|
+
scope
|
|
105
|
+
}));
|
|
106
|
+
return listed.sources.some((source) => fallbackAdmitted.has(source.id)) ? {
|
|
107
|
+
...listed,
|
|
108
|
+
notice: "platformFallback"
|
|
109
|
+
} : listed;
|
|
100
110
|
} catch (err) {
|
|
101
111
|
req.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`);
|
|
102
112
|
return degrade();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type GatedScope, isGatedScope } from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport {\n\tneedsUnscopedSourceAccess,\n\tresolveRequestedScope,\n\
|
|
1
|
+
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type GatedScope, isGatedScope } from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport {\n\tneedsUnscopedSourceAccess,\n\tresolveRequestedScope,\n\tvisibleSourcesFor,\n} from '../core/scopedRead'\nimport { sourceRefFor } from '../core/sourceLabel'\nimport type { QuerySourceRef } from '../query/response'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolvableScope,\n\tresolveRegistryFor,\n\ttype ScopeGates,\n\tscopeGates,\n} from './runtime'\n\n/** One readable source on the wire: its identity plus the capabilities a client gates on. */\nexport interface RequestSource extends QuerySourceRef {\n\tcapabilities: SerializedCapabilities\n}\n\n/**\n * What a listing tells its reader about itself: `platformFallback` when a shared source is listed\n * only because the scope has no source of its own yet (`sources.<id>.tenants: 'fallback'`).\n */\nexport type SourcesNotice = 'platformFallback'\n\ninterface RequestSources {\n\t/** Wire rows for the resolved scope, in registry order; empty when none resolve. */\n\tsources: RequestSource[]\n\tdefaultId: string | null\n\tnotice?: SourcesNotice\n\t/** The adapters behind `sources`, for callers that read through them. */\n\tadapters: ReadonlyMap<string, AnalyticsAdapter>\n\t/** Scope the sources were resolved for; null is install-wide, `*` is cross-scope. */\n\tscope: string | null\n}\n\ninterface ResolveSourcesArgs {\n\t/**\n\t * A scope {@link resolveRequestedScope} already cleared for this request, which replaces this\n\t * call's own resolution. Only that helper mints one.\n\t */\n\tscope?: GatedScope\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\nconst empty = (): RequestSources => ({\n\tsources: [],\n\tdefaultId: null,\n\tadapters: new Map(),\n\tscope: null,\n})\n\nconst fromRegistry = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tregistry: AdapterRegistry\n\tscope: string | null\n}): Promise<RequestSources> => {\n\tconst { runtime, req, registry, scope } = args\n\tconst adapters = registry.all()\n\treturn {\n\t\tsources: await Promise.all(\n\t\t\tadapters.map(async (adapter) => ({\n\t\t\t\t...(await sourceRefFor(adapter, { req, scope, configIds: runtime.configAdapterIds })),\n\t\t\t\tcapabilities: serializeCapabilities(adapter.capabilities),\n\t\t\t}))\n\t\t),\n\t\tdefaultId: registry.default().id,\n\t\tadapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),\n\t\tscope,\n\t}\n}\n\n/**\n * Sources that can answer about one scope. Under a tenant scope a shared adapter unable to narrow\n * would report every tenant's numbers, so it is dropped however privileged the reader.\n */\nconst narrowToScope = (runtime: AnalyticsRuntime, resolved: RequestSources): RequestSources => {\n\tconst scope = resolved.scope\n\tif (scope === null) {\n\t\treturn resolved\n\t}\n\tconst narrowable = resolved.sources.filter((source) => {\n\t\tconst adapter = resolved.adapters.get(source.id)\n\t\treturn adapter !== undefined && !needsUnscopedSourceAccess(runtime, adapter, scope)\n\t})\n\tif (narrowable.length === resolved.sources.length) {\n\t\treturn resolved\n\t}\n\tconst kept = new Set(narrowable.map((source) => source.id))\n\treturn {\n\t\tsources: narrowable,\n\t\tdefaultId:\n\t\t\tresolved.defaultId !== null && kept.has(resolved.defaultId)\n\t\t\t\t? resolved.defaultId\n\t\t\t\t: (narrowable[0]?.id ?? null),\n\t\tadapters: new Map([...resolved.adapters].filter(([id]) => kept.has(id))),\n\t\tscope,\n\t}\n}\n\n/**\n * Sources a request may read, shared by every listing surface. A denied, cross-scope or non-member\n * read lists nothing; a failed resolution lists nothing when scoped, else the config registry.\n */\nexport const resolveSourcesForRequest = async (\n\treq: PayloadRequest,\n\targs: ResolveSourcesArgs = {}\n): Promise<RequestSources> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty()\n\t}\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn empty()\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: access.read failed, listing no sources: ${String(err)}`)\n\t\treturn empty()\n\t}\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst degrade = async (): Promise<RequestSources> =>\n\t\truntime.scoped\n\t\t\t? empty()\n\t\t\t: fromRegistry({ runtime, req, registry: runtime.registry, scope: null })\n\ttry {\n\t\tlet scope: string | null\n\t\tif (args.scope !== undefined) {\n\t\t\tif (!isGatedScope(args.scope)) {\n\t\t\t\treturn empty()\n\t\t\t}\n\t\t\tscope = args.scope.value\n\t\t} else {\n\t\t\tconst requested = await resolveRequestedScope({ runtime, req, gates })\n\t\t\tif (!requested.ok) {\n\t\t\t\treturn requested.reason === 'failed' ? degrade() : empty()\n\t\t\t}\n\t\t\tscope = requested.scope\n\t\t}\n\t\tconst resolved = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: resolvableScope(scope),\n\t\t})\n\t\tconst { registry, fallbackAdmitted } = await visibleSourcesFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tresolved,\n\t\t\tscope,\n\t\t\tgates,\n\t\t})\n\t\tif (!registry) {\n\t\t\treturn { ...empty(), scope }\n\t\t}\n\t\tconst listed = narrowToScope(runtime, await fromRegistry({ runtime, req, registry, scope }))\n\t\treturn listed.sources.some((source) => fallbackAdmitted.has(source.id))\n\t\t\t? { ...listed, notice: 'platformFallback' }\n\t\t\t: listed\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`)\n\t\treturn degrade()\n\t}\n}\n"],"mappings":";;;;;;;AAsDA,MAAM,eAA+B;CACpC,SAAS,CAAC;CACV,WAAW;CACX,0BAAU,IAAI,IAAI;CAClB,OAAO;AACR;AAEA,MAAM,eAAe,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;EACb,IAAI,QAAQ,QAAQ,KAAK,sDAAsD,OAAO,GAAG,GAAG;EAC5F,OAAO,MAAM;CACd;CACA,MAAM,QAAQ,KAAK,SAAS,WAAW,SAAS,GAAG;CACnD,MAAM,UAAU,YACf,QAAQ,SACL,MAAM,IACN,aAAa;EAAE;EAAS;EAAK,UAAU,QAAQ;EAAU,OAAO;CAAK,CAAC;CAC1E,IAAI;EACH,IAAI;EACJ,IAAI,KAAK,UAAU,KAAA,GAAW;GAC7B,IAAI,CAAC,aAAa,KAAK,KAAK,GAC3B,OAAO,MAAM;GAEd,QAAQ,KAAK,MAAM;EACpB,OAAO;GACN,MAAM,YAAY,MAAM,sBAAsB;IAAE;IAAS;IAAK;GAAM,CAAC;GACrE,IAAI,CAAC,UAAU,IACd,OAAO,UAAU,WAAW,WAAW,QAAQ,IAAI,MAAM;GAE1D,QAAQ,UAAU;EACnB;EAMA,MAAM,EAAE,UAAU,qBAAqB,MAAM,kBAAkB;GAC9D;GACA;GACA,UAAA,MARsB,mBAAmB,SAAS;IAClD,SAAS,IAAI;IACb;IACA,OAAO,gBAAgB,KAAK;GAC7B,CAAC;GAKA;GACA;EACD,CAAC;EACD,IAAI,CAAC,UACJ,OAAO;GAAE,GAAG,MAAM;GAAG;EAAM;EAE5B,MAAM,SAAS,cAAc,SAAS,MAAM,aAAa;GAAE;GAAS;GAAK;GAAU;EAAM,CAAC,CAAC;EAC3F,OAAO,OAAO,QAAQ,MAAM,WAAW,iBAAiB,IAAI,OAAO,EAAE,CAAC,IACnE;GAAE,GAAG;GAAQ,QAAQ;EAAmB,IACxC;CACJ,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,OAAO,GAAG,GAAG;EAC9E,OAAO,QAAQ;CAChB;AACD"}
|
package/dist/plugin/runtime.js
CHANGED
|
@@ -232,11 +232,19 @@ const goalNamesFor = async (args) => {
|
|
|
232
232
|
* admin collection.
|
|
233
233
|
*/
|
|
234
234
|
const scopeGates = (runtime, req) => {
|
|
235
|
-
const gate = (decision) => () =>
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
235
|
+
const gate = (decision) => (ctx = {}) => {
|
|
236
|
+
const { scope, adapterId } = ctx;
|
|
237
|
+
const args = {
|
|
238
|
+
req,
|
|
239
|
+
...scope === void 0 ? {} : { scope },
|
|
240
|
+
...adapterId === void 0 ? {} : { adapterId }
|
|
241
|
+
};
|
|
242
|
+
return decideOnce(req, {
|
|
243
|
+
owner: runtime,
|
|
244
|
+
key: `crossScope:${decision}:${JSON.stringify(scope)}:${adapterId ?? ""}`,
|
|
245
|
+
decide: () => runtime.crossScope?.[decision]?.(args) ?? isAdminUser({ req })
|
|
246
|
+
});
|
|
247
|
+
};
|
|
240
248
|
return {
|
|
241
249
|
named: gate("named"),
|
|
242
250
|
aggregate: gate("aggregate"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Access, Payload, PayloadRequest } from 'payload'\nimport { isAdminUser } from '../access/adminUser'\nimport { decideOnce } from '../access/decideOnce'\nimport type { ResolvedBinding } from '../binding/types'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CacheKeyEpochs } from '../core/cacheKey'\nimport { type AnalyticsAdapter, type AnalyticsResult, PLATFORM_SCOPE } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type {\n\tAnalyticsCountryFlags,\n\tCaptureGatePolicy,\n\tCaptureSlotOption,\n\tCrossScopeAccess,\n\tResolvedExclusion,\n\tResolvedOptions,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n} from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ResolveRegistryArgs,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { ServerEventInput, ServerTrackOptions } from '../core/serverEvent'\nimport { isRecord } from '../core/values'\nimport type { GoalsResolver, ResolvedGoal } from '../goals/resolver'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { CacheSweeper } from '../surfacing/cacheSweep'\nimport type { Engine } from '../surfacing/engine'\nimport { type EpochStore, epochsFor, INITIAL_EPOCH } from '../surfacing/epoch'\nimport type { Memo } from '../surfacing/memo'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport type { ResolvedAutoCapture, TrackerSkip } from '../tracker/config'\nimport { onDestroy } from './destroy'\nimport { requestMemo } from './requestMemo'\nimport { ANALYTICS_CONFIG_KEY } from './routes'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/**\n\t * Never call directly: ask {@link resolveScopeFor} or {@link resolveCaptureScopeFor}, whose\n\t * capture path strips the visitor's identity first. Absent resolves null.\n\t */\n\tresolveScope?: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\t/**\n\t * `scope.member`, set exactly when the install is scoped. A runtime without one admits nobody\n\t * to a tenant scope they did not reach through `access.crossScope`.\n\t */\n\tmember?: ScopeMemberAccess\n\t/** The plugin's reportingTimezone as a resolver; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The plugin's `revenue.currency` as a resolver; absent runtimes and installs that set\n\t * none resolve undefined, and revenue then renders as a plain number.\n\t */\n\tresolveCurrency?: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * `capture.gate`: whether a slot's tracker waits for the host's consent manager, evaluated\n\t * per request-resolved adapter. Absent runtimes hold every slot.\n\t */\n\tcaptureGate?: CaptureGatePolicy\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** `capture.skip`, resolved; absent runtimes skip everything it can. */\n\tcaptureSkip?: TrackerSkip\n\t/** Config goals, and the fallback wherever the merged resolution is unavailable. */\n\tgoals?: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal?: boolean\n\t/**\n\t * Config goals merged with the goals collection for a request's scope. Absent runtimes\n\t * fall back to `goals`.\n\t */\n\tresolveGoals?: GoalsResolver['resolve']\n\t/** The same merge, each goal tagged with where it came from. */\n\tresolveGoalsDetailed?: GoalsResolver['resolveDetailed']\n\t/**\n\t * The goals a reader's picker lists: collection goals as the collection's read access lets\n\t * the request's user see them. Absent runtimes list what `resolveGoalsDetailed` answers.\n\t */\n\tlistGoals?: GoalsResolver['listReadable']\n\t/** The goals a report spanning every scope names its rows by; see `goalNamesFor`. */\n\tlistGoalsAcross?: GoalsResolver['listAcross']\n\t/** Slug of the goals collection when the install enabled it; the picker links to it. */\n\tgoalsCollectionSlug?: string\n\t/**\n\t * Providers collection when enabled; it makes a scoped install's sources per tenant.\n\t * `sourceAccess` picks which documents a tenant reads through, else the collection's read access.\n\t */\n\tprovidersCollection?: { slug: string; scopeField: string; sourceAccess?: Access }\n\t/**\n\t * Fetch for adapters built from provider documents: every resolved address must be public unless\n\t * `providers.hosts.allowPrivateNetwork`.\n\t */\n\tproviderFetch?: FetchLike\n\t/**\n\t * Releases what the runtime itself holds once it is retired: the adapters built from provider\n\t * documents, then the connections they reached their vendors through.\n\t */\n\tclose?: () => Promise<void>\n\t/**\n\t * Records an event from server code, through whichever registered adapter accepts\n\t * server events. Rejects with an `AnalyticsTrackError` when none does.\n\t */\n\ttrack?: (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted from the adapter that\n\t * registered one. Absent runtimes fall back to the base's own ingest mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits, separate from `cache.timeoutMs` on purpose: that is a per-read deadline\n\t * for dashboard queries, this a public request path with different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** The plugin's `trustedProxyHops`, read wherever a request's client address is. */\n\ttrustedProxyHops?: number\n\t/** The plugin's `trustedPlatform`, read wherever a request's client address is. */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized: the other sites whose pages may POST to the public\n\t * capture routes. Absent runtimes admit no cross-site POST at all.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/** `capture.exclusion` while the link is on; absent while it is off. */\n\texclusion?: ResolvedExclusion\n\t/**\n\t * `access.view`, which also gates handing out the exclusion link the view shows. Absent\n\t * runtimes fall back to the read gate alone.\n\t */\n\tviewAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** True when the app configured `scope.resolve` (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/** `scope.label`: names the resolved scope in the view's caption. */\n\tscopeLabel?: ScopeLabelResolver\n\t/** `scope.list`: the scopes a named refresh may bump. */\n\tscopeList?: ScopeListResolver\n\t/** The read cache's collection, when the install keeps its cache there rather than in `cache.store`. */\n\tcacheCollectionSlug?: string\n\t/** `countryFlags`, for the server surfaces that draw a flag outside the view. */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\t/**\n\t * Ids of the config-time adapters shared by every scope; runtime provider adapters (from the\n\t * providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/**\n\t * `access.crossScope`, every gate filled at config time. A gate a runtime leaves out (a test\n\t * double, a half-booted install) admits the users of the admin collection.\n\t */\n\tcrossScope?: Partial<Record<ScopeDecision, CrossScopeAccess>>\n\t/**\n\t * `access.read`, asked through `readGate` by every read; absent runtimes admit the users of\n\t * the admin collection.\n\t */\n\treadAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** Each bound collection, with the field its documents carry their scope in. */\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/**\n\t * The per-scope refresh epoch the engine keys on, shared with the reads that build their\n\t * own keys. Absent runtimes key on the initial token throughout.\n\t */\n\tepoch?: EpochStore\n\t/**\n\t * Provider and goal configuration epoch every cache key carries beside the refresh epoch: a hash\n\t * of committed documents, or a token `refreshProviders()` bumps. Absent, one fixed value.\n\t */\n\tconfigEpoch?: (scope?: string | null) => Promise<string>\n\t/**\n\t * Told by the providers and goals collection hooks which scopes a save touched, so this\n\t * instance reads them again as soon as the save commits. Writes nothing.\n\t */\n\tconfigChanged?: (collection: 'providers' | 'goals', scopes: Iterable<string | null>) => void\n\t/** `refreshProviders()`: retires a scope's cached reads on every instance. */\n\trefreshProviders?: (scope: string | null) => Promise<void>\n\t/**\n\t * Whether a scope's own enabled provider documents grant an adapter, decided from their\n\t * committed rows alone: nothing is decrypted. Set on an install running the providers collection.\n\t */\n\tproviderGranted?: (scope: string | null, adapterId: string) => Promise<boolean>\n\t/** The instance's in-process memo, the only place a live count is ever kept. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Where reads are cached across instances, and what deletes the expired entries. */\n\tcache?: { store: CacheStore; sweeper: CacheSweeper }\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n\t/** The config adapters this runtime attached to its Payload instance; retiring it closes them. */\n\tadapters?: readonly AnalyticsAdapter[]\n}\n\n/**\n * What the plugin leaves under its key in `config.custom`, which never reaches the client: how\n * to build a runtime for one Payload instance, and the boot checks its `onInit` runs.\n */\nexport interface RuntimeFactory {\n\tcreate: (payload: Payload) => AnalyticsRuntime\n\tvalidate: (payload: Payload) => Promise<void>\n\t/** The options resolved at config time, which the admin view renders with. */\n\tresolved?: ResolvedOptions\n}\n\nconst isRuntimeFactory = (value: unknown): value is RuntimeFactory =>\n\tisRecord(value) && typeof value.create === 'function' && typeof value.validate === 'function'\n\n/** The factory a config carries, absent wherever the plugin is not installed or is disabled. */\nexport const runtimeFactoryOf = (\n\tconfig: { custom?: Record<string, unknown> } | undefined\n): RuntimeFactory | undefined => {\n\tconst factory = config?.custom?.[ANALYTICS_CONFIG_KEY]\n\treturn isRuntimeFactory(factory) ? factory : undefined\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the separate `.`\n * and `/rsc` bundles a consumer loads; `Symbol.for` resolves the same key in both.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\n/** Runtimes replaced on this instance whose adapters are still waiting out their grace period. */\nconst RETIRING_KEY = Symbol.for('@10x-media/analytics/retiring')\n\n/** How long a replaced runtime keeps serving the requests that already hold it. */\nexport const RUNTIME_RETIRE_GRACE_MS = 30_000\n\n/** A runtime and the exact config object it was built for, which is how a reload is noticed. */\ninterface RuntimeSlot {\n\tconfig: unknown\n\truntime: AnalyticsRuntime | undefined\n}\n\nconst isRuntimeSlot = (value: unknown): value is RuntimeSlot =>\n\tisRecord(value) && 'config' in value && 'runtime' in value\n\nconst slotOf = (payload: Payload): RuntimeSlot | undefined => {\n\tconst slot: unknown = Reflect.get(payload, RUNTIME_KEY)\n\treturn isRuntimeSlot(slot) ? slot : undefined\n}\n\ninterface Retirement {\n\t/** Closes the retired adapters now; later calls share the first one's promise. */\n\trun: () => Promise<void>\n}\n\nconst retiringOf = (payload: Payload): Set<Retirement> => {\n\tconst existing: unknown = Reflect.get(payload, RETIRING_KEY)\n\tif (existing instanceof Set) {\n\t\treturn existing\n\t}\n\tconst created = new Set<Retirement>()\n\tReflect.set(payload, RETIRING_KEY, created)\n\treturn created\n}\n\n/** Runs one close, warning rather than throwing so the closes beside it still run. */\nconst closeOrWarn = async (payload: Payload, what: string, close: () => unknown): Promise<void> => {\n\ttry {\n\t\tawait close()\n\t} catch (err) {\n\t\tpayload.logger?.warn(`analytics: closing ${what} failed: ${String(err)}`)\n\t}\n}\n\n/**\n * After the grace period, closes the retired runtime's resources and every adapter it attached that\n * its successor no longer uses: a shared adapter keeps its buffer and clients.\n */\nconst retire = (\n\tpayload: Payload,\n\tretired: AnalyticsRuntime | undefined,\n\tsuccessor: AnalyticsRuntime | undefined\n): void => {\n\tconst kept = new Set(successor?.adapters ?? [])\n\tconst closing = (retired?.adapters ?? []).filter((adapter) => !kept.has(adapter))\n\tconst closeRuntime = retired?.close\n\tif (closing.length === 0 && !closeRuntime) {\n\t\treturn\n\t}\n\tconst pending = retiringOf(payload)\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tlet done: Promise<void> | undefined\n\tconst entry: Retirement = {\n\t\trun: () => {\n\t\t\tdone ??= (async () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tpending.delete(entry)\n\t\t\t\tawait Promise.all([\n\t\t\t\t\tcloseOrWarn(payload, \"a replaced runtime's connections\", () => closeRuntime?.()),\n\t\t\t\t\t...closing.map((adapter) =>\n\t\t\t\t\t\tcloseOrWarn(payload, `the \"${adapter.id}\" adapter of a replaced runtime`, () =>\n\t\t\t\t\t\t\tadapter.close?.(payload)\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t})()\n\t\t\treturn done\n\t\t},\n\t}\n\tpending.add(entry)\n\ttimer = setTimeout(() => void entry.run(), RUNTIME_RETIRE_GRACE_MS)\n\ttimer.unref?.()\n}\n\n/** Closes the instance's runtime and every runtime it replaced, at once: the instance is going away. */\nconst closeRuntimes = async (payload: Payload): Promise<void> => {\n\tconst slot = slotOf(payload)\n\tif (slot?.runtime) {\n\t\tretire(payload, slot.runtime, undefined)\n\t}\n\tawait settleRetiredRuntimes(payload)\n}\n\n/**\n * An instance's runtime, built on first use and rebuilt when `payload.config` changes identity (HMR\n * `reload`); undefined without the plugin. Building one makes `payload.destroy()` close it.\n */\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\tif (slot && slot.config === payload.config) {\n\t\treturn slot.runtime\n\t}\n\tconst runtime = runtimeFactoryOf(payload.config)?.create(payload)\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n\tif (slot) {\n\t\tretire(payload, slot.runtime, runtime)\n\t}\n\tif (runtime) {\n\t\tonDestroy(payload, () => closeRuntimes(payload))\n\t}\n\treturn runtime\n}\n\n/** The runtime already built for the instance's current config; unlike `getRuntime`, never builds one. */\nexport const builtRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\treturn slot && slot.config === payload.config ? slot.runtime : undefined\n}\n\n/** Installs a hand-built runtime for the instance's current config, which is what tests need. */\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n}\n\n/** Closes every replaced runtime's adapters now rather than after the grace period. */\nexport const settleRetiredRuntimes = async (payload: Payload): Promise<void> => {\n\tawait Promise.all([...retiringOf(payload)].map((entry) => entry.run()))\n}\n\nconst scopes = requestMemo<string | null>('scopeResolutions')\nconst timezones = requestMemo<string>('timezoneResolutions')\nconst currencies = requestMemo<string | undefined>('currencyResolutions')\n\n/** A memo key per scope argument, where absent (the request's own scope) and null differ. */\nconst scopeKey = (scope: string | null | undefined): string =>\n\tscope === undefined ? 'own' : JSON.stringify(scope)\n\n/**\n * The scope a per-scope resolver answers for: no timezone, currency, goal or source belongs to the\n * cross-scope marker, so it reads as install-wide.\n */\nexport const resolvableScope = <S extends string | null | undefined>(scope: S): S | null =>\n\tscope === PLATFORM_SCOPE ? null : scope\n\n/**\n * The scope a signed-in reader's or editor's request selected: the `admin` call site, asked of\n * the host's resolver once per request and user however many reads ask.\n */\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => {\n\tconst resolve = runtime.resolveScope\n\tif (!resolve) {\n\t\treturn Promise.resolve(null)\n\t}\n\treturn scopes(req, {\n\t\towner: runtime,\n\t\tkey: 'admin',\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\treturn await resolve(req, 'admin')\n\t\t\t} catch (err) {\n\t\t\t\t// Said once here rather than by every read the failure reaches.\n\t\t\t\treq.payload?.logger?.warn?.(`analytics: scope resolution failed: ${String(err)}`)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * A visitor hit's scope, asked via {@link captureRequest} so no user, cookie or auth header reaches\n * the resolver: an editor's beacon files under the site, not their admin tenant.\n */\nexport const resolveCaptureScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> =>\n\truntime.resolveScope?.(captureRequest(req), 'capture') ?? Promise.resolve(null)\n\n/** The scope's reporting timezone, asked of the host's resolver once per request, scope and user. */\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => {\n\tconst resolve = runtime.resolveTimezone\n\treturn resolve\n\t\t? timezones(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(DEFAULT_TIMEZONE)\n}\n\n/** The scope's reporting currency, asked of the host's resolver once per request, scope and user. */\nexport const resolveCurrencyFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string | undefined> => {\n\tconst resolve = runtime.resolveCurrency\n\treturn resolve\n\t\t? currencies(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(undefined)\n}\n\n/**\n * Like {@link resolveTimezoneFor} but resolving the request's scope first, for calendar days read\n * before a read begins. UTC without the plugin or when resolution throws.\n */\nexport const requestTimezone = async (req: PayloadRequest): Promise<string> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveTimezoneFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n}\n\n/**\n * A request's reporting currency, resolving its scope first. Undefined without the plugin, without\n * a configured currency, or when resolution throws: revenue then renders as a plain number.\n */\nexport const requestCurrency = async (req: PayloadRequest): Promise<string | undefined> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.resolveCurrency) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveCurrencyFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** The scope's refresh epoch token, the initial one wherever the runtime carries no store. */\nexport const cacheEpochFor = (runtime: AnalyticsRuntime, scope?: string | null): Promise<string> =>\n\truntime.epoch?.get(scope) ?? Promise.resolve(INITIAL_EPOCH)\n\n/** Both epochs the scope's cache keys carry, for a read that builds its own key. */\nexport const cacheEpochsFor = (\n\truntime: AnalyticsRuntime,\n\tscope?: string | null\n): Promise<CacheKeyEpochs> =>\n\tepochsFor(\n\t\t{\n\t\t\t...(runtime.epoch ? { refresh: runtime.epoch } : {}),\n\t\t\t...(runtime.configEpoch ? { config: runtime.configEpoch } : {}),\n\t\t},\n\t\tscope\n\t)\n\n/** The scope's adapter registry; without a per-scope resolver, the config one and no grants. */\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<ScopeRegistry> =>\n\truntime.resolveRegistry?.(args) ??\n\tPromise.resolve({ registry: runtime.registry, grants: NO_GRANTS })\n\n/** The scope's goals: config goals merged with the goals collection, where the runtime can. */\nexport const resolveGoalsFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<Goal[]> => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? [])\n\n/**\n * {@link resolveGoalsFor}'s goals, each tagged with its origin. Falls back to the untagged\n * resolver, not the static config list, so the two never disagree.\n */\nexport const resolveGoalsDetailedFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<ResolvedGoal[]> => {\n\tif (runtime.resolveGoalsDetailed) {\n\t\treturn runtime.resolveGoalsDetailed(req, scope)\n\t}\n\tconst goals = runtime.resolveGoals\n\t\t? await runtime.resolveGoals(req, scope)\n\t\t: (runtime.goals ?? [])\n\treturn goals.map((goal) => ({ goal, source: 'config' as const }))\n}\n\n/**\n * Whether a read in `scope` spans every scope: the aggregate, or the install-wide read a scoped\n * install answers a platform reader who selected no tenant.\n */\nconst readsAcrossScopes = (\n\truntime: Pick<AnalyticsRuntime, 'scoped'>,\n\tscope: string | null | undefined\n): boolean => scope === PLATFORM_SCOPE || ((scope ?? null) === null && runtime.scoped === true)\n\n/**\n * Names a report in `scope` lists goal rows by. A cross-scope report draws on every scope the\n * reader may see, so a foreign goal reads by name; unnamed goals read as slugs.\n */\nexport const goalNamesFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string | null | undefined\n\t/** The scope's own goals, when the caller already resolved them. */\n\tresolved?: ResolvedGoal[]\n}): Promise<Array<{ slug: string; name: string }>> => {\n\tconst { runtime, req, scope, resolved } = args\n\tconst own = resolved ?? (await resolveGoalsDetailedFor(runtime, req, resolvableScope(scope)))\n\tif (!readsAcrossScopes(runtime, scope) || !runtime.listGoalsAcross) {\n\t\treturn own.map(({ goal }) => ({ slug: goal.slug, name: goal.name }))\n\t}\n\tconst across = await runtime.listGoalsAcross(req)\n\tconst names = new Map(own.map(({ goal }) => [goal.slug, goal.name]))\n\tfor (const { goal } of across) {\n\t\tif (!names.has(goal.slug)) {\n\t\t\tnames.set(goal.slug, goal.name)\n\t\t}\n\t}\n\treturn [...names].map(([slug, name]) => ({ slug, name }))\n}\n\n/** The three cross-scope decisions `access.crossScope` names. */\nexport type ScopeDecision = 'named' | 'aggregate' | 'unscopedSource'\n\n/**\n * The three cross-scope decisions for one request, each evaluated at most once per user however\n * many gates and reads consult it.\n */\nexport type ScopeGates = Record<ScopeDecision, () => Promise<boolean>>\n\n/**\n * The request's {@link ScopeGates}; a gate `access.crossScope` leaves unset admits the users of the\n * admin collection.\n */\nexport const scopeGates = (runtime: AnalyticsRuntime, req: PayloadRequest): ScopeGates => {\n\tconst gate = (decision: ScopeDecision) => (): Promise<boolean> =>\n\t\tdecideOnce(req, {\n\t\t\towner: runtime,\n\t\t\tkey: `crossScope:${decision}`,\n\t\t\tdecide: () => runtime.crossScope?.[decision]?.({ req }) ?? isAdminUser({ req }),\n\t\t})\n\treturn {\n\t\tnamed: gate('named'),\n\t\taggregate: gate('aggregate'),\n\t\tunscopedSource: gate('unscopedSource'),\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA6NA,MAAM,oBAAoB,UACzB,SAAS,KAAK,KAAK,OAAO,MAAM,WAAW,cAAc,OAAO,MAAM,aAAa;;AAGpF,MAAa,oBACZ,WACgC;CAChC,MAAM,UAAU,QAAQ,SAAS;CACjC,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC9C;;;;;AAMA,MAAM,cAAc,OAAO,IAAI,8BAA8B;;AAG7D,MAAM,eAAe,OAAO,IAAI,+BAA+B;;AAG/D,MAAa,0BAA0B;AAQvC,MAAM,iBAAiB,UACtB,SAAS,KAAK,KAAK,YAAY,SAAS,aAAa;AAEtD,MAAM,UAAU,YAA8C;CAC7D,MAAM,OAAgB,QAAQ,IAAI,SAAS,WAAW;CACtD,OAAO,cAAc,IAAI,IAAI,OAAO,KAAA;AACrC;AAOA,MAAM,cAAc,YAAsC;CACzD,MAAM,WAAoB,QAAQ,IAAI,SAAS,YAAY;CAC3D,IAAI,oBAAoB,KACvB,OAAO;CAER,M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CAAC;CAC/E,CAAC;CACF,OAAO;EACN,OAAO,KAAK,OAAO;EACnB,WAAW,KAAK,WAAW;EAC3B,gBAAgB,KAAK,gBAAgB;CACtC;AACD"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Access, Payload, PayloadRequest } from 'payload'\nimport { isAdminUser } from '../access/adminUser'\nimport { decideOnce } from '../access/decideOnce'\nimport type { ResolvedBinding } from '../binding/types'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CacheKeyEpochs } from '../core/cacheKey'\nimport { type AnalyticsAdapter, type AnalyticsResult, PLATFORM_SCOPE } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type {\n\tAnalyticsCountryFlags,\n\tCaptureGatePolicy,\n\tCaptureSlotOption,\n\tCrossScopeAccess,\n\tResolvedExclusion,\n\tResolvedOptions,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n} from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ResolveRegistryArgs,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { ServerEventInput, ServerTrackOptions } from '../core/serverEvent'\nimport type { DefaultSourceRule, ResolvedSources } from '../core/sourcePolicy'\nimport { isRecord } from '../core/values'\nimport type { GoalsResolver, ResolvedGoal } from '../goals/resolver'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { CacheSweeper } from '../surfacing/cacheSweep'\nimport type { Engine } from '../surfacing/engine'\nimport { type EpochStore, epochsFor, INITIAL_EPOCH } from '../surfacing/epoch'\nimport type { Memo } from '../surfacing/memo'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport type { ResolvedAutoCapture, TrackerSkip } from '../tracker/config'\nimport { onDestroy } from './destroy'\nimport { requestMemo } from './requestMemo'\nimport { ANALYTICS_CONFIG_KEY } from './routes'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/**\n\t * Never call directly: ask {@link resolveScopeFor} or {@link resolveCaptureScopeFor}, whose\n\t * capture path strips the visitor's identity first. Absent resolves null.\n\t */\n\tresolveScope?: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\t/**\n\t * `scope.member`, set exactly when the install is scoped. A runtime without one admits nobody\n\t * to a tenant scope they did not reach through `access.crossScope`.\n\t */\n\tmember?: ScopeMemberAccess\n\t/** The plugin's reportingTimezone as a resolver; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The plugin's `revenue.currency` as a resolver; absent runtimes and installs that set\n\t * none resolve undefined, and revenue then renders as a plain number.\n\t */\n\tresolveCurrency?: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/**\n\t * `sources`: each shared config adapter whose tenants read under a policy other than `staff`.\n\t * Absent runtimes admit tenants to no shared adapter beyond `unscopedSource`.\n\t */\n\tsourcePolicies?: ResolvedSources['policies']\n\t/** `defaultSource`: how a tenant scope picks its default source; absent keeps the registry's. */\n\tdefaultSource?: DefaultSourceRule\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * `capture.gate`: whether a slot's tracker waits for the host's consent manager, evaluated\n\t * per request-resolved adapter. Absent runtimes hold every slot.\n\t */\n\tcaptureGate?: CaptureGatePolicy\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** `capture.skip`, resolved; absent runtimes skip everything it can. */\n\tcaptureSkip?: TrackerSkip\n\t/** Config goals, and the fallback wherever the merged resolution is unavailable. */\n\tgoals?: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal?: boolean\n\t/**\n\t * Config goals merged with the goals collection for a request's scope. Absent runtimes\n\t * fall back to `goals`.\n\t */\n\tresolveGoals?: GoalsResolver['resolve']\n\t/** The same merge, each goal tagged with where it came from. */\n\tresolveGoalsDetailed?: GoalsResolver['resolveDetailed']\n\t/**\n\t * The goals a reader's picker lists: collection goals as the collection's read access lets\n\t * the request's user see them. Absent runtimes list what `resolveGoalsDetailed` answers.\n\t */\n\tlistGoals?: GoalsResolver['listReadable']\n\t/** The goals a report spanning every scope names its rows by; see `goalNamesFor`. */\n\tlistGoalsAcross?: GoalsResolver['listAcross']\n\t/** Slug of the goals collection when the install enabled it; the picker links to it. */\n\tgoalsCollectionSlug?: string\n\t/**\n\t * Providers collection when enabled; it makes a scoped install's sources per tenant.\n\t * `sourceAccess` picks which documents a tenant reads through, else the collection's read access.\n\t */\n\tprovidersCollection?: { slug: string; scopeField: string; sourceAccess?: Access }\n\t/**\n\t * Fetch for adapters built from provider documents: every resolved address must be public unless\n\t * `providers.hosts.allowPrivateNetwork`.\n\t */\n\tproviderFetch?: FetchLike\n\t/**\n\t * Releases what the runtime itself holds once it is retired: the adapters built from provider\n\t * documents, then the connections they reached their vendors through.\n\t */\n\tclose?: () => Promise<void>\n\t/**\n\t * Records an event from server code, through whichever registered adapter accepts\n\t * server events. Rejects with an `AnalyticsTrackError` when none does.\n\t */\n\ttrack?: (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted from the adapter that\n\t * registered one. Absent runtimes fall back to the base's own ingest mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits, separate from `cache.timeoutMs` on purpose: that is a per-read deadline\n\t * for dashboard queries, this a public request path with different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** The plugin's `trustedProxyHops`, read wherever a request's client address is. */\n\ttrustedProxyHops?: number\n\t/** The plugin's `trustedPlatform`, read wherever a request's client address is. */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized: the other sites whose pages may POST to the public\n\t * capture routes. Absent runtimes admit no cross-site POST at all.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/** `capture.exclusion` while the link is on; absent while it is off. */\n\texclusion?: ResolvedExclusion\n\t/**\n\t * `access.view`, which also gates handing out the exclusion link the view shows. Absent\n\t * runtimes fall back to the read gate alone.\n\t */\n\tviewAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** True when the app configured `scope.resolve` (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/** `scope.label`: names the resolved scope in the view's caption. */\n\tscopeLabel?: ScopeLabelResolver\n\t/** `scope.list`: the scopes a named refresh may bump. */\n\tscopeList?: ScopeListResolver\n\t/** The read cache's collection, when the install keeps its cache there rather than in `cache.store`. */\n\tcacheCollectionSlug?: string\n\t/** `countryFlags`, for the server surfaces that draw a flag outside the view. */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\t/**\n\t * Ids of the config-time adapters shared by every scope; runtime provider adapters (from the\n\t * providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/**\n\t * `access.crossScope`, every gate filled at config time. A gate a runtime leaves out (a test\n\t * double, a half-booted install) admits the users of the admin collection.\n\t */\n\tcrossScope?: Partial<Record<ScopeDecision, CrossScopeAccess>>\n\t/**\n\t * `access.read`, asked through `readGate` by every read; absent runtimes admit the users of\n\t * the admin collection.\n\t */\n\treadAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** Each bound collection, with the field its documents carry their scope in. */\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/**\n\t * The per-scope refresh epoch the engine keys on, shared with the reads that build their\n\t * own keys. Absent runtimes key on the initial token throughout.\n\t */\n\tepoch?: EpochStore\n\t/**\n\t * Provider and goal configuration epoch every cache key carries beside the refresh epoch: a hash\n\t * of committed documents, or a token `refreshProviders()` bumps. Absent, one fixed value.\n\t */\n\tconfigEpoch?: (scope?: string | null) => Promise<string>\n\t/**\n\t * Told by the providers and goals collection hooks which scopes a save touched, so this\n\t * instance reads them again as soon as the save commits. Writes nothing.\n\t */\n\tconfigChanged?: (collection: 'providers' | 'goals', scopes: Iterable<string | null>) => void\n\t/** `refreshProviders()`: retires a scope's cached reads on every instance. */\n\trefreshProviders?: (scope: string | null) => Promise<void>\n\t/**\n\t * Whether a scope's own enabled provider documents grant an adapter, decided from their\n\t * committed rows alone: nothing is decrypted. Set on an install running the providers collection.\n\t */\n\tproviderGranted?: (scope: string | null, adapterId: string) => Promise<boolean>\n\t/** The instance's in-process memo, the only place a live count is ever kept. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Where reads are cached across instances, and what deletes the expired entries. */\n\tcache?: { store: CacheStore; sweeper: CacheSweeper }\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n\t/** The config adapters this runtime attached to its Payload instance; retiring it closes them. */\n\tadapters?: readonly AnalyticsAdapter[]\n}\n\n/**\n * What the plugin leaves under its key in `config.custom`, which never reaches the client: how\n * to build a runtime for one Payload instance, and the boot checks its `onInit` runs.\n */\nexport interface RuntimeFactory {\n\tcreate: (payload: Payload) => AnalyticsRuntime\n\tvalidate: (payload: Payload) => Promise<void>\n\t/** The options resolved at config time, which the admin view renders with. */\n\tresolved?: ResolvedOptions\n}\n\nconst isRuntimeFactory = (value: unknown): value is RuntimeFactory =>\n\tisRecord(value) && typeof value.create === 'function' && typeof value.validate === 'function'\n\n/** The factory a config carries, absent wherever the plugin is not installed or is disabled. */\nexport const runtimeFactoryOf = (\n\tconfig: { custom?: Record<string, unknown> } | undefined\n): RuntimeFactory | undefined => {\n\tconst factory = config?.custom?.[ANALYTICS_CONFIG_KEY]\n\treturn isRuntimeFactory(factory) ? factory : undefined\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the separate `.`\n * and `/rsc` bundles a consumer loads; `Symbol.for` resolves the same key in both.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\n/** Runtimes replaced on this instance whose adapters are still waiting out their grace period. */\nconst RETIRING_KEY = Symbol.for('@10x-media/analytics/retiring')\n\n/** How long a replaced runtime keeps serving the requests that already hold it. */\nexport const RUNTIME_RETIRE_GRACE_MS = 30_000\n\n/** A runtime and the exact config object it was built for, which is how a reload is noticed. */\ninterface RuntimeSlot {\n\tconfig: unknown\n\truntime: AnalyticsRuntime | undefined\n}\n\nconst isRuntimeSlot = (value: unknown): value is RuntimeSlot =>\n\tisRecord(value) && 'config' in value && 'runtime' in value\n\nconst slotOf = (payload: Payload): RuntimeSlot | undefined => {\n\tconst slot: unknown = Reflect.get(payload, RUNTIME_KEY)\n\treturn isRuntimeSlot(slot) ? slot : undefined\n}\n\ninterface Retirement {\n\t/** Closes the retired adapters now; later calls share the first one's promise. */\n\trun: () => Promise<void>\n}\n\nconst retiringOf = (payload: Payload): Set<Retirement> => {\n\tconst existing: unknown = Reflect.get(payload, RETIRING_KEY)\n\tif (existing instanceof Set) {\n\t\treturn existing\n\t}\n\tconst created = new Set<Retirement>()\n\tReflect.set(payload, RETIRING_KEY, created)\n\treturn created\n}\n\n/** Runs one close, warning rather than throwing so the closes beside it still run. */\nconst closeOrWarn = async (payload: Payload, what: string, close: () => unknown): Promise<void> => {\n\ttry {\n\t\tawait close()\n\t} catch (err) {\n\t\tpayload.logger?.warn(`analytics: closing ${what} failed: ${String(err)}`)\n\t}\n}\n\n/**\n * After the grace period, closes the retired runtime's resources and every adapter it attached that\n * its successor no longer uses: a shared adapter keeps its buffer and clients.\n */\nconst retire = (\n\tpayload: Payload,\n\tretired: AnalyticsRuntime | undefined,\n\tsuccessor: AnalyticsRuntime | undefined\n): void => {\n\tconst kept = new Set(successor?.adapters ?? [])\n\tconst closing = (retired?.adapters ?? []).filter((adapter) => !kept.has(adapter))\n\tconst closeRuntime = retired?.close\n\tif (closing.length === 0 && !closeRuntime) {\n\t\treturn\n\t}\n\tconst pending = retiringOf(payload)\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tlet done: Promise<void> | undefined\n\tconst entry: Retirement = {\n\t\trun: () => {\n\t\t\tdone ??= (async () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tpending.delete(entry)\n\t\t\t\tawait Promise.all([\n\t\t\t\t\tcloseOrWarn(payload, \"a replaced runtime's connections\", () => closeRuntime?.()),\n\t\t\t\t\t...closing.map((adapter) =>\n\t\t\t\t\t\tcloseOrWarn(payload, `the \"${adapter.id}\" adapter of a replaced runtime`, () =>\n\t\t\t\t\t\t\tadapter.close?.(payload)\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t})()\n\t\t\treturn done\n\t\t},\n\t}\n\tpending.add(entry)\n\ttimer = setTimeout(() => void entry.run(), RUNTIME_RETIRE_GRACE_MS)\n\ttimer.unref?.()\n}\n\n/** Closes the instance's runtime and every runtime it replaced, at once: the instance is going away. */\nconst closeRuntimes = async (payload: Payload): Promise<void> => {\n\tconst slot = slotOf(payload)\n\tif (slot?.runtime) {\n\t\tretire(payload, slot.runtime, undefined)\n\t}\n\tawait settleRetiredRuntimes(payload)\n}\n\n/**\n * An instance's runtime, built on first use and rebuilt when `payload.config` changes identity (HMR\n * `reload`); undefined without the plugin. Building one makes `payload.destroy()` close it.\n */\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\tif (slot && slot.config === payload.config) {\n\t\treturn slot.runtime\n\t}\n\tconst runtime = runtimeFactoryOf(payload.config)?.create(payload)\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n\tif (slot) {\n\t\tretire(payload, slot.runtime, runtime)\n\t}\n\tif (runtime) {\n\t\tonDestroy(payload, () => closeRuntimes(payload))\n\t}\n\treturn runtime\n}\n\n/** The runtime already built for the instance's current config; unlike `getRuntime`, never builds one. */\nexport const builtRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\treturn slot && slot.config === payload.config ? slot.runtime : undefined\n}\n\n/** Installs a hand-built runtime for the instance's current config, which is what tests need. */\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n}\n\n/** Closes every replaced runtime's adapters now rather than after the grace period. */\nexport const settleRetiredRuntimes = async (payload: Payload): Promise<void> => {\n\tawait Promise.all([...retiringOf(payload)].map((entry) => entry.run()))\n}\n\nconst scopes = requestMemo<string | null>('scopeResolutions')\nconst timezones = requestMemo<string>('timezoneResolutions')\nconst currencies = requestMemo<string | undefined>('currencyResolutions')\n\n/** A memo key per scope argument, where absent (the request's own scope) and null differ. */\nconst scopeKey = (scope: string | null | undefined): string =>\n\tscope === undefined ? 'own' : JSON.stringify(scope)\n\n/**\n * The scope a per-scope resolver answers for: no timezone, currency, goal or source belongs to the\n * cross-scope marker, so it reads as install-wide.\n */\nexport const resolvableScope = <S extends string | null | undefined>(scope: S): S | null =>\n\tscope === PLATFORM_SCOPE ? null : scope\n\n/**\n * The scope a signed-in reader's or editor's request selected: the `admin` call site, asked of\n * the host's resolver once per request and user however many reads ask.\n */\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => {\n\tconst resolve = runtime.resolveScope\n\tif (!resolve) {\n\t\treturn Promise.resolve(null)\n\t}\n\treturn scopes(req, {\n\t\towner: runtime,\n\t\tkey: 'admin',\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\treturn await resolve(req, 'admin')\n\t\t\t} catch (err) {\n\t\t\t\t// Said once here rather than by every read the failure reaches.\n\t\t\t\treq.payload?.logger?.warn?.(`analytics: scope resolution failed: ${String(err)}`)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * A visitor hit's scope, asked via {@link captureRequest} so no user, cookie or auth header reaches\n * the resolver: an editor's beacon files under the site, not their admin tenant.\n */\nexport const resolveCaptureScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> =>\n\truntime.resolveScope?.(captureRequest(req), 'capture') ?? Promise.resolve(null)\n\n/** The scope's reporting timezone, asked of the host's resolver once per request, scope and user. */\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => {\n\tconst resolve = runtime.resolveTimezone\n\treturn resolve\n\t\t? timezones(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(DEFAULT_TIMEZONE)\n}\n\n/** The scope's reporting currency, asked of the host's resolver once per request, scope and user. */\nexport const resolveCurrencyFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string | undefined> => {\n\tconst resolve = runtime.resolveCurrency\n\treturn resolve\n\t\t? currencies(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(undefined)\n}\n\n/**\n * Like {@link resolveTimezoneFor} but resolving the request's scope first, for calendar days read\n * before a read begins. UTC without the plugin or when resolution throws.\n */\nexport const requestTimezone = async (req: PayloadRequest): Promise<string> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveTimezoneFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n}\n\n/**\n * A request's reporting currency, resolving its scope first. Undefined without the plugin, without\n * a configured currency, or when resolution throws: revenue then renders as a plain number.\n */\nexport const requestCurrency = async (req: PayloadRequest): Promise<string | undefined> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.resolveCurrency) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveCurrencyFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** The scope's refresh epoch token, the initial one wherever the runtime carries no store. */\nexport const cacheEpochFor = (runtime: AnalyticsRuntime, scope?: string | null): Promise<string> =>\n\truntime.epoch?.get(scope) ?? Promise.resolve(INITIAL_EPOCH)\n\n/** Both epochs the scope's cache keys carry, for a read that builds its own key. */\nexport const cacheEpochsFor = (\n\truntime: AnalyticsRuntime,\n\tscope?: string | null\n): Promise<CacheKeyEpochs> =>\n\tepochsFor(\n\t\t{\n\t\t\t...(runtime.epoch ? { refresh: runtime.epoch } : {}),\n\t\t\t...(runtime.configEpoch ? { config: runtime.configEpoch } : {}),\n\t\t},\n\t\tscope\n\t)\n\n/** The scope's adapter registry; without a per-scope resolver, the config one and no grants. */\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<ScopeRegistry> =>\n\truntime.resolveRegistry?.(args) ??\n\tPromise.resolve({ registry: runtime.registry, grants: NO_GRANTS })\n\n/** The scope's goals: config goals merged with the goals collection, where the runtime can. */\nexport const resolveGoalsFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<Goal[]> => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? [])\n\n/**\n * {@link resolveGoalsFor}'s goals, each tagged with its origin. Falls back to the untagged\n * resolver, not the static config list, so the two never disagree.\n */\nexport const resolveGoalsDetailedFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<ResolvedGoal[]> => {\n\tif (runtime.resolveGoalsDetailed) {\n\t\treturn runtime.resolveGoalsDetailed(req, scope)\n\t}\n\tconst goals = runtime.resolveGoals\n\t\t? await runtime.resolveGoals(req, scope)\n\t\t: (runtime.goals ?? [])\n\treturn goals.map((goal) => ({ goal, source: 'config' as const }))\n}\n\n/**\n * Whether a read in `scope` spans every scope: the aggregate, or the install-wide read a scoped\n * install answers a platform reader who selected no tenant.\n */\nconst readsAcrossScopes = (\n\truntime: Pick<AnalyticsRuntime, 'scoped'>,\n\tscope: string | null | undefined\n): boolean => scope === PLATFORM_SCOPE || ((scope ?? null) === null && runtime.scoped === true)\n\n/**\n * Names a report in `scope` lists goal rows by. A cross-scope report draws on every scope the\n * reader may see, so a foreign goal reads by name; unnamed goals read as slugs.\n */\nexport const goalNamesFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string | null | undefined\n\t/** The scope's own goals, when the caller already resolved them. */\n\tresolved?: ResolvedGoal[]\n}): Promise<Array<{ slug: string; name: string }>> => {\n\tconst { runtime, req, scope, resolved } = args\n\tconst own = resolved ?? (await resolveGoalsDetailedFor(runtime, req, resolvableScope(scope)))\n\tif (!readsAcrossScopes(runtime, scope) || !runtime.listGoalsAcross) {\n\t\treturn own.map(({ goal }) => ({ slug: goal.slug, name: goal.name }))\n\t}\n\tconst across = await runtime.listGoalsAcross(req)\n\tconst names = new Map(own.map(({ goal }) => [goal.slug, goal.name]))\n\tfor (const { goal } of across) {\n\t\tif (!names.has(goal.slug)) {\n\t\t\tnames.set(goal.slug, goal.name)\n\t\t}\n\t}\n\treturn [...names].map(([slug, name]) => ({ slug, name }))\n}\n\n/** The three cross-scope decisions `access.crossScope` names. */\nexport type ScopeDecision = 'named' | 'aggregate' | 'unscopedSource'\n\n/** What one gate is asked about: the scope (`'*'` or null for every scope) and the adapter. */\nexport interface GateContext {\n\tscope?: string | null\n\tadapterId?: string\n}\n\n/**\n * The three cross-scope decisions for one request, each evaluated at most once per user, scope and\n * adapter however many gates and reads consult it.\n */\nexport type ScopeGates = Record<ScopeDecision, (ctx?: GateContext) => Promise<boolean>>\n\n/**\n * The request's {@link ScopeGates}; a gate `access.crossScope` leaves unset admits the users of the\n * admin collection.\n */\nexport const scopeGates = (runtime: AnalyticsRuntime, req: PayloadRequest): ScopeGates => {\n\tconst gate =\n\t\t(decision: ScopeDecision) =>\n\t\t(ctx: GateContext = {}): Promise<boolean> => {\n\t\t\tconst { scope, adapterId } = ctx\n\t\t\tconst args = {\n\t\t\t\treq,\n\t\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\t\t...(adapterId === undefined ? {} : { adapterId }),\n\t\t\t}\n\t\t\treturn decideOnce(req, {\n\t\t\t\towner: runtime,\n\t\t\t\tkey: `crossScope:${decision}:${JSON.stringify(scope)}:${adapterId ?? ''}`,\n\t\t\t\tdecide: () => runtime.crossScope?.[decision]?.(args) ?? isAdminUser({ req }),\n\t\t\t})\n\t\t}\n\treturn {\n\t\tnamed: gate('named'),\n\t\taggregate: gate('aggregate'),\n\t\tunscopedSource: gate('unscopedSource'),\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAqOA,MAAM,oBAAoB,UACzB,SAAS,KAAK,KAAK,OAAO,MAAM,WAAW,cAAc,OAAO,MAAM,aAAa;;AAGpF,MAAa,oBACZ,WACgC;CAChC,MAAM,UAAU,QAAQ,SAAS;CACjC,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC9C;;;;;AAMA,MAAM,cAAc,OAAO,IAAI,8BAA8B;;AAG7D,MAAM,eAAe,OAAO,IAAI,+BAA+B;;AAG/D,MAAa,0BAA0B;AAQvC,MAAM,iBAAiB,UACtB,SAAS,KAAK,KAAK,YAAY,SAAS,aAAa;AAEtD,MAAM,UAAU,YAA8C;CAC7D,MAAM,OAAgB,QAAQ,IAAI,SAAS,WAAW;CACtD,OAAO,cAAc,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C;CACzF,MAAM,QACJ,cACA,MAAmB,CAAC,MAAwB;EAC5C,MAAM,EAAE,OAAO,cAAc;EAC7B,MAAM,OAAO;GACZ;GACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;GACvC,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAChD;EACA,OAAO,WAAW,KAAK;GACtB,OAAO;GACP,KAAK,cAAc,SAAS,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG,aAAa;GACrE,cAAc,QAAQ,aAAa,YAAY,IAAI,KAAK,YAAY,EAAE,IAAI,CAAC;EAC5E,CAAC;CACF;CACD,OAAO;EACN,OAAO,KAAK,OAAO;EACnB,WAAW,KAAK,WAAW;EAC3B,gBAAgB,KAAK,gBAAgB;CACtC;AACD"}
|
|
@@ -20,6 +20,12 @@ const makeSourcesHandler = () => async (req) => {
|
|
|
20
20
|
return errorResponse(500, analyticsError("internal", "analytics: sources listing failed"));
|
|
21
21
|
}
|
|
22
22
|
};
|
|
23
|
+
/** The listing on the wire: what the client renders, never the adapters behind it. */
|
|
24
|
+
const listingBody = ({ defaultId, sources, notice }) => ({
|
|
25
|
+
defaultId,
|
|
26
|
+
sources,
|
|
27
|
+
...notice ? { notice } : {}
|
|
28
|
+
});
|
|
23
29
|
const listSources = async (req, runtime) => {
|
|
24
30
|
if (runtime && !await readGate(runtime, req)) return readDeniedResponse();
|
|
25
31
|
const params = queryParams(req);
|
|
@@ -45,16 +51,9 @@ const listSources = async (req, runtime) => {
|
|
|
45
51
|
gates,
|
|
46
52
|
...scope.scope === null ? {} : { scope: scope.gated }
|
|
47
53
|
});
|
|
48
|
-
return Response.json({
|
|
49
|
-
defaultId: listing.defaultId,
|
|
50
|
-
sources: listing.sources
|
|
51
|
-
}, { headers: NO_STORE });
|
|
54
|
+
return Response.json(listingBody(listing), { headers: NO_STORE });
|
|
52
55
|
}
|
|
53
|
-
|
|
54
|
-
return Response.json({
|
|
55
|
-
defaultId,
|
|
56
|
-
sources
|
|
57
|
-
}, { headers: NO_STORE });
|
|
56
|
+
return Response.json(listingBody(await resolveSourcesForRequest(req)), { headers: NO_STORE });
|
|
58
57
|
};
|
|
59
58
|
//#endregion
|
|
60
59
|
export { makeSourcesHandler };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { resolveBoundDocument, unloadedDocumentResponse } from './boundDocument'\nimport { resolveDocumentScope } from './documentScopes'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { type AnalyticsRuntime, getRuntime, scopeGates } from './runtime'\n\n/**\n * Authenticated GET listing adapters the requesting scope sees, with no scope parameter so a tenant\n * never enumerates another's. `collection` and `id` list one readable document's scope instead.\n */\nexport const makeSourcesHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\ttry {\n\t\treturn await listSources(req, runtime)\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: sources listing failed: ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: sources listing failed'))\n\t}\n}\n\nconst listSources = async (\n\treq: PayloadRequest,\n\truntime: AnalyticsRuntime | undefined\n): Promise<Response> => {\n\t// No runtime means the plugin served nothing to gate: the listing below is empty anyway.\n\tif (runtime && !(await readGate(runtime, req))) {\n\t\treturn readDeniedResponse()\n\t}\n\tconst params = queryParams(req)\n\tconst collection = params.get('collection') ?? ''\n\tconst id = params.get('id') ?? ''\n\tif (runtime && collection && id) {\n\t\tconst bound = await resolveBoundDocument({ req, collection, id })\n\t\tif (!bound.ok) {\n\t\t\treturn unloadedDocumentResponse(bound.status)\n\t\t}\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst scope = await resolveDocumentScope({ runtime, req, collection, data: bound.data, gates })\n\t\tif (!scope.ok) {\n\t\t\treturn untrustedScopeResponse()\n\t\t}\n\t\tconst listing = await resolveSourcesForRequest(req, {\n\t\t\tgates,\n\t\t\t...(scope.scope === null ? {} : { scope: scope.gated }),\n\t\t})\n\t\treturn Response.json(
|
|
1
|
+
{"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { resolveBoundDocument, unloadedDocumentResponse } from './boundDocument'\nimport { resolveDocumentScope } from './documentScopes'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { type AnalyticsRuntime, getRuntime, scopeGates } from './runtime'\n\n/**\n * Authenticated GET listing adapters the requesting scope sees, with no scope parameter so a tenant\n * never enumerates another's. `collection` and `id` list one readable document's scope instead.\n */\nexport const makeSourcesHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\ttry {\n\t\treturn await listSources(req, runtime)\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: sources listing failed: ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: sources listing failed'))\n\t}\n}\n\n/** The listing on the wire: what the client renders, never the adapters behind it. */\nconst listingBody = ({\n\tdefaultId,\n\tsources,\n\tnotice,\n}: Awaited<ReturnType<typeof resolveSourcesForRequest>>) => ({\n\tdefaultId,\n\tsources,\n\t...(notice ? { notice } : {}),\n})\n\nconst listSources = async (\n\treq: PayloadRequest,\n\truntime: AnalyticsRuntime | undefined\n): Promise<Response> => {\n\t// No runtime means the plugin served nothing to gate: the listing below is empty anyway.\n\tif (runtime && !(await readGate(runtime, req))) {\n\t\treturn readDeniedResponse()\n\t}\n\tconst params = queryParams(req)\n\tconst collection = params.get('collection') ?? ''\n\tconst id = params.get('id') ?? ''\n\tif (runtime && collection && id) {\n\t\tconst bound = await resolveBoundDocument({ req, collection, id })\n\t\tif (!bound.ok) {\n\t\t\treturn unloadedDocumentResponse(bound.status)\n\t\t}\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst scope = await resolveDocumentScope({ runtime, req, collection, data: bound.data, gates })\n\t\tif (!scope.ok) {\n\t\t\treturn untrustedScopeResponse()\n\t\t}\n\t\tconst listing = await resolveSourcesForRequest(req, {\n\t\t\tgates,\n\t\t\t...(scope.scope === null ? {} : { scope: scope.gated }),\n\t\t})\n\t\treturn Response.json(listingBody(listing), { headers: NO_STORE })\n\t}\n\treturn Response.json(listingBody(await resolveSourcesForRequest(req)), { headers: NO_STORE })\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,2BAA2C,OAAO,QAAQ;CACtE,IAAI,CAAC,IAAI,MACR,OAAO,qBAAqB;CAE7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI;EACH,OAAO,MAAM,YAAY,KAAK,OAAO;CACtC,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,MAAM,sCAAsC,OAAO,GAAG,GAAG;EAC7E,OAAO,cAAc,KAAK,eAAe,YAAY,mCAAmC,CAAC;CAC1F;AACD;;AAGA,MAAM,eAAe,EACpB,WACA,SACA,cAC4D;CAC5D;CACA;CACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAC5B;AAEA,MAAM,cAAc,OACnB,KACA,YACuB;CAEvB,IAAI,WAAW,CAAE,MAAM,SAAS,SAAS,GAAG,GAC3C,OAAO,mBAAmB;CAE3B,MAAM,SAAS,YAAY,GAAG;CAC9B,MAAM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