opscms-analytics-plugin 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +31 -2
- package/dist/index.d.mts +72 -0
- package/dist/index.d.ts +72 -0
- package/dist/index.js +337 -0
- package/dist/index.mjs +303 -0
- package/icon.svg +1 -0
- package/package.json +56 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.1
|
|
4
|
+
|
|
5
|
+
A site admin's tracking ID, Tag Manager ID and server address are checked when saved: each must have the shape a real one has, so nothing that could end a string or a tag in the inline snippet is accepted (the server address must be https, with no login in it). Empty stays allowed.
|
|
6
|
+
|
|
7
|
+
## 1.0.0
|
|
8
|
+
|
|
9
|
+
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,
|
|
10
|
+
`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
|
-
#
|
|
1
|
+
# opscms-analytics-plugin
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
/**
|
|
37
|
+
* What an analytics integration's own values may look like.
|
|
38
|
+
*
|
|
39
|
+
* A site's admin types these (the customer's own script is a separate field only the platform owner can write), and they end up inside
|
|
40
|
+
* every page of the site: as part of a script address and inside an inline snippet. So each is held to the shape a real one has, and
|
|
41
|
+
* nothing that could end a string or a tag is accepted. (The component that renders them escapes them as well; this is the first line.)
|
|
42
|
+
*/
|
|
43
|
+
/** `true`, or the sentence that tells the person what is wrong. Empty is allowed: the field is optional. */
|
|
44
|
+
declare function trackingIdProblem(value: unknown): true | string;
|
|
45
|
+
declare function tagIdProblem(value: unknown): true | string;
|
|
46
|
+
declare function serverUrlProblem(value: unknown): true | string;
|
|
47
|
+
|
|
48
|
+
/** Resolve a field_mapping of { paramName: "{{template}}" } against the workflow context. */
|
|
49
|
+
declare function resolveParams(mapping: Record<string, unknown> | null | undefined, ctx: Record<string, unknown>): Record<string, string>;
|
|
50
|
+
/** Build the GA4 Measurement Protocol request body. Exposed for unit verification. */
|
|
51
|
+
declare function buildGa4Body(args: {
|
|
52
|
+
clientId?: string;
|
|
53
|
+
eventName: string;
|
|
54
|
+
params: Record<string, string>;
|
|
55
|
+
}): {
|
|
56
|
+
client_id: string;
|
|
57
|
+
events: Array<{
|
|
58
|
+
name: string;
|
|
59
|
+
params: Record<string, unknown>;
|
|
60
|
+
}>;
|
|
61
|
+
};
|
|
62
|
+
declare function ga4SendHandler(ctx: WorkflowActionContext): Promise<WorkflowStepResult>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Per-site analytics: the `analytics-integrations` collection (each site's own Google, Matomo, Plausible, Fathom, Umami, PostHog or custom settings, with the
|
|
66
|
+
* secret encrypted), and the server-side GA4 workflow action (`ga4-send-event`) that reads them for the platform's `send_analytics_event` block.
|
|
67
|
+
*
|
|
68
|
+
* Meta's own server-side events are the Meta plugin's (`meta-conversion-event`), not this plugin's.
|
|
69
|
+
*/
|
|
70
|
+
declare const analyticsPlugin: opscms_sdk.PlatformPlugin;
|
|
71
|
+
|
|
72
|
+
export { ANALYTICS_INTEGRATIONS, AnalyticsIntegrations, analyticsManifest, analyticsPlugin, buildGa4Body, ga4SendHandler, resolveParams, serverUrlProblem, tagIdProblem, trackingIdProblem };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
/**
|
|
37
|
+
* What an analytics integration's own values may look like.
|
|
38
|
+
*
|
|
39
|
+
* A site's admin types these (the customer's own script is a separate field only the platform owner can write), and they end up inside
|
|
40
|
+
* every page of the site: as part of a script address and inside an inline snippet. So each is held to the shape a real one has, and
|
|
41
|
+
* nothing that could end a string or a tag is accepted. (The component that renders them escapes them as well; this is the first line.)
|
|
42
|
+
*/
|
|
43
|
+
/** `true`, or the sentence that tells the person what is wrong. Empty is allowed: the field is optional. */
|
|
44
|
+
declare function trackingIdProblem(value: unknown): true | string;
|
|
45
|
+
declare function tagIdProblem(value: unknown): true | string;
|
|
46
|
+
declare function serverUrlProblem(value: unknown): true | string;
|
|
47
|
+
|
|
48
|
+
/** Resolve a field_mapping of { paramName: "{{template}}" } against the workflow context. */
|
|
49
|
+
declare function resolveParams(mapping: Record<string, unknown> | null | undefined, ctx: Record<string, unknown>): Record<string, string>;
|
|
50
|
+
/** Build the GA4 Measurement Protocol request body. Exposed for unit verification. */
|
|
51
|
+
declare function buildGa4Body(args: {
|
|
52
|
+
clientId?: string;
|
|
53
|
+
eventName: string;
|
|
54
|
+
params: Record<string, string>;
|
|
55
|
+
}): {
|
|
56
|
+
client_id: string;
|
|
57
|
+
events: Array<{
|
|
58
|
+
name: string;
|
|
59
|
+
params: Record<string, unknown>;
|
|
60
|
+
}>;
|
|
61
|
+
};
|
|
62
|
+
declare function ga4SendHandler(ctx: WorkflowActionContext): Promise<WorkflowStepResult>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Per-site analytics: the `analytics-integrations` collection (each site's own Google, Matomo, Plausible, Fathom, Umami, PostHog or custom settings, with the
|
|
66
|
+
* secret encrypted), and the server-side GA4 workflow action (`ga4-send-event`) that reads them for the platform's `send_analytics_event` block.
|
|
67
|
+
*
|
|
68
|
+
* Meta's own server-side events are the Meta plugin's (`meta-conversion-event`), not this plugin's.
|
|
69
|
+
*/
|
|
70
|
+
declare const analyticsPlugin: opscms_sdk.PlatformPlugin;
|
|
71
|
+
|
|
72
|
+
export { ANALYTICS_INTEGRATIONS, AnalyticsIntegrations, analyticsManifest, analyticsPlugin, buildGa4Body, ga4SendHandler, resolveParams, serverUrlProblem, tagIdProblem, trackingIdProblem };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
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
|
+
serverUrlProblem: () => serverUrlProblem,
|
|
31
|
+
tagIdProblem: () => tagIdProblem,
|
|
32
|
+
trackingIdProblem: () => trackingIdProblem
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(index_exports);
|
|
35
|
+
var import_opscms_sdk5 = require("opscms-sdk");
|
|
36
|
+
|
|
37
|
+
// src/AnalyticsIntegrations.ts
|
|
38
|
+
var import_opscms_sdk = require("opscms-sdk");
|
|
39
|
+
|
|
40
|
+
// src/integrationValues.ts
|
|
41
|
+
var ID = /^[A-Za-z0-9._:/-]{1,100}$/;
|
|
42
|
+
var TAG = /^[A-Za-z0-9_-]{1,40}$/;
|
|
43
|
+
function trackingIdProblem(value) {
|
|
44
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
45
|
+
return typeof value === "string" && ID.test(value) ? true : "A tracking or site ID has only letters, digits and . _ : / - (for example G-ABC123, 3, or example.com).";
|
|
46
|
+
}
|
|
47
|
+
function tagIdProblem(value) {
|
|
48
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
49
|
+
return typeof value === "string" && TAG.test(value) ? true : "A Tag Manager container ID looks like GTM-ABC123.";
|
|
50
|
+
}
|
|
51
|
+
function serverUrlProblem(value) {
|
|
52
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
53
|
+
if (typeof value !== "string" || value.length > 300 || /[\s"'<>`\\]/.test(value)) return "That is not a web address.";
|
|
54
|
+
let url;
|
|
55
|
+
try {
|
|
56
|
+
url = new URL(value);
|
|
57
|
+
} catch {
|
|
58
|
+
return "That is not a web address (it should look like https://analytics.example.com/).";
|
|
59
|
+
}
|
|
60
|
+
if (url.protocol !== "https:") return "The address must start with https:// (a page served over https cannot load a script from plain http).";
|
|
61
|
+
if (url.username || url.password) return "The address cannot contain a username or password.";
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/AnalyticsIntegrations.ts
|
|
66
|
+
var ANALYTICS_INTEGRATIONS = "analytics-integrations";
|
|
67
|
+
var onlySuperAdminField = ({ req }) => req?.user?.role === "super-admin";
|
|
68
|
+
var AnalyticsIntegrations = {
|
|
69
|
+
slug: ANALYTICS_INTEGRATIONS,
|
|
70
|
+
admin: {
|
|
71
|
+
useAsTitle: "label",
|
|
72
|
+
defaultColumns: ["label", "provider", "project", "isActive", "createdAt"],
|
|
73
|
+
group: "Configuration"
|
|
74
|
+
},
|
|
75
|
+
access: {
|
|
76
|
+
read: import_opscms_sdk.access.siteScopedRead(),
|
|
77
|
+
create: import_opscms_sdk.access.siteScopedCreate,
|
|
78
|
+
update: import_opscms_sdk.access.siteScopedUpdate(),
|
|
79
|
+
delete: import_opscms_sdk.access.siteScopedDelete()
|
|
80
|
+
},
|
|
81
|
+
fields: [
|
|
82
|
+
{
|
|
83
|
+
name: "label",
|
|
84
|
+
type: "text",
|
|
85
|
+
required: true,
|
|
86
|
+
admin: { description: 'Friendly label, e.g. "GA \u2013 ivarse.com"' }
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: "provider",
|
|
90
|
+
type: "select",
|
|
91
|
+
required: true,
|
|
92
|
+
options: [
|
|
93
|
+
{ label: "Google (Analytics + Tag Manager)", value: "google" },
|
|
94
|
+
{ label: "Matomo", value: "matomo" },
|
|
95
|
+
{ label: "Plausible", value: "plausible" },
|
|
96
|
+
{ label: "Fathom", value: "fathom" },
|
|
97
|
+
{ label: "Umami", value: "umami" },
|
|
98
|
+
{ label: "PostHog", value: "posthog" },
|
|
99
|
+
{ label: "Custom", value: "custom" }
|
|
100
|
+
]
|
|
101
|
+
},
|
|
102
|
+
// ── Provider-specific settings ──────────────────────────────
|
|
103
|
+
{
|
|
104
|
+
name: "trackingId",
|
|
105
|
+
type: "text",
|
|
106
|
+
validate: (value) => trackingIdProblem(value),
|
|
107
|
+
admin: {
|
|
108
|
+
description: "Measurement / tracking ID \u2014 GA4 measurement ID (G-XXXX) for Google, or site ID for others. Leave blank if only using Tag Manager.",
|
|
109
|
+
condition: (_data, siblingData) => ["google", "matomo", "plausible", "fathom", "umami", "posthog"].includes(
|
|
110
|
+
siblingData?.provider
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
name: "tagId",
|
|
116
|
+
type: "text",
|
|
117
|
+
validate: (value) => tagIdProblem(value),
|
|
118
|
+
admin: {
|
|
119
|
+
description: "Google Tag Manager container ID (GTM-XXXX). Leave blank if not using Tag Manager.",
|
|
120
|
+
condition: (_data, siblingData) => siblingData?.provider === "google"
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
// 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
|
|
124
|
+
// ga4-send-event workflow action, which asks for it explicitly (`context.preventMasking`). Anyone else, an anonymous request to the platform's public content
|
|
125
|
+
// delivery API included, gets the mask: the field fails CLOSED.
|
|
126
|
+
(0, import_opscms_sdk.secretField)(ANALYTICS_INTEGRATIONS, "apiSecret", {
|
|
127
|
+
label: "API secret",
|
|
128
|
+
description: "Server secret: the GA4 Measurement Protocol API secret.",
|
|
129
|
+
condition: (_data, siblingData) => siblingData?.provider === "google"
|
|
130
|
+
}),
|
|
131
|
+
{
|
|
132
|
+
name: "serverUrl",
|
|
133
|
+
type: "text",
|
|
134
|
+
validate: (value) => serverUrlProblem(value),
|
|
135
|
+
admin: {
|
|
136
|
+
description: "Self-hosted instance URL (Matomo, Umami, Plausible, PostHog)",
|
|
137
|
+
condition: (_data, siblingData) => ["matomo", "plausible", "umami", "posthog"].includes(siblingData?.provider)
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
name: "customScript",
|
|
142
|
+
type: "code",
|
|
143
|
+
// Rendered raw into every page of every site by packages/ui Analytics.tsx.
|
|
144
|
+
// It cannot be sanitised — it is deliberately a script tag — so the control
|
|
145
|
+
// has to be who may write it. Any editor with access to this field could
|
|
146
|
+
// otherwise run arbitrary JavaScript on all eight brands at once, and the
|
|
147
|
+
// shared CSP allows 'unsafe-inline' so nothing downstream would stop it.
|
|
148
|
+
access: { create: onlySuperAdminField, update: onlySuperAdminField },
|
|
149
|
+
admin: {
|
|
150
|
+
language: "html",
|
|
151
|
+
description: 'Raw analytics script tag(s) for the "Custom" provider. Super-admin only: this is injected verbatim into every page.',
|
|
152
|
+
condition: (_data, siblingData) => siblingData?.provider === "custom"
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
// ── Relationships ───────────────────────────────────────────
|
|
156
|
+
{
|
|
157
|
+
name: "site",
|
|
158
|
+
type: "relationship",
|
|
159
|
+
relationTo: "sites",
|
|
160
|
+
required: true,
|
|
161
|
+
index: true,
|
|
162
|
+
admin: { description: "The site this integration applies to" },
|
|
163
|
+
// 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
|
|
164
|
+
// on every page) under another tenant's site: a cross-tenant stored-XSS path.
|
|
165
|
+
hooks: { beforeValidate: [import_opscms_sdk.tenancy.pinSite] }
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
name: "organization",
|
|
169
|
+
type: "relationship",
|
|
170
|
+
relationTo: "organizations",
|
|
171
|
+
required: true,
|
|
172
|
+
index: true,
|
|
173
|
+
admin: { readOnly: true, description: "Set from the site: a site belongs to exactly one organization." },
|
|
174
|
+
// Skipped on create (the hook sets it), so a read-only required field does not block the form.
|
|
175
|
+
validate: (value, { operation }) => operation === "create" || value != null ? true : "This field is required.",
|
|
176
|
+
hooks: { beforeValidate: [import_opscms_sdk.tenancy.pinOrganization] }
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: "isActive",
|
|
180
|
+
type: "checkbox",
|
|
181
|
+
defaultValue: true
|
|
182
|
+
}
|
|
183
|
+
],
|
|
184
|
+
timestamps: true
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// src/manifest.ts
|
|
188
|
+
var import_opscms_sdk2 = require("opscms-sdk");
|
|
189
|
+
var analyticsManifest = (0, import_opscms_sdk2.definePluginManifest)({
|
|
190
|
+
key: "analytics",
|
|
191
|
+
name: "Analytics & Insights",
|
|
192
|
+
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.)",
|
|
193
|
+
category: "analytics",
|
|
194
|
+
icon: "icon.svg",
|
|
195
|
+
releases: [
|
|
196
|
+
{
|
|
197
|
+
version: "1.0.0",
|
|
198
|
+
date: "2026-11-05",
|
|
199
|
+
notes: [
|
|
200
|
+
"Packaged as a plugin: per-site analytics settings (credentials encrypted) and the server-side GA4 workflow action.",
|
|
201
|
+
"Part of the CMS since 2026-05-28."
|
|
202
|
+
]
|
|
203
|
+
}
|
|
204
|
+
]
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// src/marketingActions.ts
|
|
208
|
+
var import_opscms_sdk3 = require("opscms-sdk");
|
|
209
|
+
var HTTP_TIMEOUT_MS = 8e3;
|
|
210
|
+
function resolveParams(mapping, ctx) {
|
|
211
|
+
const out = {};
|
|
212
|
+
for (const [key, tpl] of Object.entries(mapping ?? {})) {
|
|
213
|
+
if (typeof tpl === "string") {
|
|
214
|
+
const resolved = (0, import_opscms_sdk3.platform)().notifications.renderTemplate(tpl, ctx);
|
|
215
|
+
if (resolved !== void 0 && resolved !== null && resolved !== "") out[key] = String(resolved);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
function buildGa4Body(args) {
|
|
221
|
+
const { value, currency, ...rest } = args.params;
|
|
222
|
+
const params = { ...rest };
|
|
223
|
+
if (value !== void 0) params.value = Number(value);
|
|
224
|
+
if (currency) params.currency = currency;
|
|
225
|
+
return {
|
|
226
|
+
// A client_id is required by MP; fall back to a server-generated one for pure
|
|
227
|
+
// server events that have no browser client id.
|
|
228
|
+
client_id: args.clientId && args.clientId.length > 0 ? args.clientId : `srv.${Date.now()}`,
|
|
229
|
+
events: [{ name: args.eventName, params }]
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
async function findConfig(payload, siteSlug, provider) {
|
|
233
|
+
if (!siteSlug) return void 0;
|
|
234
|
+
const res = await payload.find({
|
|
235
|
+
collection: ANALYTICS_INTEGRATIONS,
|
|
236
|
+
where: {
|
|
237
|
+
and: [
|
|
238
|
+
{ "site.slug": { equals: siteSlug } },
|
|
239
|
+
{ provider: { equals: provider } },
|
|
240
|
+
{ isActive: { equals: true } }
|
|
241
|
+
]
|
|
242
|
+
},
|
|
243
|
+
limit: 1,
|
|
244
|
+
depth: 0,
|
|
245
|
+
overrideAccess: true,
|
|
246
|
+
context: { preventMasking: true }
|
|
247
|
+
});
|
|
248
|
+
return res.docs[0];
|
|
249
|
+
}
|
|
250
|
+
async function ga4SendHandler(ctx) {
|
|
251
|
+
const siteSlug = ctx.workflowContext.siteSlug;
|
|
252
|
+
const eventName = ctx.step.event_name;
|
|
253
|
+
if (!eventName) return { success: false, error: "ga4-send-event requires event_name" };
|
|
254
|
+
const cfg = await findConfig(ctx.payload, siteSlug, "google");
|
|
255
|
+
const measurementId = cfg?.trackingId;
|
|
256
|
+
const apiSecret = cfg?.apiSecret ?? "";
|
|
257
|
+
if (!measurementId || !apiSecret) {
|
|
258
|
+
ctx.payload.logger.info(`[ga4-send-event] no active GA4 config for ${siteSlug} \u2014 skipping`);
|
|
259
|
+
return { success: true, data: { ga4_skipped: true } };
|
|
260
|
+
}
|
|
261
|
+
const params = resolveParams(ctx.step.field_mapping, ctx.workflowContext);
|
|
262
|
+
const clientId = params.client_id;
|
|
263
|
+
delete params.client_id;
|
|
264
|
+
const body = buildGa4Body({ clientId, eventName, params });
|
|
265
|
+
try {
|
|
266
|
+
const res = await fetch(
|
|
267
|
+
`https://www.google-analytics.com/mp/collect?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`,
|
|
268
|
+
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) }
|
|
269
|
+
);
|
|
270
|
+
if (res.status !== 204 && !res.ok) {
|
|
271
|
+
const text = await res.text().catch(() => "");
|
|
272
|
+
return { success: false, error: `GA4 MP \u2192 ${res.status}: ${text.slice(0, 200)}` };
|
|
273
|
+
}
|
|
274
|
+
return { success: true, data: { ga4_event: eventName } };
|
|
275
|
+
} catch (err) {
|
|
276
|
+
return { success: false, error: `GA4 MP request failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
var marketingActions = [{ name: "ga4-send-event", handler: ga4SendHandler }];
|
|
280
|
+
|
|
281
|
+
// src/migrations.ts
|
|
282
|
+
var import_opscms_sdk4 = require("opscms-sdk");
|
|
283
|
+
var migration = (0, import_opscms_sdk4.sqlMigration)("analytics:20261108_100000_create_integrations", {
|
|
284
|
+
up: [
|
|
285
|
+
`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 $$;`,
|
|
286
|
+
`CREATE TABLE IF NOT EXISTS "analytics_integrations" (
|
|
287
|
+
"id" serial PRIMARY KEY NOT NULL,
|
|
288
|
+
"label" varchar NOT NULL,
|
|
289
|
+
"provider" "public"."enum_analytics_integrations_provider" NOT NULL,
|
|
290
|
+
"tracking_id" varchar,
|
|
291
|
+
"tag_id" varchar,
|
|
292
|
+
"api_secret" varchar,
|
|
293
|
+
"server_url" varchar,
|
|
294
|
+
"custom_script" varchar,
|
|
295
|
+
"site_id" integer NOT NULL,
|
|
296
|
+
"organization_id" integer NOT NULL,
|
|
297
|
+
"is_active" boolean DEFAULT true,
|
|
298
|
+
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
|
299
|
+
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
|
300
|
+
)`,
|
|
301
|
+
`ALTER TABLE "payload_locked_documents_rels" ADD COLUMN IF NOT EXISTS "analytics_integrations_id" integer`,
|
|
302
|
+
`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 $$;`,
|
|
303
|
+
`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 $$;`,
|
|
304
|
+
`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 $$;`,
|
|
305
|
+
`CREATE INDEX IF NOT EXISTS "analytics_integrations_site_idx" ON "analytics_integrations" USING btree ("site_id")`,
|
|
306
|
+
`CREATE INDEX IF NOT EXISTS "analytics_integrations_organization_idx" ON "analytics_integrations" USING btree ("organization_id")`,
|
|
307
|
+
`CREATE INDEX IF NOT EXISTS "analytics_integrations_updated_at_idx" ON "analytics_integrations" USING btree ("updated_at")`,
|
|
308
|
+
`CREATE INDEX IF NOT EXISTS "analytics_integrations_created_at_idx" ON "analytics_integrations" USING btree ("created_at")`,
|
|
309
|
+
`CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_analytics_integrations_id_idx" ON "payload_locked_documents_rels" USING btree ("analytics_integrations_id")`
|
|
310
|
+
],
|
|
311
|
+
down: [
|
|
312
|
+
`ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "analytics_integrations_id"`,
|
|
313
|
+
`DROP TABLE IF EXISTS "analytics_integrations" CASCADE`,
|
|
314
|
+
`DROP TYPE IF EXISTS "public"."enum_analytics_integrations_provider"`
|
|
315
|
+
]
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// src/index.ts
|
|
319
|
+
var analyticsPlugin = (0, import_opscms_sdk5.definePlugin)({
|
|
320
|
+
manifest: analyticsManifest,
|
|
321
|
+
collections: [AnalyticsIntegrations],
|
|
322
|
+
workflowActions: marketingActions,
|
|
323
|
+
migrations: [migration]
|
|
324
|
+
});
|
|
325
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
326
|
+
0 && (module.exports = {
|
|
327
|
+
ANALYTICS_INTEGRATIONS,
|
|
328
|
+
AnalyticsIntegrations,
|
|
329
|
+
analyticsManifest,
|
|
330
|
+
analyticsPlugin,
|
|
331
|
+
buildGa4Body,
|
|
332
|
+
ga4SendHandler,
|
|
333
|
+
resolveParams,
|
|
334
|
+
serverUrlProblem,
|
|
335
|
+
tagIdProblem,
|
|
336
|
+
trackingIdProblem
|
|
337
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { definePlugin } from "opscms-sdk";
|
|
3
|
+
|
|
4
|
+
// src/AnalyticsIntegrations.ts
|
|
5
|
+
import { access, secretField, tenancy } from "opscms-sdk";
|
|
6
|
+
|
|
7
|
+
// src/integrationValues.ts
|
|
8
|
+
var ID = /^[A-Za-z0-9._:/-]{1,100}$/;
|
|
9
|
+
var TAG = /^[A-Za-z0-9_-]{1,40}$/;
|
|
10
|
+
function trackingIdProblem(value) {
|
|
11
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
12
|
+
return typeof value === "string" && ID.test(value) ? true : "A tracking or site ID has only letters, digits and . _ : / - (for example G-ABC123, 3, or example.com).";
|
|
13
|
+
}
|
|
14
|
+
function tagIdProblem(value) {
|
|
15
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
16
|
+
return typeof value === "string" && TAG.test(value) ? true : "A Tag Manager container ID looks like GTM-ABC123.";
|
|
17
|
+
}
|
|
18
|
+
function serverUrlProblem(value) {
|
|
19
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
20
|
+
if (typeof value !== "string" || value.length > 300 || /[\s"'<>`\\]/.test(value)) return "That is not a web address.";
|
|
21
|
+
let url;
|
|
22
|
+
try {
|
|
23
|
+
url = new URL(value);
|
|
24
|
+
} catch {
|
|
25
|
+
return "That is not a web address (it should look like https://analytics.example.com/).";
|
|
26
|
+
}
|
|
27
|
+
if (url.protocol !== "https:") return "The address must start with https:// (a page served over https cannot load a script from plain http).";
|
|
28
|
+
if (url.username || url.password) return "The address cannot contain a username or password.";
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/AnalyticsIntegrations.ts
|
|
33
|
+
var ANALYTICS_INTEGRATIONS = "analytics-integrations";
|
|
34
|
+
var onlySuperAdminField = ({ req }) => req?.user?.role === "super-admin";
|
|
35
|
+
var AnalyticsIntegrations = {
|
|
36
|
+
slug: ANALYTICS_INTEGRATIONS,
|
|
37
|
+
admin: {
|
|
38
|
+
useAsTitle: "label",
|
|
39
|
+
defaultColumns: ["label", "provider", "project", "isActive", "createdAt"],
|
|
40
|
+
group: "Configuration"
|
|
41
|
+
},
|
|
42
|
+
access: {
|
|
43
|
+
read: access.siteScopedRead(),
|
|
44
|
+
create: access.siteScopedCreate,
|
|
45
|
+
update: access.siteScopedUpdate(),
|
|
46
|
+
delete: access.siteScopedDelete()
|
|
47
|
+
},
|
|
48
|
+
fields: [
|
|
49
|
+
{
|
|
50
|
+
name: "label",
|
|
51
|
+
type: "text",
|
|
52
|
+
required: true,
|
|
53
|
+
admin: { description: 'Friendly label, e.g. "GA \u2013 ivarse.com"' }
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "provider",
|
|
57
|
+
type: "select",
|
|
58
|
+
required: true,
|
|
59
|
+
options: [
|
|
60
|
+
{ label: "Google (Analytics + Tag Manager)", value: "google" },
|
|
61
|
+
{ label: "Matomo", value: "matomo" },
|
|
62
|
+
{ label: "Plausible", value: "plausible" },
|
|
63
|
+
{ label: "Fathom", value: "fathom" },
|
|
64
|
+
{ label: "Umami", value: "umami" },
|
|
65
|
+
{ label: "PostHog", value: "posthog" },
|
|
66
|
+
{ label: "Custom", value: "custom" }
|
|
67
|
+
]
|
|
68
|
+
},
|
|
69
|
+
// ── Provider-specific settings ──────────────────────────────
|
|
70
|
+
{
|
|
71
|
+
name: "trackingId",
|
|
72
|
+
type: "text",
|
|
73
|
+
validate: (value) => trackingIdProblem(value),
|
|
74
|
+
admin: {
|
|
75
|
+
description: "Measurement / tracking ID \u2014 GA4 measurement ID (G-XXXX) for Google, or site ID for others. Leave blank if only using Tag Manager.",
|
|
76
|
+
condition: (_data, siblingData) => ["google", "matomo", "plausible", "fathom", "umami", "posthog"].includes(
|
|
77
|
+
siblingData?.provider
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: "tagId",
|
|
83
|
+
type: "text",
|
|
84
|
+
validate: (value) => tagIdProblem(value),
|
|
85
|
+
admin: {
|
|
86
|
+
description: "Google Tag Manager container ID (GTM-XXXX). Leave blank if not using Tag Manager.",
|
|
87
|
+
condition: (_data, siblingData) => siblingData?.provider === "google"
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
// 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
|
|
91
|
+
// ga4-send-event workflow action, which asks for it explicitly (`context.preventMasking`). Anyone else, an anonymous request to the platform's public content
|
|
92
|
+
// delivery API included, gets the mask: the field fails CLOSED.
|
|
93
|
+
secretField(ANALYTICS_INTEGRATIONS, "apiSecret", {
|
|
94
|
+
label: "API secret",
|
|
95
|
+
description: "Server secret: the GA4 Measurement Protocol API secret.",
|
|
96
|
+
condition: (_data, siblingData) => siblingData?.provider === "google"
|
|
97
|
+
}),
|
|
98
|
+
{
|
|
99
|
+
name: "serverUrl",
|
|
100
|
+
type: "text",
|
|
101
|
+
validate: (value) => serverUrlProblem(value),
|
|
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: [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: [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
|
+
import { definePluginManifest } from "opscms-sdk";
|
|
156
|
+
var analyticsManifest = 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
|
+
import { platform } from "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 = 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
|
+
import { sqlMigration } from "opscms-sdk";
|
|
250
|
+
var migration = 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 = definePlugin({
|
|
287
|
+
manifest: analyticsManifest,
|
|
288
|
+
collections: [AnalyticsIntegrations],
|
|
289
|
+
workflowActions: marketingActions,
|
|
290
|
+
migrations: [migration]
|
|
291
|
+
});
|
|
292
|
+
export {
|
|
293
|
+
ANALYTICS_INTEGRATIONS,
|
|
294
|
+
AnalyticsIntegrations,
|
|
295
|
+
analyticsManifest,
|
|
296
|
+
analyticsPlugin,
|
|
297
|
+
buildGa4Body,
|
|
298
|
+
ga4SendHandler,
|
|
299
|
+
resolveParams,
|
|
300
|
+
serverUrlProblem,
|
|
301
|
+
tagIdProblem,
|
|
302
|
+
trackingIdProblem
|
|
303
|
+
};
|
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": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
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
|
+
}
|