opscms-analytics-plugin 0.0.0-stage → 1.0.0

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 ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ First release as a package of its own (it was part of the platform's code). Keeps a site's analytics providers in its own table,
6
+ `analytics_integrations`, which the plugin creates when installed and drops when removed, and carries out the `ga4-send-event` workflow action.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 puzzo-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # opscms-analytics-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Per-site analytics for the OpsCMS platform, built with [`opscms-sdk`](../opscms-sdk).
4
+
5
+ - **`analytics-integrations`**: each site's own analytics providers: Google (GA4 and Tag Manager), Matomo, Plausible, Fathom, Umami, PostHog, or a custom
6
+ script. A site can run several at once. The server secret (GA4's Measurement Protocol secret) is encrypted under the site's key and shown masked; the
7
+ platform's public content API never returns it. A **custom script** is injected verbatim into every page of the site, so only the platform owner may write one.
8
+ - **The `ga4-send-event` workflow action**: carries out the platform's `send_analytics_event` block, sending a server-side event to GA4 with the site's own
9
+ measurement id and secret. A site with no active GA4 setup is skipped successfully: tracking is best-effort and never fails the business workflow.
10
+
11
+ Meta's own server-side events belong to the Meta plugin (`meta-conversion-event`), not to this one.
12
+
13
+ ## Install
14
+
15
+ From the admin: **Plugins → Install from npm → `opscms-analytics-plugin`**. The platform creates the plugin's table (its one migration), lists the plugin
16
+ with its logo, and restarts to start it. **Removing the plugin drops its table and the secrets in it.**
17
+
18
+ The platform currently carries this plugin in its own code under the same key; install the package only after that copy has been removed. The platform's
19
+ public content API serves this collection to a site's storefront by its slug, `analytics-integrations`.
20
+
21
+ ## Needs
22
+
23
+ `payload` ^3 and `opscms-sdk` ^0.1.7 (the platform provides both).
24
+
25
+ ## Develop
26
+
27
+ ```
28
+ npm install
29
+ npm run typecheck && npm test && npm run build && npm pack --dry-run
30
+ ```
31
+
32
+ `opscms-sdk` is linked from a sibling checkout (`file:../opscms-sdk`) until it is published.
@@ -0,0 +1,60 @@
1
+ import * as opscms_sdk from 'opscms-sdk';
2
+ import { WorkflowActionContext, WorkflowStepResult } from 'opscms-sdk';
3
+ import { CollectionConfig } from 'payload';
4
+
5
+ /** The slug of the collection. */
6
+ declare const ANALYTICS_INTEGRATIONS: "analytics-integrations";
7
+ /**
8
+ * AnalyticsIntegrations
9
+ *
10
+ * Stores per-site analytics provider configurations.
11
+ * Each site can have multiple active analytics providers simultaneously
12
+ * (e.g. Google Analytics + Matomo on the same project).
13
+ *
14
+ * Wired to frontends through `@ivarse/shared-cms/server#getAnalyticsIntegrations`
15
+ * and rendered by the `@ivarse/ui/Analytics` component. Server-side GA4
16
+ * Measurement Protocol calls read `apiSecret` from this collection via the
17
+ * `ga4-send-event` workflow action registered in `marketingActions.ts`.
18
+ *
19
+ * Does NOT include Meta — that lives in opscms-meta-plugin's `meta-config`
20
+ * collection (populated by its OAuth Connect flow), not here. A `meta-capi`
21
+ * provider used to exist on this collection with its own separate credential
22
+ * entry; retired since it duplicated meta-config for no benefit and had zero
23
+ * adoption.
24
+ *
25
+ * `google-analytics` and `google-tag-manager` used to be two separate provider
26
+ * options, each requiring its own record even though most sites run GA4 and
27
+ * GTM together. Consolidated into a single `google` provider carrying all
28
+ * three Google-related inputs (trackingId = GA4 measurement ID, tagId = GTM
29
+ * container ID, apiSecret = GA4 Measurement Protocol secret) — any subset can
30
+ * be filled in, so a site can use just GA4, just GTM, or both from one record.
31
+ */
32
+ declare const AnalyticsIntegrations: CollectionConfig;
33
+
34
+ declare const analyticsManifest: opscms_sdk.PluginManifest;
35
+
36
+ /** Resolve a field_mapping of { paramName: "{{template}}" } against the workflow context. */
37
+ declare function resolveParams(mapping: Record<string, unknown> | null | undefined, ctx: Record<string, unknown>): Record<string, string>;
38
+ /** Build the GA4 Measurement Protocol request body. Exposed for unit verification. */
39
+ declare function buildGa4Body(args: {
40
+ clientId?: string;
41
+ eventName: string;
42
+ params: Record<string, string>;
43
+ }): {
44
+ client_id: string;
45
+ events: Array<{
46
+ name: string;
47
+ params: Record<string, unknown>;
48
+ }>;
49
+ };
50
+ declare function ga4SendHandler(ctx: WorkflowActionContext): Promise<WorkflowStepResult>;
51
+
52
+ /**
53
+ * Per-site analytics: the `analytics-integrations` collection (each site's own Google, Matomo, Plausible, Fathom, Umami, PostHog or custom settings, with the
54
+ * secret encrypted), and the server-side GA4 workflow action (`ga4-send-event`) that reads them for the platform's `send_analytics_event` block.
55
+ *
56
+ * Meta's own server-side events are the Meta plugin's (`meta-conversion-event`), not this plugin's.
57
+ */
58
+ declare const analyticsPlugin: opscms_sdk.PlatformPlugin;
59
+
60
+ export { ANALYTICS_INTEGRATIONS, AnalyticsIntegrations, analyticsManifest, analyticsPlugin, buildGa4Body, ga4SendHandler, resolveParams };
@@ -0,0 +1,60 @@
1
+ import * as opscms_sdk from 'opscms-sdk';
2
+ import { WorkflowActionContext, WorkflowStepResult } from 'opscms-sdk';
3
+ import { CollectionConfig } from 'payload';
4
+
5
+ /** The slug of the collection. */
6
+ declare const ANALYTICS_INTEGRATIONS: "analytics-integrations";
7
+ /**
8
+ * AnalyticsIntegrations
9
+ *
10
+ * Stores per-site analytics provider configurations.
11
+ * Each site can have multiple active analytics providers simultaneously
12
+ * (e.g. Google Analytics + Matomo on the same project).
13
+ *
14
+ * Wired to frontends through `@ivarse/shared-cms/server#getAnalyticsIntegrations`
15
+ * and rendered by the `@ivarse/ui/Analytics` component. Server-side GA4
16
+ * Measurement Protocol calls read `apiSecret` from this collection via the
17
+ * `ga4-send-event` workflow action registered in `marketingActions.ts`.
18
+ *
19
+ * Does NOT include Meta — that lives in opscms-meta-plugin's `meta-config`
20
+ * collection (populated by its OAuth Connect flow), not here. A `meta-capi`
21
+ * provider used to exist on this collection with its own separate credential
22
+ * entry; retired since it duplicated meta-config for no benefit and had zero
23
+ * adoption.
24
+ *
25
+ * `google-analytics` and `google-tag-manager` used to be two separate provider
26
+ * options, each requiring its own record even though most sites run GA4 and
27
+ * GTM together. Consolidated into a single `google` provider carrying all
28
+ * three Google-related inputs (trackingId = GA4 measurement ID, tagId = GTM
29
+ * container ID, apiSecret = GA4 Measurement Protocol secret) — any subset can
30
+ * be filled in, so a site can use just GA4, just GTM, or both from one record.
31
+ */
32
+ declare const AnalyticsIntegrations: CollectionConfig;
33
+
34
+ declare const analyticsManifest: opscms_sdk.PluginManifest;
35
+
36
+ /** Resolve a field_mapping of { paramName: "{{template}}" } against the workflow context. */
37
+ declare function resolveParams(mapping: Record<string, unknown> | null | undefined, ctx: Record<string, unknown>): Record<string, string>;
38
+ /** Build the GA4 Measurement Protocol request body. Exposed for unit verification. */
39
+ declare function buildGa4Body(args: {
40
+ clientId?: string;
41
+ eventName: string;
42
+ params: Record<string, string>;
43
+ }): {
44
+ client_id: string;
45
+ events: Array<{
46
+ name: string;
47
+ params: Record<string, unknown>;
48
+ }>;
49
+ };
50
+ declare function ga4SendHandler(ctx: WorkflowActionContext): Promise<WorkflowStepResult>;
51
+
52
+ /**
53
+ * Per-site analytics: the `analytics-integrations` collection (each site's own Google, Matomo, Plausible, Fathom, Umami, PostHog or custom settings, with the
54
+ * secret encrypted), and the server-side GA4 workflow action (`ga4-send-event`) that reads them for the platform's `send_analytics_event` block.
55
+ *
56
+ * Meta's own server-side events are the Meta plugin's (`meta-conversion-event`), not this plugin's.
57
+ */
58
+ declare const analyticsPlugin: opscms_sdk.PlatformPlugin;
59
+
60
+ export { ANALYTICS_INTEGRATIONS, AnalyticsIntegrations, analyticsManifest, analyticsPlugin, buildGa4Body, ga4SendHandler, resolveParams };
package/dist/index.js ADDED
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ANALYTICS_INTEGRATIONS: () => ANALYTICS_INTEGRATIONS,
24
+ AnalyticsIntegrations: () => AnalyticsIntegrations,
25
+ analyticsManifest: () => analyticsManifest,
26
+ analyticsPlugin: () => analyticsPlugin,
27
+ buildGa4Body: () => buildGa4Body,
28
+ ga4SendHandler: () => ga4SendHandler,
29
+ resolveParams: () => resolveParams
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+ var import_opscms_sdk5 = require("opscms-sdk");
33
+
34
+ // src/AnalyticsIntegrations.ts
35
+ var import_opscms_sdk = require("opscms-sdk");
36
+ var ANALYTICS_INTEGRATIONS = "analytics-integrations";
37
+ var onlySuperAdminField = ({ req }) => req?.user?.role === "super-admin";
38
+ var AnalyticsIntegrations = {
39
+ slug: ANALYTICS_INTEGRATIONS,
40
+ admin: {
41
+ useAsTitle: "label",
42
+ defaultColumns: ["label", "provider", "project", "isActive", "createdAt"],
43
+ group: "Configuration"
44
+ },
45
+ access: {
46
+ read: import_opscms_sdk.access.siteScopedRead(),
47
+ create: import_opscms_sdk.access.siteScopedCreate,
48
+ update: import_opscms_sdk.access.siteScopedUpdate(),
49
+ delete: import_opscms_sdk.access.siteScopedDelete()
50
+ },
51
+ fields: [
52
+ {
53
+ name: "label",
54
+ type: "text",
55
+ required: true,
56
+ admin: { description: 'Friendly label, e.g. "GA \u2013 ivarse.com"' }
57
+ },
58
+ {
59
+ name: "provider",
60
+ type: "select",
61
+ required: true,
62
+ options: [
63
+ { label: "Google (Analytics + Tag Manager)", value: "google" },
64
+ { label: "Matomo", value: "matomo" },
65
+ { label: "Plausible", value: "plausible" },
66
+ { label: "Fathom", value: "fathom" },
67
+ { label: "Umami", value: "umami" },
68
+ { label: "PostHog", value: "posthog" },
69
+ { label: "Custom", value: "custom" }
70
+ ]
71
+ },
72
+ // ── Provider-specific settings ──────────────────────────────
73
+ {
74
+ name: "trackingId",
75
+ type: "text",
76
+ admin: {
77
+ description: "Measurement / tracking ID \u2014 GA4 measurement ID (G-XXXX) for Google, or site ID for others. Leave blank if only using Tag Manager.",
78
+ condition: (_data, siblingData) => ["google", "matomo", "plausible", "fathom", "umami", "posthog"].includes(
79
+ siblingData?.provider
80
+ )
81
+ }
82
+ },
83
+ {
84
+ name: "tagId",
85
+ type: "text",
86
+ admin: {
87
+ description: "Google Tag Manager container ID (GTM-XXXX). Leave blank if not using Tag Manager.",
88
+ condition: (_data, siblingData) => siblingData?.provider === "google"
89
+ }
90
+ },
91
+ // Server-side secret: the GA4 Measurement Protocol api_secret. Encrypted at rest under the site's key and shown masked; the real value is read only by the
92
+ // ga4-send-event workflow action, which asks for it explicitly (`context.preventMasking`). Anyone else, an anonymous request to the platform's public content
93
+ // delivery API included, gets the mask: the field fails CLOSED.
94
+ (0, import_opscms_sdk.secretField)(ANALYTICS_INTEGRATIONS, "apiSecret", {
95
+ label: "API secret",
96
+ description: "Server secret: the GA4 Measurement Protocol API secret.",
97
+ condition: (_data, siblingData) => siblingData?.provider === "google"
98
+ }),
99
+ {
100
+ name: "serverUrl",
101
+ type: "text",
102
+ admin: {
103
+ description: "Self-hosted instance URL (Matomo, Umami, Plausible, PostHog)",
104
+ condition: (_data, siblingData) => ["matomo", "plausible", "umami", "posthog"].includes(siblingData?.provider)
105
+ }
106
+ },
107
+ {
108
+ name: "customScript",
109
+ type: "code",
110
+ // Rendered raw into every page of every site by packages/ui Analytics.tsx.
111
+ // It cannot be sanitised — it is deliberately a script tag — so the control
112
+ // has to be who may write it. Any editor with access to this field could
113
+ // otherwise run arbitrary JavaScript on all eight brands at once, and the
114
+ // shared CSP allows 'unsafe-inline' so nothing downstream would stop it.
115
+ access: { create: onlySuperAdminField, update: onlySuperAdminField },
116
+ admin: {
117
+ language: "html",
118
+ description: 'Raw analytics script tag(s) for the "Custom" provider. Super-admin only: this is injected verbatim into every page.',
119
+ condition: (_data, siblingData) => siblingData?.provider === "custom"
120
+ }
121
+ },
122
+ // ── Relationships ───────────────────────────────────────────
123
+ {
124
+ name: "site",
125
+ type: "relationship",
126
+ relationTo: "sites",
127
+ required: true,
128
+ index: true,
129
+ admin: { description: "The site this integration applies to" },
130
+ // The value of `site` is decided by who is writing, not by what they submitted. Without this an editor could plant a `customScript` (rendered raw
131
+ // on every page) under another tenant's site: a cross-tenant stored-XSS path.
132
+ hooks: { beforeValidate: [import_opscms_sdk.tenancy.pinSite] }
133
+ },
134
+ {
135
+ name: "organization",
136
+ type: "relationship",
137
+ relationTo: "organizations",
138
+ required: true,
139
+ index: true,
140
+ admin: { readOnly: true, description: "Set from the site: a site belongs to exactly one organization." },
141
+ // Skipped on create (the hook sets it), so a read-only required field does not block the form.
142
+ validate: (value, { operation }) => operation === "create" || value != null ? true : "This field is required.",
143
+ hooks: { beforeValidate: [import_opscms_sdk.tenancy.pinOrganization] }
144
+ },
145
+ {
146
+ name: "isActive",
147
+ type: "checkbox",
148
+ defaultValue: true
149
+ }
150
+ ],
151
+ timestamps: true
152
+ };
153
+
154
+ // src/manifest.ts
155
+ var import_opscms_sdk2 = require("opscms-sdk");
156
+ var analyticsManifest = (0, import_opscms_sdk2.definePluginManifest)({
157
+ key: "analytics",
158
+ name: "Analytics & Insights",
159
+ description: "Analytics integrations per site: Google (GA4 and Tag Manager), Matomo, Plausible, Fathom, Umami, PostHog or a custom script; server-side GA4 events; and the marketing dashboard. (Meta Pixel belongs to the Meta plugin.)",
160
+ category: "analytics",
161
+ icon: "icon.svg",
162
+ releases: [
163
+ {
164
+ version: "1.0.0",
165
+ date: "2026-11-05",
166
+ notes: [
167
+ "Packaged as a plugin: per-site analytics settings (credentials encrypted) and the server-side GA4 workflow action.",
168
+ "Part of the CMS since 2026-05-28."
169
+ ]
170
+ }
171
+ ]
172
+ });
173
+
174
+ // src/marketingActions.ts
175
+ var import_opscms_sdk3 = require("opscms-sdk");
176
+ var HTTP_TIMEOUT_MS = 8e3;
177
+ function resolveParams(mapping, ctx) {
178
+ const out = {};
179
+ for (const [key, tpl] of Object.entries(mapping ?? {})) {
180
+ if (typeof tpl === "string") {
181
+ const resolved = (0, import_opscms_sdk3.platform)().notifications.renderTemplate(tpl, ctx);
182
+ if (resolved !== void 0 && resolved !== null && resolved !== "") out[key] = String(resolved);
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+ function buildGa4Body(args) {
188
+ const { value, currency, ...rest } = args.params;
189
+ const params = { ...rest };
190
+ if (value !== void 0) params.value = Number(value);
191
+ if (currency) params.currency = currency;
192
+ return {
193
+ // A client_id is required by MP; fall back to a server-generated one for pure
194
+ // server events that have no browser client id.
195
+ client_id: args.clientId && args.clientId.length > 0 ? args.clientId : `srv.${Date.now()}`,
196
+ events: [{ name: args.eventName, params }]
197
+ };
198
+ }
199
+ async function findConfig(payload, siteSlug, provider) {
200
+ if (!siteSlug) return void 0;
201
+ const res = await payload.find({
202
+ collection: ANALYTICS_INTEGRATIONS,
203
+ where: {
204
+ and: [
205
+ { "site.slug": { equals: siteSlug } },
206
+ { provider: { equals: provider } },
207
+ { isActive: { equals: true } }
208
+ ]
209
+ },
210
+ limit: 1,
211
+ depth: 0,
212
+ overrideAccess: true,
213
+ context: { preventMasking: true }
214
+ });
215
+ return res.docs[0];
216
+ }
217
+ async function ga4SendHandler(ctx) {
218
+ const siteSlug = ctx.workflowContext.siteSlug;
219
+ const eventName = ctx.step.event_name;
220
+ if (!eventName) return { success: false, error: "ga4-send-event requires event_name" };
221
+ const cfg = await findConfig(ctx.payload, siteSlug, "google");
222
+ const measurementId = cfg?.trackingId;
223
+ const apiSecret = cfg?.apiSecret ?? "";
224
+ if (!measurementId || !apiSecret) {
225
+ ctx.payload.logger.info(`[ga4-send-event] no active GA4 config for ${siteSlug} \u2014 skipping`);
226
+ return { success: true, data: { ga4_skipped: true } };
227
+ }
228
+ const params = resolveParams(ctx.step.field_mapping, ctx.workflowContext);
229
+ const clientId = params.client_id;
230
+ delete params.client_id;
231
+ const body = buildGa4Body({ clientId, eventName, params });
232
+ try {
233
+ const res = await fetch(
234
+ `https://www.google-analytics.com/mp/collect?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`,
235
+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) }
236
+ );
237
+ if (res.status !== 204 && !res.ok) {
238
+ const text = await res.text().catch(() => "");
239
+ return { success: false, error: `GA4 MP \u2192 ${res.status}: ${text.slice(0, 200)}` };
240
+ }
241
+ return { success: true, data: { ga4_event: eventName } };
242
+ } catch (err) {
243
+ return { success: false, error: `GA4 MP request failed: ${err instanceof Error ? err.message : String(err)}` };
244
+ }
245
+ }
246
+ var marketingActions = [{ name: "ga4-send-event", handler: ga4SendHandler }];
247
+
248
+ // src/migrations.ts
249
+ var import_opscms_sdk4 = require("opscms-sdk");
250
+ var migration = (0, import_opscms_sdk4.sqlMigration)("analytics:20261108_100000_create_integrations", {
251
+ up: [
252
+ `DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_analytics_integrations_provider') THEN CREATE TYPE "public"."enum_analytics_integrations_provider" AS ENUM('google', 'matomo', 'plausible', 'fathom', 'umami', 'posthog', 'custom'); END IF; END $$;`,
253
+ `CREATE TABLE IF NOT EXISTS "analytics_integrations" (
254
+ "id" serial PRIMARY KEY NOT NULL,
255
+ "label" varchar NOT NULL,
256
+ "provider" "public"."enum_analytics_integrations_provider" NOT NULL,
257
+ "tracking_id" varchar,
258
+ "tag_id" varchar,
259
+ "api_secret" varchar,
260
+ "server_url" varchar,
261
+ "custom_script" varchar,
262
+ "site_id" integer NOT NULL,
263
+ "organization_id" integer NOT NULL,
264
+ "is_active" boolean DEFAULT true,
265
+ "updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
266
+ "created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
267
+ )`,
268
+ `ALTER TABLE "payload_locked_documents_rels" ADD COLUMN IF NOT EXISTS "analytics_integrations_id" integer`,
269
+ `DO $$ BEGIN ALTER TABLE "analytics_integrations" ADD CONSTRAINT "analytics_integrations_site_id_sites_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("id") ON DELETE set null ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
270
+ `DO $$ BEGIN ALTER TABLE "analytics_integrations" ADD CONSTRAINT "analytics_integrations_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE set null ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
271
+ `DO $$ BEGIN ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_analytics_integrations_fk" FOREIGN KEY ("analytics_integrations_id") REFERENCES "public"."analytics_integrations"("id") ON DELETE cascade ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
272
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_site_idx" ON "analytics_integrations" USING btree ("site_id")`,
273
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_organization_idx" ON "analytics_integrations" USING btree ("organization_id")`,
274
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_updated_at_idx" ON "analytics_integrations" USING btree ("updated_at")`,
275
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_created_at_idx" ON "analytics_integrations" USING btree ("created_at")`,
276
+ `CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_analytics_integrations_id_idx" ON "payload_locked_documents_rels" USING btree ("analytics_integrations_id")`
277
+ ],
278
+ down: [
279
+ `ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "analytics_integrations_id"`,
280
+ `DROP TABLE IF EXISTS "analytics_integrations" CASCADE`,
281
+ `DROP TYPE IF EXISTS "public"."enum_analytics_integrations_provider"`
282
+ ]
283
+ });
284
+
285
+ // src/index.ts
286
+ var analyticsPlugin = (0, import_opscms_sdk5.definePlugin)({
287
+ manifest: analyticsManifest,
288
+ collections: [AnalyticsIntegrations],
289
+ workflowActions: marketingActions,
290
+ migrations: [migration]
291
+ });
292
+ // Annotate the CommonJS export names for ESM import in node:
293
+ 0 && (module.exports = {
294
+ ANALYTICS_INTEGRATIONS,
295
+ AnalyticsIntegrations,
296
+ analyticsManifest,
297
+ analyticsPlugin,
298
+ buildGa4Body,
299
+ ga4SendHandler,
300
+ resolveParams
301
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,270 @@
1
+ // src/index.ts
2
+ import { definePlugin } from "opscms-sdk";
3
+
4
+ // src/AnalyticsIntegrations.ts
5
+ import { access, secretField, tenancy } from "opscms-sdk";
6
+ var ANALYTICS_INTEGRATIONS = "analytics-integrations";
7
+ var onlySuperAdminField = ({ req }) => req?.user?.role === "super-admin";
8
+ var AnalyticsIntegrations = {
9
+ slug: ANALYTICS_INTEGRATIONS,
10
+ admin: {
11
+ useAsTitle: "label",
12
+ defaultColumns: ["label", "provider", "project", "isActive", "createdAt"],
13
+ group: "Configuration"
14
+ },
15
+ access: {
16
+ read: access.siteScopedRead(),
17
+ create: access.siteScopedCreate,
18
+ update: access.siteScopedUpdate(),
19
+ delete: access.siteScopedDelete()
20
+ },
21
+ fields: [
22
+ {
23
+ name: "label",
24
+ type: "text",
25
+ required: true,
26
+ admin: { description: 'Friendly label, e.g. "GA \u2013 ivarse.com"' }
27
+ },
28
+ {
29
+ name: "provider",
30
+ type: "select",
31
+ required: true,
32
+ options: [
33
+ { label: "Google (Analytics + Tag Manager)", value: "google" },
34
+ { label: "Matomo", value: "matomo" },
35
+ { label: "Plausible", value: "plausible" },
36
+ { label: "Fathom", value: "fathom" },
37
+ { label: "Umami", value: "umami" },
38
+ { label: "PostHog", value: "posthog" },
39
+ { label: "Custom", value: "custom" }
40
+ ]
41
+ },
42
+ // ── Provider-specific settings ──────────────────────────────
43
+ {
44
+ name: "trackingId",
45
+ type: "text",
46
+ admin: {
47
+ description: "Measurement / tracking ID \u2014 GA4 measurement ID (G-XXXX) for Google, or site ID for others. Leave blank if only using Tag Manager.",
48
+ condition: (_data, siblingData) => ["google", "matomo", "plausible", "fathom", "umami", "posthog"].includes(
49
+ siblingData?.provider
50
+ )
51
+ }
52
+ },
53
+ {
54
+ name: "tagId",
55
+ type: "text",
56
+ admin: {
57
+ description: "Google Tag Manager container ID (GTM-XXXX). Leave blank if not using Tag Manager.",
58
+ condition: (_data, siblingData) => siblingData?.provider === "google"
59
+ }
60
+ },
61
+ // Server-side secret: the GA4 Measurement Protocol api_secret. Encrypted at rest under the site's key and shown masked; the real value is read only by the
62
+ // ga4-send-event workflow action, which asks for it explicitly (`context.preventMasking`). Anyone else, an anonymous request to the platform's public content
63
+ // delivery API included, gets the mask: the field fails CLOSED.
64
+ secretField(ANALYTICS_INTEGRATIONS, "apiSecret", {
65
+ label: "API secret",
66
+ description: "Server secret: the GA4 Measurement Protocol API secret.",
67
+ condition: (_data, siblingData) => siblingData?.provider === "google"
68
+ }),
69
+ {
70
+ name: "serverUrl",
71
+ type: "text",
72
+ admin: {
73
+ description: "Self-hosted instance URL (Matomo, Umami, Plausible, PostHog)",
74
+ condition: (_data, siblingData) => ["matomo", "plausible", "umami", "posthog"].includes(siblingData?.provider)
75
+ }
76
+ },
77
+ {
78
+ name: "customScript",
79
+ type: "code",
80
+ // Rendered raw into every page of every site by packages/ui Analytics.tsx.
81
+ // It cannot be sanitised — it is deliberately a script tag — so the control
82
+ // has to be who may write it. Any editor with access to this field could
83
+ // otherwise run arbitrary JavaScript on all eight brands at once, and the
84
+ // shared CSP allows 'unsafe-inline' so nothing downstream would stop it.
85
+ access: { create: onlySuperAdminField, update: onlySuperAdminField },
86
+ admin: {
87
+ language: "html",
88
+ description: 'Raw analytics script tag(s) for the "Custom" provider. Super-admin only: this is injected verbatim into every page.',
89
+ condition: (_data, siblingData) => siblingData?.provider === "custom"
90
+ }
91
+ },
92
+ // ── Relationships ───────────────────────────────────────────
93
+ {
94
+ name: "site",
95
+ type: "relationship",
96
+ relationTo: "sites",
97
+ required: true,
98
+ index: true,
99
+ admin: { description: "The site this integration applies to" },
100
+ // The value of `site` is decided by who is writing, not by what they submitted. Without this an editor could plant a `customScript` (rendered raw
101
+ // on every page) under another tenant's site: a cross-tenant stored-XSS path.
102
+ hooks: { beforeValidate: [tenancy.pinSite] }
103
+ },
104
+ {
105
+ name: "organization",
106
+ type: "relationship",
107
+ relationTo: "organizations",
108
+ required: true,
109
+ index: true,
110
+ admin: { readOnly: true, description: "Set from the site: a site belongs to exactly one organization." },
111
+ // Skipped on create (the hook sets it), so a read-only required field does not block the form.
112
+ validate: (value, { operation }) => operation === "create" || value != null ? true : "This field is required.",
113
+ hooks: { beforeValidate: [tenancy.pinOrganization] }
114
+ },
115
+ {
116
+ name: "isActive",
117
+ type: "checkbox",
118
+ defaultValue: true
119
+ }
120
+ ],
121
+ timestamps: true
122
+ };
123
+
124
+ // src/manifest.ts
125
+ import { definePluginManifest } from "opscms-sdk";
126
+ var analyticsManifest = definePluginManifest({
127
+ key: "analytics",
128
+ name: "Analytics & Insights",
129
+ description: "Analytics integrations per site: Google (GA4 and Tag Manager), Matomo, Plausible, Fathom, Umami, PostHog or a custom script; server-side GA4 events; and the marketing dashboard. (Meta Pixel belongs to the Meta plugin.)",
130
+ category: "analytics",
131
+ icon: "icon.svg",
132
+ releases: [
133
+ {
134
+ version: "1.0.0",
135
+ date: "2026-11-05",
136
+ notes: [
137
+ "Packaged as a plugin: per-site analytics settings (credentials encrypted) and the server-side GA4 workflow action.",
138
+ "Part of the CMS since 2026-05-28."
139
+ ]
140
+ }
141
+ ]
142
+ });
143
+
144
+ // src/marketingActions.ts
145
+ import { platform } from "opscms-sdk";
146
+ var HTTP_TIMEOUT_MS = 8e3;
147
+ function resolveParams(mapping, ctx) {
148
+ const out = {};
149
+ for (const [key, tpl] of Object.entries(mapping ?? {})) {
150
+ if (typeof tpl === "string") {
151
+ const resolved = platform().notifications.renderTemplate(tpl, ctx);
152
+ if (resolved !== void 0 && resolved !== null && resolved !== "") out[key] = String(resolved);
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+ function buildGa4Body(args) {
158
+ const { value, currency, ...rest } = args.params;
159
+ const params = { ...rest };
160
+ if (value !== void 0) params.value = Number(value);
161
+ if (currency) params.currency = currency;
162
+ return {
163
+ // A client_id is required by MP; fall back to a server-generated one for pure
164
+ // server events that have no browser client id.
165
+ client_id: args.clientId && args.clientId.length > 0 ? args.clientId : `srv.${Date.now()}`,
166
+ events: [{ name: args.eventName, params }]
167
+ };
168
+ }
169
+ async function findConfig(payload, siteSlug, provider) {
170
+ if (!siteSlug) return void 0;
171
+ const res = await payload.find({
172
+ collection: ANALYTICS_INTEGRATIONS,
173
+ where: {
174
+ and: [
175
+ { "site.slug": { equals: siteSlug } },
176
+ { provider: { equals: provider } },
177
+ { isActive: { equals: true } }
178
+ ]
179
+ },
180
+ limit: 1,
181
+ depth: 0,
182
+ overrideAccess: true,
183
+ context: { preventMasking: true }
184
+ });
185
+ return res.docs[0];
186
+ }
187
+ async function ga4SendHandler(ctx) {
188
+ const siteSlug = ctx.workflowContext.siteSlug;
189
+ const eventName = ctx.step.event_name;
190
+ if (!eventName) return { success: false, error: "ga4-send-event requires event_name" };
191
+ const cfg = await findConfig(ctx.payload, siteSlug, "google");
192
+ const measurementId = cfg?.trackingId;
193
+ const apiSecret = cfg?.apiSecret ?? "";
194
+ if (!measurementId || !apiSecret) {
195
+ ctx.payload.logger.info(`[ga4-send-event] no active GA4 config for ${siteSlug} \u2014 skipping`);
196
+ return { success: true, data: { ga4_skipped: true } };
197
+ }
198
+ const params = resolveParams(ctx.step.field_mapping, ctx.workflowContext);
199
+ const clientId = params.client_id;
200
+ delete params.client_id;
201
+ const body = buildGa4Body({ clientId, eventName, params });
202
+ try {
203
+ const res = await fetch(
204
+ `https://www.google-analytics.com/mp/collect?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`,
205
+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) }
206
+ );
207
+ if (res.status !== 204 && !res.ok) {
208
+ const text = await res.text().catch(() => "");
209
+ return { success: false, error: `GA4 MP \u2192 ${res.status}: ${text.slice(0, 200)}` };
210
+ }
211
+ return { success: true, data: { ga4_event: eventName } };
212
+ } catch (err) {
213
+ return { success: false, error: `GA4 MP request failed: ${err instanceof Error ? err.message : String(err)}` };
214
+ }
215
+ }
216
+ var marketingActions = [{ name: "ga4-send-event", handler: ga4SendHandler }];
217
+
218
+ // src/migrations.ts
219
+ import { sqlMigration } from "opscms-sdk";
220
+ var migration = sqlMigration("analytics:20261108_100000_create_integrations", {
221
+ up: [
222
+ `DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_analytics_integrations_provider') THEN CREATE TYPE "public"."enum_analytics_integrations_provider" AS ENUM('google', 'matomo', 'plausible', 'fathom', 'umami', 'posthog', 'custom'); END IF; END $$;`,
223
+ `CREATE TABLE IF NOT EXISTS "analytics_integrations" (
224
+ "id" serial PRIMARY KEY NOT NULL,
225
+ "label" varchar NOT NULL,
226
+ "provider" "public"."enum_analytics_integrations_provider" NOT NULL,
227
+ "tracking_id" varchar,
228
+ "tag_id" varchar,
229
+ "api_secret" varchar,
230
+ "server_url" varchar,
231
+ "custom_script" varchar,
232
+ "site_id" integer NOT NULL,
233
+ "organization_id" integer NOT NULL,
234
+ "is_active" boolean DEFAULT true,
235
+ "updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
236
+ "created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
237
+ )`,
238
+ `ALTER TABLE "payload_locked_documents_rels" ADD COLUMN IF NOT EXISTS "analytics_integrations_id" integer`,
239
+ `DO $$ BEGIN ALTER TABLE "analytics_integrations" ADD CONSTRAINT "analytics_integrations_site_id_sites_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("id") ON DELETE set null ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
240
+ `DO $$ BEGIN ALTER TABLE "analytics_integrations" ADD CONSTRAINT "analytics_integrations_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE set null ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
241
+ `DO $$ BEGIN ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_analytics_integrations_fk" FOREIGN KEY ("analytics_integrations_id") REFERENCES "public"."analytics_integrations"("id") ON DELETE cascade ON UPDATE no action; EXCEPTION WHEN duplicate_object THEN NULL; END $$;`,
242
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_site_idx" ON "analytics_integrations" USING btree ("site_id")`,
243
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_organization_idx" ON "analytics_integrations" USING btree ("organization_id")`,
244
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_updated_at_idx" ON "analytics_integrations" USING btree ("updated_at")`,
245
+ `CREATE INDEX IF NOT EXISTS "analytics_integrations_created_at_idx" ON "analytics_integrations" USING btree ("created_at")`,
246
+ `CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_analytics_integrations_id_idx" ON "payload_locked_documents_rels" USING btree ("analytics_integrations_id")`
247
+ ],
248
+ down: [
249
+ `ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "analytics_integrations_id"`,
250
+ `DROP TABLE IF EXISTS "analytics_integrations" CASCADE`,
251
+ `DROP TYPE IF EXISTS "public"."enum_analytics_integrations_provider"`
252
+ ]
253
+ });
254
+
255
+ // src/index.ts
256
+ var analyticsPlugin = definePlugin({
257
+ manifest: analyticsManifest,
258
+ collections: [AnalyticsIntegrations],
259
+ workflowActions: marketingActions,
260
+ migrations: [migration]
261
+ });
262
+ export {
263
+ ANALYTICS_INTEGRATIONS,
264
+ AnalyticsIntegrations,
265
+ analyticsManifest,
266
+ analyticsPlugin,
267
+ buildGa4Body,
268
+ ga4SendHandler,
269
+ resolveParams
270
+ };
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" role="img"><rect width="96" height="96" rx="22" fill="#f59e0b"/><g transform="translate(24 24) scale(2)" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></g></svg>
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "opscms-analytics-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Per-site analytics for an OpsCMS platform: each site's own Google, Matomo, Plausible, Fathom, Umami, PostHog or custom settings, and the server-side GA4 workflow action.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.mjs"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "icon.svg",
23
+ "README.md",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean --out-dir dist",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "tsx --test 'tests/**/*.test.ts'",
30
+ "prepublishOnly": "npm run build"
31
+ },
32
+ "keywords": [
33
+ "payload",
34
+ "payloadcms",
35
+ "payload-plugin",
36
+ "opscms",
37
+ "analytics",
38
+ "ga4",
39
+ "matomo"
40
+ ],
41
+ "author": "IVarse",
42
+ "license": "MIT",
43
+ "peerDependencies": {
44
+ "opscms-sdk": "^0.1.7",
45
+ "payload": "^3.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^22.0.0",
49
+ "opscms-sdk": "file:../opscms-sdk",
50
+ "payload": "^3.0.0",
51
+ "tsup": "^8.0.0",
52
+ "tsx": "^4.0.0",
53
+ "typescript": "^5.7.0"
54
+ },
55
+ "opscms": {
56
+ "plugin": true
57
+ }
58
+ }