@10x-media/analytics 0.1.0-beta.3 → 0.1.0-beta.5
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 +18 -0
- package/README.md +2 -0
- package/dist/core/capabilities.d.ts +13 -2
- package/dist/core/capabilities.js +11 -1
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/options.d.ts +14 -2
- package/dist/core/options.js +9 -3
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +7 -6
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/exports/client.d.ts +5 -1
- package/dist/exports/client.js +4 -1
- package/dist/exports/rsc.d.ts +1 -1
- package/dist/exports/types.d.ts +2 -1
- package/dist/fields/config/MetricSelectField.d.ts +23 -0
- package/dist/fields/config/MetricSelectField.js +51 -0
- package/dist/fields/config/MetricSelectField.js.map +1 -0
- package/dist/fields/config/SourceSelectField.d.ts +14 -0
- package/dist/fields/config/SourceSelectField.js +46 -0
- package/dist/fields/config/SourceSelectField.js.map +1 -0
- package/dist/fields/config/fetchSources.d.ts +12 -0
- package/dist/fields/config/fetchSources.js +29 -0
- package/dist/fields/config/fetchSources.js.map +1 -0
- package/dist/fields/config/narrow.js +30 -0
- package/dist/fields/config/narrow.js.map +1 -0
- package/dist/fields/config/sourcesState.js +11 -0
- package/dist/fields/config/sourcesState.js.map +1 -0
- package/dist/fields/config/toSelectOption.js +27 -0
- package/dist/fields/config/toSelectOption.js.map +1 -0
- package/dist/fields/config/useAnalyticsSources.d.ts +19 -0
- package/dist/fields/config/useAnalyticsSources.js +59 -0
- package/dist/fields/config/useAnalyticsSources.js.map +1 -0
- package/dist/index.js +51 -16
- package/dist/index.js.map +1 -1
- package/dist/plugin/paths.js +3 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/peerImportError.js +16 -0
- package/dist/plugin/peerImportError.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +2 -2
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +53 -0
- package/dist/plugin/sourcesEndpoint.js.map +1 -0
- package/dist/providers/access.js +44 -0
- package/dist/providers/access.js.map +1 -0
- package/dist/providers/collection.js +46 -31
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +21 -7
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/resolver.js +49 -14
- package/dist/providers/resolver.js.map +1 -1
- package/dist/providers/secrets.js +26 -21
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/stampScope.js +35 -0
- package/dist/providers/stampScope.js.map +1 -0
- package/dist/translations/de.js +1 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +1 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/keys.d.ts +1 -1
- package/dist/translations/keys.js +1 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +2 -2
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/realtimePoll.js +4 -1
- package/dist/widgets/realtimePoll.js.map +1 -1
- package/dist/widgets/registerWidgets.js +14 -4
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +9 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 0.1.0-beta.5
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Scope-aware widget pickers. A new authenticated `GET /api/analytics/sources` endpoint lists the adapters visible to the requesting scope (config adapters plus the scope's runtime providers) with their capabilities, and the widget `dataSource` and `metric` selects now render through client components that consume it: a tenant's own providers finally appear in pickers, labeled by the provider document's name (a generated label stands in when unset), and the metric list narrows to what the selected source can actually serve. Without JavaScript or when the endpoint is unreachable the pickers fall back to the config-time option lists, and stored values the endpoint no longer lists keep the previous behavior of degrading at read time.
|
|
8
|
+
|
|
9
|
+
The sources endpoint response now carries a top-level `defaultId` and a `kind: 'config' | 'runtime'` per source, and serialized capabilities are a deliberate allowlist (`metrics`, `dimensions`, `realtime`, `realtimeWindowMinutes`, `perPageQuery`, `comparison`, `minGranularity`, `maxLookbackDays`); adapter internals such as rate limits and TTL recommendations are no longer on the wire. New client reuse surface: `useAnalyticsSources` and the `WireSource` type from `@10x-media/analytics/client`, `SerializedCapabilities` from `/types`, and a `sourceFieldPath` prop on `MetricSelectField` for custom widgets. The widget data source default now follows `defaultAdapter`, and the realtime poller builds its URL from the configured API route instead of a hardcoded `/api`.
|
|
10
|
+
|
|
11
|
+
- **Breaking:** fail-closed defaults for scoped installs. With a `scopeResolver` configured, `access.platformRead` now defaults to deny instead of any authenticated user; configure it (for example a role check) so platform admins can read cross-scope and manage every tenant's provider documents. Scoped reads through a shared config adapter that cannot filter by scope are now gated behind `platformRead` even when the adapter is not designated as `platformAdapter`; a tenant's own runtime providers are never gated. A `scopeResolver` returning an empty string is now treated as the install-wide scope (fail closed) everywhere, matching ingest and registry semantics. `providers.collection.scopeField` must be a top-level field name; a dotted path now throws at config build. The provider collection's admin duplicate action is disabled (a duplicate could never carry the write-only credentials). Unscoped installs are unchanged.
|
|
12
|
+
|
|
13
|
+
## 0.1.0-beta.4
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- **Breaking:** runtime provider adapters now carry per-document instance ids (`posthog:<docId>`) instead of the plain provider id, so one scope can run several projects of the same provider type. The replace-by-id override rule is gone: runtime adapters append to the scope registry alongside config adapters (config adapters win id collisions), and a tenant preferring their own project selects it as the widget data source. Stored widget `dataSource` values and sync-tier `source` rows that referenced a runtime provider by its old plain id no longer resolve; reselect the source in affected widgets and expect new `source` values in `analytics-daily`. A sync tier filtered to a runtime provider's old plain id via sync.adapters no longer matches it; instance ids are per-document, so filter on config adapter ids or drop the filter. The adapter label shown in pickers is the provider document's `name`.
|
|
18
|
+
|
|
19
|
+
- **Breaking:** tenant-safe provider store. The `analytics-providers` collection now has scope-aware default access (a tenant only sees and manages their own provider documents; unscoped installs are unchanged), stamps the document scope server-side, requires a `name`, and stores credentials encrypted at rest via `@10x-media/fields` (write-only: secrets never leave the server; a short hint identifies the stored key). `@10x-media/fields` is a new optional peer dependency, required when `providers.collection` is enabled. The secret masking flow (`__redacted__` round-trip) is gone. Existing plaintext credentials keep working and seal on next save; bulk-encrypt with `encryptExistingData` from `@10x-media/fields/encrypted`. The plugin factory is also now async, breaking only for programmatic callers that invoke the plugin function directly outside `buildConfig` (which already awaits plugins).
|
|
20
|
+
|
|
3
21
|
## 0.1.0-beta.3
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
1
3
|
# @10x-media/analytics
|
|
2
4
|
|
|
3
5
|
Adapter-based analytics for Payload v3. One adapter contract covers a self-hosted native engine and the major providers (GA4, Plausible, Umami, PostHog), surfaced through dashboard widgets and per-document stat fields, with cached reads, an opt-in sync tier, and capability gating so unsupported surfaces never appear.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DimensionKey, MetricKey } from "./contract.js";
|
|
1
|
+
import { DimensionKey, Granularity, MetricKey } from "./contract.js";
|
|
2
2
|
|
|
3
3
|
//#region src/core/capabilities.d.ts
|
|
4
4
|
interface CapabilityRequirement {
|
|
@@ -7,6 +7,17 @@ interface CapabilityRequirement {
|
|
|
7
7
|
realtime?: boolean;
|
|
8
8
|
perPageQuery?: boolean;
|
|
9
9
|
}
|
|
10
|
+
/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */
|
|
11
|
+
type SerializedCapabilities = {
|
|
12
|
+
metrics: MetricKey[];
|
|
13
|
+
dimensions: DimensionKey[];
|
|
14
|
+
realtime: boolean;
|
|
15
|
+
realtimeWindowMinutes?: number;
|
|
16
|
+
perPageQuery: boolean;
|
|
17
|
+
comparison: boolean;
|
|
18
|
+
minGranularity: Granularity;
|
|
19
|
+
maxLookbackDays: number | null;
|
|
20
|
+
};
|
|
10
21
|
//#endregion
|
|
11
|
-
export { CapabilityRequirement };
|
|
22
|
+
export { CapabilityRequirement, SerializedCapabilities };
|
|
12
23
|
//# sourceMappingURL=capabilities.d.ts.map
|
|
@@ -6,7 +6,17 @@ function satisfiesCapabilities(caps, req) {
|
|
|
6
6
|
if (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false;
|
|
7
7
|
return true;
|
|
8
8
|
}
|
|
9
|
+
const serializeCapabilities = (caps) => ({
|
|
10
|
+
metrics: [...caps.metrics],
|
|
11
|
+
dimensions: [...caps.dimensions],
|
|
12
|
+
realtime: caps.realtime,
|
|
13
|
+
...caps.realtimeWindowMinutes !== void 0 ? { realtimeWindowMinutes: caps.realtimeWindowMinutes } : {},
|
|
14
|
+
perPageQuery: caps.perPageQuery,
|
|
15
|
+
comparison: caps.comparison,
|
|
16
|
+
minGranularity: caps.minGranularity,
|
|
17
|
+
maxLookbackDays: caps.maxLookbackDays
|
|
18
|
+
});
|
|
9
19
|
//#endregion
|
|
10
|
-
export { satisfiesCapabilities };
|
|
20
|
+
export { satisfiesCapabilities, serializeCapabilities };
|
|
11
21
|
|
|
12
22
|
//# sourceMappingURL=capabilities.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n"],"mappings":";AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, Granularity, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: caps.comparison,\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR;AAcA,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,KAAK;CACjB,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
|
package/dist/core/options.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { TranslationsOption } from "../translations/index.js";
|
|
|
3
3
|
import { AnalyticsBinding } from "../binding/types.js";
|
|
4
4
|
import { CustomWidgetDef } from "../widgets/customWidget.js";
|
|
5
5
|
import { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from "payload";
|
|
6
|
+
import { KeysConfig } from "@10x-media/fields/encrypted";
|
|
6
7
|
|
|
7
8
|
//#region src/core/options.d.ts
|
|
8
9
|
/**
|
|
@@ -44,6 +45,15 @@ type ProvidersCollectionOptions = {
|
|
|
44
45
|
scopeField?: string;
|
|
45
46
|
overrides?: (collection: CollectionConfig) => CollectionConfig;
|
|
46
47
|
access?: Partial<CollectionConfig['access']>;
|
|
48
|
+
/**
|
|
49
|
+
* Dedicated key ring for the stored provider credentials. Unset, the
|
|
50
|
+
* fields plugin's global `encrypted.keys` applies, and with neither the
|
|
51
|
+
* ring derives from the Payload secret. Configure a dedicated key for
|
|
52
|
+
* anything beyond a dev install.
|
|
53
|
+
*/
|
|
54
|
+
encryption?: {
|
|
55
|
+
keys?: KeysConfig;
|
|
56
|
+
};
|
|
47
57
|
};
|
|
48
58
|
type ProvidersOptions = {
|
|
49
59
|
/** Opt-in admin collection storing runtime provider configurations. */collection?: boolean | ProvidersCollectionOptions;
|
|
@@ -56,8 +66,10 @@ type PlatformReadAccess = (args: {
|
|
|
56
66
|
type AnalyticsAccessOptions = {
|
|
57
67
|
/**
|
|
58
68
|
* Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through
|
|
59
|
-
* a
|
|
60
|
-
*
|
|
69
|
+
* a shared config adapter that cannot filter by scope. Scoped installs
|
|
70
|
+
* (`scopeResolver` configured) default to deny; configure it, for example a role
|
|
71
|
+
* check, so platform admins can read cross-scope and manage every tenant's
|
|
72
|
+
* providers. Unscoped installs default to any authenticated admin-panel user.
|
|
61
73
|
*/
|
|
62
74
|
platformRead?: PlatformReadAccess;
|
|
63
75
|
};
|
package/dist/core/options.js
CHANGED
|
@@ -58,7 +58,8 @@ function resolveOptions(options) {
|
|
|
58
58
|
slug: collectionOpt.slug ?? "analytics-providers",
|
|
59
59
|
scopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,
|
|
60
60
|
overrides: collectionOpt.overrides,
|
|
61
|
-
access: collectionOpt.access
|
|
61
|
+
access: collectionOpt.access,
|
|
62
|
+
encryption: collectionOpt.encryption
|
|
62
63
|
} : {
|
|
63
64
|
enabled: false,
|
|
64
65
|
slug: PROVIDERS_SLUG,
|
|
@@ -66,6 +67,10 @@ function resolveOptions(options) {
|
|
|
66
67
|
},
|
|
67
68
|
resolve: options.providers?.resolve
|
|
68
69
|
};
|
|
70
|
+
if (providers.collection.enabled) {
|
|
71
|
+
if (providers.collection.scopeField.trim() === "") throw new Error("analytics: providers.collection.scopeField must be a non-empty field name");
|
|
72
|
+
if (providers.collection.scopeField.includes(".")) throw new Error("analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key");
|
|
73
|
+
}
|
|
69
74
|
const syncOpt = options.sync;
|
|
70
75
|
const sync = syncOpt === true ? {
|
|
71
76
|
enabled: true,
|
|
@@ -87,14 +92,15 @@ function resolveOptions(options) {
|
|
|
87
92
|
lookbackDays: DEFAULT_SYNC_LOOKBACK,
|
|
88
93
|
hidden: true
|
|
89
94
|
};
|
|
95
|
+
const scoped = options.scopeResolver !== void 0;
|
|
90
96
|
return {
|
|
91
97
|
adapters: options.adapters,
|
|
92
98
|
defaultAdapter: options.defaultAdapter,
|
|
93
99
|
scopeResolver: options.scopeResolver ?? (() => null),
|
|
94
|
-
scoped
|
|
100
|
+
scoped,
|
|
95
101
|
reportingTimezone: options.reportingTimezone,
|
|
96
102
|
platformAdapter: options.platformAdapter,
|
|
97
|
-
access: { platformRead: options.access?.platformRead ?? (({ req }) => Boolean(req.user)) },
|
|
103
|
+
access: { platformRead: options.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)) },
|
|
98
104
|
providers,
|
|
99
105
|
bindings: resolveBindings(options.collections),
|
|
100
106
|
cache: {
|
package/dist/core/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a platform adapter that cannot filter by scope. Defaults to any authenticated\n\t * admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped: options.scopeResolver !== undefined,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: { platformRead: options.access?.platformRead ?? (({ req }) => Boolean(req.user)) },\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t},\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":"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"}
|
package/dist/core/scopedRead.js
CHANGED
|
@@ -5,11 +5,12 @@ import "./contract.js";
|
|
|
5
5
|
* Resolve one read's scope and adapter: explicit scope wins over the request's
|
|
6
6
|
* resolved scope, the registry is resolved per scope, then the adapter is picked
|
|
7
7
|
* by id (or the registry default). Cross-scope reads fail closed behind
|
|
8
|
-
* `platformRead`: an explicit `'*'` scope always, and
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* `platformRead`: an explicit `'*'` scope always, and any scoped read through a
|
|
9
|
+
* shared config adapter that cannot narrow the query to one scope, whether or
|
|
10
|
+
* not it is the designated platform adapter. A tenant's own runtime adapters
|
|
11
|
+
* are never gated. Any resolution failure (unknown adapter id, a throwing
|
|
12
|
+
* scopeResolver or provider lookup) degrades to `{ ok: false }` so read paths
|
|
13
|
+
* render their unavailable state instead of throwing.
|
|
13
14
|
*/
|
|
14
15
|
const resolveReadContext = async (args) => {
|
|
15
16
|
const { runtime, req, adapterId } = args;
|
|
@@ -31,7 +32,7 @@ const resolveReadContext = async (args) => {
|
|
|
31
32
|
queryScope: void 0
|
|
32
33
|
};
|
|
33
34
|
}
|
|
34
|
-
if (scope !== null && adapter.id
|
|
35
|
+
if (scope !== null && runtime.configAdapterIds.has(adapter.id) && !adapter.capabilities.scopedQueries) {
|
|
35
36
|
if (!await platformReadFor(runtime, req)) return { ok: false };
|
|
36
37
|
return {
|
|
37
38
|
ok: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always, and
|
|
1
|
+
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always, and any scoped read through a\n * shared config adapter that cannot narrow the query to one scope, whether or\n * not it is the designated platform adapter. A tenant's own runtime adapters\n * are never gated. Any resolution failure (unknown adapter id, a throwing\n * scopeResolver or provider lookup) degrades to `{ ok: false }` so read paths\n * render their unavailable state instead of throwing.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\ttry {\n\t\tconst scope = args.scope !== undefined ? args.scope : await resolveScopeFor(runtime, req)\n\t\tconst registryScope = scope === PLATFORM_SCOPE ? null : scope\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\tconst adapter = adapterId ? registry.get(adapterId) : registry.default()\n\t\tif (scope === PLATFORM_SCOPE) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope: null, queryScope: undefined }\n\t\t}\n\t\tif (\n\t\t\tscope !== null &&\n\t\t\truntime.configAdapterIds.has(adapter.id) &&\n\t\t\t!adapter.capabilities.scopedQueries\n\t\t) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope, queryScope: undefined }\n\t\t}\n\t\treturn { ok: true, adapter, scope, queryScope: scope ?? undefined }\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,MAAa,qBAAqB,OAAO,SAAuD;CAC/F,MAAM,EAAE,SAAS,KAAK,cAAc;CACpC,IAAI;EACH,MAAM,QAAQ,KAAK,UAAU,KAAA,IAAY,KAAK,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EACxF,MAAM,gBAAgB,UAAA,MAA2B,OAAO;EACxD,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,MAAM,UAAU,YAAY,SAAS,IAAI,SAAS,IAAI,SAAS,QAAQ;EACvE,IAAI,UAAA,KAA0B;GAC7B,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS,OAAO;IAAM,YAAY,KAAA;GAAU;EAChE;EACA,IACC,UAAU,QACV,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,KACvC,CAAC,QAAQ,aAAa,eACrB;GACD,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS;IAAO,YAAY,KAAA;GAAU;EAC1D;EACA,OAAO;GAAE,IAAI;GAAM;GAAS;GAAO,YAAY,SAAS,KAAA;EAAU;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { BarList, BarListProps } from "../charts/BarList.js";
|
|
2
2
|
import { TrendChart, TrendChartProps } from "../charts/TrendChart.js";
|
|
3
|
+
import { WireSource } from "../fields/config/fetchSources.js";
|
|
4
|
+
import { MetricSelectField, MetricSelectFieldProps } from "../fields/config/MetricSelectField.js";
|
|
5
|
+
import { SourceSelectField } from "../fields/config/SourceSelectField.js";
|
|
6
|
+
import { useAnalyticsSources } from "../fields/config/useAnalyticsSources.js";
|
|
3
7
|
import { DateRangeField } from "../fields/dateRange/ui.js";
|
|
4
8
|
import { RealtimeCounter } from "../widgets/RealtimeCounter.js";
|
|
5
|
-
export { BarList, type BarListProps, DateRangeField, RealtimeCounter, TrendChart, type TrendChartProps };
|
|
9
|
+
export { BarList, type BarListProps, DateRangeField, MetricSelectField, type MetricSelectFieldProps, RealtimeCounter, SourceSelectField, TrendChart, type TrendChartProps, type WireSource, useAnalyticsSources };
|
package/dist/exports/client.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { BarList } from "../charts/BarList.js";
|
|
3
3
|
import { TrendChart } from "../charts/TrendChart.js";
|
|
4
|
+
import { useAnalyticsSources } from "../fields/config/useAnalyticsSources.js";
|
|
5
|
+
import { MetricSelectField } from "../fields/config/MetricSelectField.js";
|
|
6
|
+
import { SourceSelectField } from "../fields/config/SourceSelectField.js";
|
|
4
7
|
import { DateRangeField } from "../fields/dateRange/ui.js";
|
|
5
8
|
import { RealtimeCounter } from "../widgets/RealtimeCounter.js";
|
|
6
|
-
export { BarList, DateRangeField, RealtimeCounter, TrendChart };
|
|
9
|
+
export { BarList, DateRangeField, MetricSelectField, RealtimeCounter, SourceSelectField, TrendChart, useAnalyticsSources };
|
package/dist/exports/rsc.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DateRange, DimensionKey, MetricKey } from "../core/contract.js";
|
|
2
|
-
import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
|
|
3
2
|
import { CapabilityRequirement } from "../core/capabilities.js";
|
|
3
|
+
import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
|
|
4
4
|
import { AnalyticsStatField } from "../fields/AnalyticsStatField.js";
|
|
5
5
|
import { AnalyticsPanelField } from "../fields/AnalyticsPanelField.js";
|
|
6
6
|
import { formatMetricValue } from "../fields/format.js";
|
package/dist/exports/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
|
|
2
|
+
import { SerializedCapabilities } from "../core/capabilities.js";
|
|
2
3
|
import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "../binding/types.js";
|
|
3
4
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
5
|
import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions } from "../fields/factories.js";
|
|
5
6
|
import { AnalyticsPluginOptions } from "../core/options.js";
|
|
6
|
-
export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type TimeframePreset };
|
|
7
|
+
export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CapabilityRequirement } from "../../core/capabilities.js";
|
|
2
|
+
import { SelectFieldClientProps } from "payload";
|
|
3
|
+
|
|
4
|
+
//#region src/fields/config/MetricSelectField.d.ts
|
|
5
|
+
type MetricSelectFieldProps = SelectFieldClientProps & {
|
|
6
|
+
/** Extra capability requirement (beyond the picked metric) a widget's other config imposes, e.g. a breakdown dimension. */requires?: Omit<CapabilityRequirement, 'metrics'>;
|
|
7
|
+
/**
|
|
8
|
+
* Path of the sibling source select this picker narrows against, for
|
|
9
|
+
* custom widgets whose source field is named differently. Defaults to
|
|
10
|
+
* `'dataSource'`.
|
|
11
|
+
*/
|
|
12
|
+
sourceFieldPath?: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Metric picker for scoped widget config: narrows the static option list to
|
|
16
|
+
* what the sibling source field's selected source can actually serve, once
|
|
17
|
+
* the sources endpoint answers. Never clears an already-picked value that
|
|
18
|
+
* narrowing filters out; the read path degrades that case on its own.
|
|
19
|
+
*/
|
|
20
|
+
declare const MetricSelectField: (props: MetricSelectFieldProps) => import("react/jsx-runtime").JSX.Element;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { MetricSelectField, MetricSelectFieldProps };
|
|
23
|
+
//# sourceMappingURL=MetricSelectField.d.ts.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useTranslation as useTranslation$1 } from "../../translations/useTranslation.js";
|
|
3
|
+
import { narrowMetricOptions } from "./narrow.js";
|
|
4
|
+
import { toSelectOption } from "./toSelectOption.js";
|
|
5
|
+
import { useAnalyticsSources } from "./useAnalyticsSources.js";
|
|
6
|
+
import { useMemo } from "react";
|
|
7
|
+
import { jsx } from "react/jsx-runtime";
|
|
8
|
+
import { SelectInput, useField, useFormFields } from "@payloadcms/ui";
|
|
9
|
+
//#region src/fields/config/MetricSelectField.tsx
|
|
10
|
+
/**
|
|
11
|
+
* Metric picker for scoped widget config: narrows the static option list to
|
|
12
|
+
* what the sibling source field's selected source can actually serve, once
|
|
13
|
+
* the sources endpoint answers. Never clears an already-picked value that
|
|
14
|
+
* narrowing filters out; the read path degrades that case on its own.
|
|
15
|
+
*/
|
|
16
|
+
const MetricSelectField = (props) => {
|
|
17
|
+
const { field, path, readOnly, requires, sourceFieldPath = "dataSource" } = props;
|
|
18
|
+
const { i18n } = useTranslation$1();
|
|
19
|
+
const locale = i18n.language;
|
|
20
|
+
const { setValue, showError, value } = useField({ path });
|
|
21
|
+
const { sources } = useAnalyticsSources();
|
|
22
|
+
const sourceId = useFormFields(([fields]) => fields?.[sourceFieldPath]?.value);
|
|
23
|
+
const options = narrowMetricOptions({
|
|
24
|
+
options: useMemo(() => field.options.map((option) => toSelectOption(option, locale)), [field.options, locale]),
|
|
25
|
+
requires,
|
|
26
|
+
sourceId,
|
|
27
|
+
sources: sources ?? []
|
|
28
|
+
}).map((option) => ({
|
|
29
|
+
label: option.label,
|
|
30
|
+
value: option.value
|
|
31
|
+
}));
|
|
32
|
+
return /* @__PURE__ */ jsx(SelectInput, {
|
|
33
|
+
isClearable: false,
|
|
34
|
+
label: field.label,
|
|
35
|
+
name: field.name,
|
|
36
|
+
onChange: (selected) => {
|
|
37
|
+
const option = Array.isArray(selected) ? selected[0] : selected;
|
|
38
|
+
setValue(option ? String(option.value) : null);
|
|
39
|
+
},
|
|
40
|
+
options,
|
|
41
|
+
path,
|
|
42
|
+
readOnly,
|
|
43
|
+
required: field.required,
|
|
44
|
+
showError,
|
|
45
|
+
value
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
export { MetricSelectField };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=MetricSelectField.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MetricSelectField.js","names":["useTranslation"],"sources":["../../../src/fields/config/MetricSelectField.tsx"],"sourcesContent":["'use client'\n\nimport { type ReactSelectOption, SelectInput, useField, useFormFields } from '@payloadcms/ui'\nimport type { SelectFieldClientProps } from 'payload'\nimport { useMemo } from 'react'\nimport type { CapabilityRequirement } from '../../core/capabilities'\nimport { useTranslation } from '../../translations/useTranslation'\nimport { narrowMetricOptions } from './narrow'\nimport { toSelectOption } from './toSelectOption'\nimport { useAnalyticsSources } from './useAnalyticsSources'\n\nexport type MetricSelectFieldProps = SelectFieldClientProps & {\n\t/** Extra capability requirement (beyond the picked metric) a widget's other config imposes, e.g. a breakdown dimension. */\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n\t/**\n\t * Path of the sibling source select this picker narrows against, for\n\t * custom widgets whose source field is named differently. Defaults to\n\t * `'dataSource'`.\n\t */\n\tsourceFieldPath?: string\n}\n\n/**\n * Metric picker for scoped widget config: narrows the static option list to\n * what the sibling source field's selected source can actually serve, once\n * the sources endpoint answers. Never clears an already-picked value that\n * narrowing filters out; the read path degrades that case on its own.\n */\nexport const MetricSelectField = (props: MetricSelectFieldProps) => {\n\tconst { field, path, readOnly, requires, sourceFieldPath = 'dataSource' } = props\n\tconst { i18n } = useTranslation()\n\tconst locale = i18n.language\n\tconst { setValue, showError, value } = useField<string>({ path })\n\tconst { sources } = useAnalyticsSources()\n\tconst sourceId = useFormFields(\n\t\t([fields]) => fields?.[sourceFieldPath]?.value as string | undefined\n\t)\n\n\tconst staticOptions = useMemo(\n\t\t() => field.options.map((option) => toSelectOption(option, locale)),\n\t\t[field.options, locale]\n\t)\n\n\tconst options = narrowMetricOptions({\n\t\toptions: staticOptions,\n\t\trequires,\n\t\tsourceId,\n\t\tsources: sources ?? [],\n\t}).map((option) => ({ label: option.label as string, value: option.value }))\n\n\treturn (\n\t\t<SelectInput\n\t\t\tisClearable={false}\n\t\t\tlabel={field.label}\n\t\t\tname={field.name}\n\t\t\tonChange={(selected: ReactSelectOption | ReactSelectOption[]) => {\n\t\t\t\tconst option = Array.isArray(selected) ? selected[0] : selected\n\t\t\t\tsetValue(option ? String(option.value) : null)\n\t\t\t}}\n\t\t\toptions={options}\n\t\t\tpath={path}\n\t\t\treadOnly={readOnly}\n\t\t\trequired={field.required}\n\t\t\tshowError={showError}\n\t\t\tvalue={value}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAa,qBAAqB,UAAkC;CACnE,MAAM,EAAE,OAAO,MAAM,UAAU,UAAU,kBAAkB,iBAAiB;CAC5E,MAAM,EAAE,SAASA,iBAAe;CAChC,MAAM,SAAS,KAAK;CACpB,MAAM,EAAE,UAAU,WAAW,UAAU,SAAiB,EAAE,KAAK,CAAC;CAChE,MAAM,EAAE,YAAY,oBAAoB;CACxC,MAAM,WAAW,eACf,CAAC,YAAY,SAAS,kBAAkB,KAC1C;CAOA,MAAM,UAAU,oBAAoB;EACnC,SANqB,cACf,MAAM,QAAQ,KAAK,WAAW,eAAe,QAAQ,MAAM,CAAC,GAClE,CAAC,MAAM,SAAS,MAAM,CAID;EACrB;EACA;EACA,SAAS,WAAW,CAAC;CACtB,CAAC,EAAE,KAAK,YAAY;EAAE,OAAO,OAAO;EAAiB,OAAO,OAAO;CAAM,EAAE;CAE3E,OACC,oBAAC,aAAD;EACC,aAAa;EACb,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,WAAW,aAAsD;GAChE,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK;GACvD,SAAS,SAAS,OAAO,OAAO,KAAK,IAAI,IAAI;EAC9C;EACS;EACH;EACI;EACV,UAAU,MAAM;EACL;EACJ;CACP,CAAA;AAEH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { SelectFieldClientProps } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/fields/config/SourceSelectField.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Source picker for scoped widget config: starts from the field's static
|
|
6
|
+
* option list and, once the caller-scope sources endpoint answers, replaces
|
|
7
|
+
* it with the live adapter list so a tenant only ever sees sources it can
|
|
8
|
+
* actually read from. A failed fetch keeps the static list rather than
|
|
9
|
+
* emptying the picker.
|
|
10
|
+
*/
|
|
11
|
+
declare const SourceSelectField: (props: SelectFieldClientProps) => import("react/jsx-runtime").JSX.Element;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { SourceSelectField };
|
|
14
|
+
//# sourceMappingURL=SourceSelectField.d.ts.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useTranslation as useTranslation$1 } from "../../translations/useTranslation.js";
|
|
3
|
+
import { toSelectOption } from "./toSelectOption.js";
|
|
4
|
+
import { useAnalyticsSources } from "./useAnalyticsSources.js";
|
|
5
|
+
import { useMemo } from "react";
|
|
6
|
+
import { jsx } from "react/jsx-runtime";
|
|
7
|
+
import { SelectInput, useField } from "@payloadcms/ui";
|
|
8
|
+
//#region src/fields/config/SourceSelectField.tsx
|
|
9
|
+
/**
|
|
10
|
+
* Source picker for scoped widget config: starts from the field's static
|
|
11
|
+
* option list and, once the caller-scope sources endpoint answers, replaces
|
|
12
|
+
* it with the live adapter list so a tenant only ever sees sources it can
|
|
13
|
+
* actually read from. A failed fetch keeps the static list rather than
|
|
14
|
+
* emptying the picker.
|
|
15
|
+
*/
|
|
16
|
+
const SourceSelectField = (props) => {
|
|
17
|
+
const { field, path, readOnly } = props;
|
|
18
|
+
const { i18n } = useTranslation$1();
|
|
19
|
+
const locale = i18n.language;
|
|
20
|
+
const { setValue, showError, value } = useField({ path });
|
|
21
|
+
const { sources } = useAnalyticsSources();
|
|
22
|
+
const staticOptions = useMemo(() => field.options.map((option) => toSelectOption(option, locale)), [field.options, locale]);
|
|
23
|
+
const options = sources && sources.length > 0 ? sources.map((source) => ({
|
|
24
|
+
value: source.id,
|
|
25
|
+
label: source.label
|
|
26
|
+
})) : staticOptions;
|
|
27
|
+
return /* @__PURE__ */ jsx(SelectInput, {
|
|
28
|
+
isClearable: false,
|
|
29
|
+
label: field.label,
|
|
30
|
+
name: field.name,
|
|
31
|
+
onChange: (selected) => {
|
|
32
|
+
const option = Array.isArray(selected) ? selected[0] : selected;
|
|
33
|
+
setValue(option ? String(option.value) : null);
|
|
34
|
+
},
|
|
35
|
+
options,
|
|
36
|
+
path,
|
|
37
|
+
readOnly,
|
|
38
|
+
required: field.required,
|
|
39
|
+
showError,
|
|
40
|
+
value
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
//#endregion
|
|
44
|
+
export { SourceSelectField };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=SourceSelectField.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SourceSelectField.js","names":["useTranslation"],"sources":["../../../src/fields/config/SourceSelectField.tsx"],"sourcesContent":["'use client'\n\nimport { type ReactSelectOption, SelectInput, useField } from '@payloadcms/ui'\nimport type { SelectFieldClientProps } from 'payload'\nimport { useMemo } from 'react'\nimport { useTranslation } from '../../translations/useTranslation'\nimport { toSelectOption } from './toSelectOption'\nimport { useAnalyticsSources } from './useAnalyticsSources'\n\n/**\n * Source picker for scoped widget config: starts from the field's static\n * option list and, once the caller-scope sources endpoint answers, replaces\n * it with the live adapter list so a tenant only ever sees sources it can\n * actually read from. A failed fetch keeps the static list rather than\n * emptying the picker.\n */\nexport const SourceSelectField = (props: SelectFieldClientProps) => {\n\tconst { field, path, readOnly } = props\n\tconst { i18n } = useTranslation()\n\tconst locale = i18n.language\n\tconst { setValue, showError, value } = useField<string>({ path })\n\tconst { sources } = useAnalyticsSources()\n\n\tconst staticOptions = useMemo(\n\t\t() => field.options.map((option) => toSelectOption(option, locale)),\n\t\t[field.options, locale]\n\t)\n\n\tconst options =\n\t\tsources && sources.length > 0\n\t\t\t? sources.map((source) => ({ value: source.id, label: source.label }))\n\t\t\t: staticOptions\n\n\treturn (\n\t\t<SelectInput\n\t\t\tisClearable={false}\n\t\t\tlabel={field.label}\n\t\t\tname={field.name}\n\t\t\tonChange={(selected: ReactSelectOption | ReactSelectOption[]) => {\n\t\t\t\tconst option = Array.isArray(selected) ? selected[0] : selected\n\t\t\t\tsetValue(option ? String(option.value) : null)\n\t\t\t}}\n\t\t\toptions={options}\n\t\t\tpath={path}\n\t\t\treadOnly={readOnly}\n\t\t\trequired={field.required}\n\t\t\tshowError={showError}\n\t\t\tvalue={value}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAa,qBAAqB,UAAkC;CACnE,MAAM,EAAE,OAAO,MAAM,aAAa;CAClC,MAAM,EAAE,SAASA,iBAAe;CAChC,MAAM,SAAS,KAAK;CACpB,MAAM,EAAE,UAAU,WAAW,UAAU,SAAiB,EAAE,KAAK,CAAC;CAChE,MAAM,EAAE,YAAY,oBAAoB;CAExC,MAAM,gBAAgB,cACf,MAAM,QAAQ,KAAK,WAAW,eAAe,QAAQ,MAAM,CAAC,GAClE,CAAC,MAAM,SAAS,MAAM,CACvB;CAEA,MAAM,UACL,WAAW,QAAQ,SAAS,IACzB,QAAQ,KAAK,YAAY;EAAE,OAAO,OAAO;EAAI,OAAO,OAAO;CAAM,EAAE,IACnE;CAEJ,OACC,oBAAC,aAAD;EACC,aAAa;EACb,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,WAAW,aAAsD;GAChE,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK;GACvD,SAAS,SAAS,OAAO,OAAO,KAAK,IAAI,IAAI;EAC9C;EACS;EACH;EACI;EACV,UAAU,MAAM;EACL;EACJ;CACP,CAAA;AAEH"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { SerializedCapabilities } from "../../core/capabilities.js";
|
|
2
|
+
|
|
3
|
+
//#region src/fields/config/fetchSources.d.ts
|
|
4
|
+
interface WireSource {
|
|
5
|
+
id: string;
|
|
6
|
+
label: string;
|
|
7
|
+
kind: 'config' | 'runtime';
|
|
8
|
+
capabilities: SerializedCapabilities;
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
export { WireSource };
|
|
12
|
+
//# sourceMappingURL=fetchSources.d.ts.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { SOURCES_PATH } from "../../plugin/paths.js";
|
|
2
|
+
//#region src/fields/config/fetchSources.ts
|
|
3
|
+
const cache = /* @__PURE__ */ new Map();
|
|
4
|
+
/**
|
|
5
|
+
* Fetch the caller-scope source list once per user per admin session and share
|
|
6
|
+
* it between every picker instance on the page; a failed fetch clears its cache
|
|
7
|
+
* entry so a later mount retries instead of pinning the error. Keying by user
|
|
8
|
+
* id keeps a soft-navigation logout/login from serving the previous user's
|
|
9
|
+
* cached sources.
|
|
10
|
+
*/
|
|
11
|
+
const fetchSources = (serverURL, apiRoute, userKey) => {
|
|
12
|
+
const url = `${serverURL}${apiRoute}${SOURCES_PATH}`;
|
|
13
|
+
const key = `${userKey}:${url}`;
|
|
14
|
+
const hit = cache.get(key);
|
|
15
|
+
if (hit) return hit;
|
|
16
|
+
const p = fetch(url, { credentials: "include" }).then((res) => {
|
|
17
|
+
if (!res.ok) throw new Error(`sources ${res.status}`);
|
|
18
|
+
return res.json();
|
|
19
|
+
}).catch((err) => {
|
|
20
|
+
cache.delete(key);
|
|
21
|
+
throw err;
|
|
22
|
+
});
|
|
23
|
+
cache.set(key, p);
|
|
24
|
+
return p;
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
export { fetchSources };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=fetchSources.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetchSources.js","names":[],"sources":["../../../src/fields/config/fetchSources.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../../core/capabilities'\nimport { SOURCES_PATH } from '../../plugin/paths'\n\nexport interface WireSource {\n\tid: string\n\tlabel: string\n\tkind: 'config' | 'runtime'\n\tcapabilities: SerializedCapabilities\n}\n\nexport interface SourcesResponse {\n\tdefaultId: string | null\n\tsources: WireSource[]\n}\n\nconst cache = new Map<string, Promise<SourcesResponse>>()\n\n/**\n * Fetch the caller-scope source list once per user per admin session and share\n * it between every picker instance on the page; a failed fetch clears its cache\n * entry so a later mount retries instead of pinning the error. Keying by user\n * id keeps a soft-navigation logout/login from serving the previous user's\n * cached sources.\n */\nexport const fetchSources = (\n\tserverURL: string,\n\tapiRoute: string,\n\tuserKey: string\n): Promise<SourcesResponse> => {\n\tconst url = `${serverURL}${apiRoute}${SOURCES_PATH}`\n\tconst key = `${userKey}:${url}`\n\tconst hit = cache.get(key)\n\tif (hit) return hit\n\tconst p = fetch(url, { credentials: 'include' })\n\t\t.then((res) => {\n\t\t\tif (!res.ok) throw new Error(`sources ${res.status}`)\n\t\t\treturn res.json() as Promise<SourcesResponse>\n\t\t})\n\t\t.catch((err) => {\n\t\t\tcache.delete(key)\n\t\t\tthrow err\n\t\t})\n\tcache.set(key, p)\n\treturn p\n}\n"],"mappings":";;AAeA,MAAM,wBAAQ,IAAI,IAAsC;;;;;;;;AASxD,MAAa,gBACZ,WACA,UACA,YAC8B;CAC9B,MAAM,MAAM,GAAG,YAAY,WAAW;CACtC,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,MAAM,MAAM,MAAM,IAAI,GAAG;CACzB,IAAI,KAAK,OAAO;CAChB,MAAM,IAAI,MAAM,KAAK,EAAE,aAAa,UAAU,CAAC,EAC7C,MAAM,QAAQ;EACd,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,WAAW,IAAI,QAAQ;EACpD,OAAO,IAAI,KAAK;CACjB,CAAC,EACA,OAAO,QAAQ;EACf,MAAM,OAAO,GAAG;EAChB,MAAM;CACP,CAAC;CACF,MAAM,IAAI,KAAK,CAAC;CAChB,OAAO;AACR"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/fields/config/narrow.ts
|
|
2
|
+
/** satisfiesCapabilities over the wire form (arrays instead of Sets). */
|
|
3
|
+
const satisfiesSerialized = (caps, req) => {
|
|
4
|
+
if (req.realtime && !caps.realtime) return false;
|
|
5
|
+
if (req.perPageQuery && !caps.perPageQuery) return false;
|
|
6
|
+
if (req.metrics?.some((m) => !caps.metrics.includes(m))) return false;
|
|
7
|
+
if (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false;
|
|
8
|
+
return true;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Options for the metric picker, narrowed to what the selected source can
|
|
12
|
+
* serve. An unknown source id (a stale value, a source the endpoint could not
|
|
13
|
+
* list) keeps the full static list, mirroring the server-side filterOptions
|
|
14
|
+
* fallback, and a source that cannot meet the widget's extra requirements at
|
|
15
|
+
* all falls back to the full list rather than an empty picker.
|
|
16
|
+
*/
|
|
17
|
+
const narrowMetricOptions = (args) => {
|
|
18
|
+
const src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : void 0;
|
|
19
|
+
if (!src) return args.options;
|
|
20
|
+
if (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) return args.options;
|
|
21
|
+
const narrowed = args.options.filter((o) => satisfiesSerialized(src.capabilities, {
|
|
22
|
+
...args.requires,
|
|
23
|
+
metrics: [o.value]
|
|
24
|
+
}));
|
|
25
|
+
return narrowed.length > 0 ? narrowed : args.options;
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { narrowMetricOptions };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=narrow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/fields/config/sourcesState.ts
|
|
2
|
+
const EMPTY_SOURCES = {
|
|
3
|
+
defaultId: null,
|
|
4
|
+
sources: null
|
|
5
|
+
};
|
|
6
|
+
/** Sources fetched for another user never render: a key mismatch reads as not-yet-loaded. */
|
|
7
|
+
const resolveSourcesState = (state, userKey) => state.key === userKey ? state.data : EMPTY_SOURCES;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { EMPTY_SOURCES, resolveSourcesState };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=sourcesState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sourcesState.js","names":[],"sources":["../../../src/fields/config/sourcesState.ts"],"sourcesContent":["import type { AnalyticsSources } from './useAnalyticsSources'\n\nexport interface KeyedSources {\n\tkey: string\n\tdata: AnalyticsSources\n}\n\nexport const EMPTY_SOURCES: AnalyticsSources = { defaultId: null, sources: null }\n\n/** Sources fetched for another user never render: a key mismatch reads as not-yet-loaded. */\nexport const resolveSourcesState = (state: KeyedSources, userKey: string): AnalyticsSources =>\n\tstate.key === userKey ? state.data : EMPTY_SOURCES\n"],"mappings":";AAOA,MAAa,gBAAkC;CAAE,WAAW;CAAM,SAAS;AAAK;;AAGhF,MAAa,uBAAuB,OAAqB,YACxD,MAAM,QAAQ,UAAU,MAAM,OAAO"}
|