@adport/provider-matomo 0.0.0-stage → 0.15.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yannick Westermann
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @adport/provider-matomo
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
+ Connect a Matomo Cloud or self-hosted site to Adport with a view token. The package reads aggregate acquisition reports and configured goals through `analytics_acquisition_report` and `analytics_goals`. Configure `MATOMO_URL` and `MATOMO_TOKEN_AUTH` or run `adport connect matomo`.
4
+
5
+ See the [connection guide](https://github.com/ynnickw/adport/blob/main/docs/providers/matomo.md) and [shared reporting contract](https://github.com/ynnickw/adport/blob/main/docs/providers/website-analytics.md).
@@ -0,0 +1,73 @@
1
+ import { AdProvider, NormalizedQuery, Report, WriteOperation, WritePreview, WriteResult, Account, AcquisitionQuery, AcquisitionReport, CredentialStore, ProviderModule } from '@adport/core';
2
+ export { matomoBaseUrl, normalizeMatomoUrl } from '@adport/core';
3
+
4
+ type MatomoFetch = (url: string, init: {
5
+ method: 'POST';
6
+ redirect: 'error';
7
+ signal: AbortSignal;
8
+ headers: Record<string, string>;
9
+ body: URLSearchParams;
10
+ }) => Promise<Pick<Response, 'ok' | 'status' | 'text'>>;
11
+ interface MatomoCredentials {
12
+ /** Instance base URL, e.g. https://example.matomo.cloud or https://analytics.example.com/matomo. */
13
+ url: string;
14
+ /** Personal auth token of a user with view access to the sites. */
15
+ tokenAuth: string;
16
+ }
17
+ interface MatomoBearerCredentials {
18
+ url: string;
19
+ accessToken(): Promise<string>;
20
+ }
21
+ /** Documented read methods only. Every other Matomo API method is refused before any request. */
22
+ declare const MATOMO_READ_METHODS: Set<string>;
23
+ /**
24
+ * Matomo Reporting API over POST so token_auth never appears in a URL. Matomo
25
+ * answers most failures with HTTP 200 and {"result":"error"}; messages are
26
+ * classified but never echoed, since they can contain instance details.
27
+ */
28
+ declare class MatomoClient {
29
+ private readonly credentials;
30
+ private readonly fetchImpl;
31
+ readonly baseUrl: string;
32
+ constructor(credentials: MatomoCredentials | MatomoBearerCredentials, fetchImpl?: MatomoFetch);
33
+ call(method: string, params?: Record<string, string>): Promise<unknown>;
34
+ }
35
+
36
+ declare function matomoSiteId(value: unknown): string;
37
+ interface MatomoSite {
38
+ id: string;
39
+ name: string;
40
+ timezone?: string;
41
+ currency?: string;
42
+ ecommerce: boolean;
43
+ }
44
+ declare class MatomoProvider implements AdProvider {
45
+ private readonly client;
46
+ readonly id = "matomo";
47
+ get acquisitionAnalytics(): this;
48
+ constructor(client: MatomoClient);
49
+ capabilities(): {
50
+ serverDryRun: boolean;
51
+ reporting: boolean;
52
+ };
53
+ report(_query: NormalizedQuery): Promise<Report>;
54
+ previewWrite(_op: WriteOperation): Promise<WritePreview>;
55
+ applyWrite(_op: WriteOperation): Promise<WriteResult>;
56
+ listAccounts(): Promise<Account[]>;
57
+ private site;
58
+ private configuredGoals;
59
+ listGoals(accountId: string): Promise<{
60
+ id: string;
61
+ name: string;
62
+ counting_method?: string | undefined;
63
+ }[]>;
64
+ acquisitionReport(query: AcquisitionQuery): Promise<AcquisitionReport>;
65
+ }
66
+
67
+ /** Stored data uses { url, token_auth }; both values are required. */
68
+ declare function matomoCredentialsFromData(data: Record<string, string> | undefined): MatomoCredentials | undefined;
69
+ declare function matomoEnvironmentData(): Record<string, string>;
70
+ declare function resolveMatomoCredentials(store: CredentialStore): Promise<MatomoCredentials | undefined>;
71
+ declare function createMatomoModule(store: CredentialStore): Promise<ProviderModule | undefined>;
72
+
73
+ export { MATOMO_READ_METHODS, type MatomoBearerCredentials, MatomoClient, type MatomoCredentials, MatomoProvider, type MatomoSite, createMatomoModule, matomoCredentialsFromData, matomoEnvironmentData, matomoSiteId, resolveMatomoCredentials };
package/dist/index.js ADDED
@@ -0,0 +1,380 @@
1
+ // src/index.ts
2
+ import { normalizeMatomoUrl as normalizeMatomoUrl2 } from "@adport/core";
3
+
4
+ // src/client.ts
5
+ import { AdportError, normalizeMatomoUrl } from "@adport/core";
6
+ var MATOMO_READ_METHODS = /* @__PURE__ */ new Set([
7
+ "API.getReportMetadata",
8
+ "SitesManager.getSitesWithAtLeastViewAccess",
9
+ "SitesManager.getSiteFromId",
10
+ "Goals.getGoals",
11
+ "Referrers.getReferrerType",
12
+ "Referrers.getCampaigns",
13
+ "MarketingCampaignsReporting.getName",
14
+ "MarketingCampaignsReporting.getSource",
15
+ "MarketingCampaignsReporting.getMedium",
16
+ "MarketingCampaignsReporting.getSourceMedium",
17
+ "Actions.getEntryPageUrls"
18
+ ]);
19
+ var RESERVED = /* @__PURE__ */ new Set(["module", "method", "format", "token_auth", "force_api_session"]);
20
+ var MatomoClient = class {
21
+ constructor(credentials, fetchImpl = fetch) {
22
+ this.credentials = credentials;
23
+ this.fetchImpl = fetchImpl;
24
+ this.baseUrl = normalizeMatomoUrl(credentials.url);
25
+ if ("tokenAuth" in credentials && !credentials.tokenAuth.trim()) throw new AdportError("INVALID_INPUT", "matomo: token_auth is empty");
26
+ }
27
+ credentials;
28
+ fetchImpl;
29
+ baseUrl;
30
+ async call(method, params = {}) {
31
+ if (!MATOMO_READ_METHODS.has(method)) throw new AdportError("INVALID_INPUT", "Unsupported Matomo read method.");
32
+ if (Object.keys(params).some((key) => RESERVED.has(key))) throw new AdportError("INVALID_INPUT", "Reserved Matomo request parameter.");
33
+ const body = new URLSearchParams({ ...params, module: "API", method, format: "JSON" });
34
+ const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
35
+ if ("accessToken" in this.credentials) headers.authorization = "Bearer " + await this.credentials.accessToken();
36
+ else body.set("token_auth", this.credentials.tokenAuth.trim());
37
+ let response;
38
+ try {
39
+ response = await this.fetchImpl(`${this.baseUrl}/index.php`, {
40
+ method: "POST",
41
+ redirect: "error",
42
+ signal: AbortSignal.timeout(3e4),
43
+ headers,
44
+ body
45
+ });
46
+ } catch {
47
+ throw new AdportError("PROVIDER_ERROR", "Matomo could not be reached (network error, redirect or timeout). Check MATOMO_URL.");
48
+ }
49
+ if (response.status === 401) throw new AdportError("NOT_CONNECTED", "Matomo rejected the auth token. Reconnect Matomo to renew access.");
50
+ if (!response.ok) throw new AdportError("PROVIDER_ERROR", `Matomo read failed (HTTP ${response.status}).`, { status: response.status });
51
+ let data;
52
+ try {
53
+ data = JSON.parse(await response.text());
54
+ } catch {
55
+ throw new AdportError("PROVIDER_ERROR", "Matomo returned a non-JSON response. Check that MATOMO_URL points to the Matomo instance, not a login page or proxy.");
56
+ }
57
+ if (data && typeof data === "object" && !Array.isArray(data) && data.result === "error") {
58
+ throw classify(String(data.message ?? ""), method);
59
+ }
60
+ return data;
61
+ }
62
+ };
63
+ function classify(message, method) {
64
+ const authFailure = /\b(?:unable to authenticate|authentication (?:failed|required)|not logged in|(?:must|please|need to) (?:log in|login))\b/i;
65
+ const badToken = /\btoken_auth\b.{0,60}\b(?:invalid|not valid|expired|missing)|\b(?:invalid|expired|missing) (?:authentication token|token_auth)\b/i;
66
+ if (authFailure.test(message) || badToken.test(message)) {
67
+ return new AdportError("NOT_CONNECTED", "Matomo rejected the auth token. Reconnect Matomo to renew access.", { reason: "auth" });
68
+ }
69
+ if (/segment/i.test(message)) return new AdportError("PROVIDER_ERROR", "Matomo rejected the segment. This site must support aggregate entry-page segmentation to group by landing page.", { reason: "segment" });
70
+ if (/access|permission|not allowed/i.test(message)) {
71
+ return new AdportError("PROVIDER_ERROR", "Matomo denied access: the token is invalid or its user lacks view access to this site.", { reason: "access_denied" });
72
+ }
73
+ if (/date|period/i.test(message)) return new AdportError("PROVIDER_ERROR", "Matomo rejected the date or period.", { reason: "date" });
74
+ return new AdportError("PROVIDER_ERROR", `Matomo returned an error for ${method}. Check the site ID and parameters.`, { reason: "provider" });
75
+ }
76
+
77
+ // src/provider.ts
78
+ import {
79
+ AdportError as AdportError3
80
+ } from "@adport/core";
81
+
82
+ // src/acquisition.ts
83
+ import { AdportError as AdportError2 } from "@adport/core";
84
+ var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
85
+ function records(raw) {
86
+ const list = Array.isArray(raw) ? raw : object(raw) ? Object.values(raw) : null;
87
+ if (!list || !list.every(object)) throw new AdportError2("PROVIDER_ERROR", "Unexpected Matomo report shape.");
88
+ return list;
89
+ }
90
+ var maxRows = 1e4;
91
+ function table(raw) {
92
+ const rows = records(raw);
93
+ if (rows.length > maxRows) throw new AdportError2("PROVIDER_ERROR", "This Matomo archive exceeds the report limit. Choose a shorter date range.");
94
+ return rows;
95
+ }
96
+ var summary = (r) => r.label === "Others" || r.label === "-1" || Boolean(Number(r.is_summary));
97
+ var numeric = (v) => (typeof v === "number" || typeof v === "string" && v.trim()) && Number.isFinite(Number(v)) ? Number(v) : null;
98
+ function measures(r, site, ids) {
99
+ const goals = object(r.goals) ? r.goals : {};
100
+ const goalMetric = (id, field) => {
101
+ const goal = goals["idgoal=" + id];
102
+ return goal === void 0 ? 0 : object(goal) ? numeric(goal[field]) : null;
103
+ };
104
+ const m = {
105
+ sessions: numeric(r.nb_visits),
106
+ conversions: numeric(r.nb_conversions ?? (Object.keys(goals).length ? void 0 : 0)),
107
+ revenue: site.ecommerce ? goalMetric("ecommerceOrder", "revenue") : numeric(r.revenue ?? (Object.keys(goals).length ? void 0 : 0))
108
+ };
109
+ for (const id of ids) m["goal:" + id] = goalMetric(id, "nb_conversions");
110
+ return m;
111
+ }
112
+ function combine(a, b, sign = 1) {
113
+ const result = { ...a };
114
+ for (const key of Object.keys(a)) {
115
+ const x = a[key], y = b[key];
116
+ result[key] = x == null || y == null ? null : x + sign * y;
117
+ }
118
+ return result;
119
+ }
120
+ function hasData(m) {
121
+ return Object.values(m).some((x) => x === null || Math.abs(x) > 1e-6);
122
+ }
123
+ function residual(total, used, notes) {
124
+ const diff = combine(total, used, -1);
125
+ for (const [key, value] of Object.entries(diff)) {
126
+ if (value !== null && Math.abs(value) < 1e-6) diff[key] = 0;
127
+ else if (key !== "revenue" && value !== null && value < 0) {
128
+ diff[key] = null;
129
+ notes.add("Matomo archives disagree on a subtotal. An unreconciled measure is unavailable.");
130
+ }
131
+ }
132
+ return diff;
133
+ }
134
+ function row(dims, m, ids) {
135
+ const counts = ids.map((id) => m["goal:" + id] ?? null);
136
+ return {
137
+ dimensions: dims,
138
+ metrics: {
139
+ sessions: m.sessions,
140
+ revenue: m.revenue,
141
+ conversions: ids.length ? counts.some((v) => v === null) ? null : counts.reduce((a, b) => a + b, 0) : m.conversions
142
+ },
143
+ ...ids.length ? { goal_counts: Object.fromEntries(ids.map((id, i) => [id, counts[i] ?? null])) } : {}
144
+ };
145
+ }
146
+ async function groups(client, params, site, plugin, ids, notes) {
147
+ const read = async (method, options = {}) => table(await client.call(method, { ...params, ...options }));
148
+ const [channels, names, pairs, sources, media] = await Promise.all([
149
+ read("Referrers.getReferrerType"),
150
+ read(plugin ? "MarketingCampaignsReporting.getName" : "Referrers.getCampaigns"),
151
+ plugin ? read("MarketingCampaignsReporting.getSourceMedium", { expanded: "1" }) : [],
152
+ plugin ? read("MarketingCampaignsReporting.getSource") : [],
153
+ plugin ? read("MarketingCampaignsReporting.getMedium") : []
154
+ ]);
155
+ const zero = measures({ nb_visits: 0 }, site, ids);
156
+ const measuresFor = (r) => measures(r, site, ids);
157
+ let siteTotal = zero, namedTotal = zero;
158
+ for (const channel of channels) siteTotal = combine(siteTotal, measuresFor(channel));
159
+ const namedChildren = /* @__PURE__ */ new Map(), rows = [];
160
+ const sourceLabels = new Set(sources.map((r) => r.label)), mediumLabels = new Set(media.map((r) => r.label));
161
+ const archivedLabels = sources.some(summary) || media.some(summary);
162
+ for (const pair of pairs) {
163
+ if (summary(pair)) continue;
164
+ const label = String(pair.label), candidates = [];
165
+ if (sourceLabels.has(label)) candidates.push([label, null]);
166
+ if (mediumLabels.has(label)) candidates.push([null, label]);
167
+ for (let pos = label.indexOf(" - "); pos >= 0; pos = label.indexOf(" - ", pos + 1)) {
168
+ const source2 = label.slice(0, pos), medium2 = label.slice(pos + 3);
169
+ if (sourceLabels.has(source2) && mediumLabels.has(medium2)) candidates.push([source2, medium2]);
170
+ }
171
+ if (candidates.length !== 1 || archivedLabels) {
172
+ notes.add("Matomo returned an ambiguous or archived source/medium label. Its traffic stays in the unresolved dimensions.");
173
+ continue;
174
+ }
175
+ const [source, medium] = candidates[0];
176
+ let children = zero;
177
+ const parent = measuresFor(pair);
178
+ for (const child of table(pair.subtable ?? [])) {
179
+ if (summary(child) || typeof child.label !== "string" || !child.label) continue;
180
+ const m = measuresFor(child);
181
+ children = combine(children, m);
182
+ namedChildren.set(child.label, combine(namedChildren.get(child.label) ?? zero, m));
183
+ rows.push(row({ source, medium, campaign: child.label }, m, ids));
184
+ }
185
+ const remainder = residual(parent, children, notes);
186
+ if (hasData(remainder)) rows.push(row({ source, medium, campaign: null }, remainder, ids));
187
+ namedTotal = combine(namedTotal, parent);
188
+ }
189
+ for (const name of names) {
190
+ if (summary(name) || typeof name.label !== "string" || !name.label) continue;
191
+ const m = residual(measuresFor(name), namedChildren.get(name.label) ?? zero, notes);
192
+ if (hasData(m)) rows.push(row({ source: null, medium: null, campaign: name.label }, m, ids));
193
+ namedTotal = combine(namedTotal, m);
194
+ }
195
+ const rest = residual(siteTotal, namedTotal, notes);
196
+ if (hasData(rest)) rows.push(row({ source: null, medium: null, campaign: null }, rest, ids));
197
+ return { rows, sessions: siteTotal.sessions };
198
+ }
199
+ async function landingPages(client, params, notes) {
200
+ const entries = table(await client.call("Actions.getEntryPageUrls", { ...params, flat: "1", showColumns: "label,url,entry_nb_visits" }));
201
+ const paths = /* @__PURE__ */ new Map();
202
+ for (const entry of entries) {
203
+ if (summary(entry) || typeof entry.url !== "string") {
204
+ notes.add("Matomo omitted exact URLs for some archived entry pages.");
205
+ continue;
206
+ }
207
+ const url = new URL(entry.url);
208
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) continue;
209
+ const path = url.origin + url.pathname;
210
+ const page = paths.get(path) ?? { path, urls: /* @__PURE__ */ new Set(), visits: 0 };
211
+ page.urls.add(entry.url);
212
+ page.visits += numeric(entry.entry_nb_visits) ?? 0;
213
+ paths.set(path, page);
214
+ }
215
+ return [...paths.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
216
+ }
217
+ async function readAcquisition(client, site, q) {
218
+ const cursor = q.cursor ?? "0.0";
219
+ if (!/^\d{1,6}\.\d{1,7}$/.test(cursor)) throw new AdportError2("INVALID_INPUT", "Invalid Matomo report cursor.");
220
+ const [bucket, offset] = cursor.split(".").map(Number);
221
+ if (!q.landing_page && bucket !== 0) throw new AdportError2("INVALID_INPUT", "This cursor belongs to a landing-page report.");
222
+ const params = {
223
+ idSite: site.id,
224
+ period: q.start_date === q.end_date ? "day" : "range",
225
+ date: q.start_date === q.end_date ? q.start_date : q.start_date + "," + q.end_date,
226
+ filter_limit: String(maxRows + 1),
227
+ filter_limit_subtable: String(maxRows + 1),
228
+ format_metrics: "0",
229
+ language: "en"
230
+ };
231
+ const metadata = records(await client.call("API.getReportMetadata", { idSite: site.id, idSites: site.id, apiModule: "MarketingCampaignsReporting", hideMetricsDoc: "1" }));
232
+ const plugin = metadata.some((r) => r.module === "MarketingCampaignsReporting" && r.action === "getSourceMedium");
233
+ const notes = /* @__PURE__ */ new Set();
234
+ if (!plugin) notes.add("This site lacks the Marketing Campaigns Reporting source/medium archive. Campaign names are available; source and medium are unavailable.");
235
+ const pages = q.landing_page ? await landingPages(client, params, notes) : void 0;
236
+ const page = pages?.[bucket];
237
+ const rows = [];
238
+ let next;
239
+ if (!pages || page) {
240
+ const segment = page ? [...page.urls].map((url) => "entryPageUrl==" + encodeURIComponent(url)).join(",") : void 0;
241
+ const result = await groups(client, { ...params, ...segment ? { segment } : {} }, site, plugin, q.goal_ids ?? [], notes);
242
+ if (page && result.sessions !== page.visits) throw new AdportError2("PROVIDER_ERROR", "Matomo has no matching segmented archive for this entry page. Enable read-time segment archiving or run the report without landing_page.");
243
+ const sorted = result.rows.sort((a, b) => {
244
+ const x = JSON.stringify(a.dimensions), y = JSON.stringify(b.dimensions);
245
+ return x < y ? -1 : x > y ? 1 : 0;
246
+ });
247
+ rows.push(...sorted.slice(offset, offset + q.limit));
248
+ if (page) for (const r of rows) r.dimensions.landing_page = page.path;
249
+ if (offset + rows.length < sorted.length) next = `${bucket}.${offset + rows.length}`;
250
+ else if (pages && bucket + 1 < pages.length) next = `${bucket + 1}.0`;
251
+ }
252
+ return {
253
+ rows,
254
+ date_range: { start: q.start_date, end: q.end_date, timezone: site.timezone ?? null },
255
+ currency: site.currency ?? null,
256
+ attribution: "Matomo archived campaign parameters and native conversion attribution. Null dimensions include untagged or unresolved traffic.",
257
+ revenue_basis: site.ecommerce ? "Recorded ecommerce order revenue in site currency, across all goals." : "Recorded converted goal revenue in site currency, across all goals.",
258
+ notes: [...notes],
259
+ ...next ? { next_cursor: next } : {}
260
+ };
261
+ }
262
+
263
+ // src/provider.ts
264
+ function matomoSiteId(value) {
265
+ if (typeof value !== "string" && typeof value !== "number" || !/^[1-9]\d{0,9}$/.test(String(value)))
266
+ throw new AdportError3("INVALID_INPUT", "Matomo requires a positive numeric site ID.");
267
+ return String(value);
268
+ }
269
+ function returnedSiteId(value) {
270
+ try {
271
+ return matomoSiteId(value);
272
+ } catch {
273
+ throw new AdportError3("PROVIDER_ERROR", "Matomo returned an invalid site ID.");
274
+ }
275
+ }
276
+ var siteInfo = (raw) => ({
277
+ id: returnedSiteId(raw.idsite),
278
+ name: String(raw.name ?? raw.idsite),
279
+ ...typeof raw.timezone === "string" ? { timezone: raw.timezone } : {},
280
+ ...typeof raw.currency === "string" ? { currency: raw.currency } : {},
281
+ ecommerce: Number(raw.ecommerce) === 1
282
+ });
283
+ var MatomoProvider = class {
284
+ constructor(client) {
285
+ this.client = client;
286
+ }
287
+ client;
288
+ id = "matomo";
289
+ get acquisitionAnalytics() {
290
+ return this;
291
+ }
292
+ capabilities() {
293
+ return { serverDryRun: false, reporting: false };
294
+ }
295
+ async report(_query) {
296
+ throw new AdportError3("INVALID_INPUT", "Use analytics_acquisition_report for this website.");
297
+ }
298
+ async previewWrite(_op) {
299
+ throw new AdportError3("POLICY_VIOLATION", "Website analytics is read-only.");
300
+ }
301
+ async applyWrite(_op) {
302
+ throw new AdportError3("POLICY_VIOLATION", "Website analytics is read-only.");
303
+ }
304
+ async listAccounts() {
305
+ return records(await this.client.call("SitesManager.getSitesWithAtLeastViewAccess")).map(siteInfo).map(({ id, name, currency, timezone }) => ({ provider: this.id, id, name, currency, timezone }));
306
+ }
307
+ async site(accountId) {
308
+ const id = matomoSiteId(accountId);
309
+ const raw = await this.client.call("SitesManager.getSiteFromId", { idSite: id });
310
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || String(raw.idsite) !== id)
311
+ throw new AdportError3("PROVIDER_ERROR", "Matomo returned no settings for the requested site.");
312
+ return siteInfo(raw);
313
+ }
314
+ async configuredGoals(site) {
315
+ const raw = await this.client.call("Goals.getGoals", { idSite: site.id });
316
+ const goals = records(raw).filter((g) => !Number(g.deleted)).map((g) => {
317
+ if (!/^[1-9]\d*$/.test(String(g.idgoal)) || typeof g.name !== "string" || g.idsite != null && String(g.idsite) !== site.id)
318
+ throw new AdportError3("PROVIDER_ERROR", "Matomo returned an invalid goal for this site.");
319
+ return { id: String(g.idgoal), name: g.name, counting_method: Number(g.allow_multiple) === 1 ? "per_conversion" : "once_per_visit" };
320
+ });
321
+ if (site.ecommerce) goals.push({ id: "ecommerceOrder", name: "Ecommerce orders", counting_method: "per_order" });
322
+ return goals;
323
+ }
324
+ async listGoals(accountId) {
325
+ return this.configuredGoals(await this.site(accountId));
326
+ }
327
+ async acquisitionReport(query) {
328
+ const site = await this.site(query.account_id);
329
+ if (query.goal_ids) {
330
+ const goals = await this.configuredGoals(site);
331
+ if (query.goal_ids.some((id) => !goals.some((g) => g.id === id))) throw new AdportError3("INVALID_INPUT", "A selected goal is missing from this site. Refresh analytics_goals.");
332
+ }
333
+ return readAcquisition(this.client, site, query);
334
+ }
335
+ };
336
+
337
+ // src/index.ts
338
+ import { matomoBaseUrl, normalizeMatomoUrl as normalizeMatomoUrl3 } from "@adport/core";
339
+ function matomoCredentialsFromData(data) {
340
+ const url = data?.url?.trim(), tokenAuth = data?.token_auth?.trim();
341
+ return url && tokenAuth ? { url: normalizeMatomoUrl2(url), tokenAuth } : void 0;
342
+ }
343
+ function matomoEnvironmentData() {
344
+ return { url: process.env.MATOMO_URL ?? "", token_auth: process.env.MATOMO_TOKEN_AUTH ?? "" };
345
+ }
346
+ function usableCredentials(data) {
347
+ try {
348
+ return matomoCredentialsFromData(data);
349
+ } catch {
350
+ return void 0;
351
+ }
352
+ }
353
+ async function resolveMatomoCredentials(store) {
354
+ return usableCredentials((await store.get("matomo"))?.data) ?? usableCredentials(matomoEnvironmentData());
355
+ }
356
+ async function createMatomoModule(store) {
357
+ const credentials = await resolveMatomoCredentials(store);
358
+ if (!credentials) return void 0;
359
+ let client;
360
+ try {
361
+ client = new MatomoClient(credentials);
362
+ } catch {
363
+ return void 0;
364
+ }
365
+ const provider = new MatomoProvider(client);
366
+ return { provider, tools: [] };
367
+ }
368
+ export {
369
+ MATOMO_READ_METHODS,
370
+ MatomoClient,
371
+ MatomoProvider,
372
+ createMatomoModule,
373
+ matomoBaseUrl,
374
+ matomoCredentialsFromData,
375
+ matomoEnvironmentData,
376
+ matomoSiteId,
377
+ normalizeMatomoUrl3 as normalizeMatomoUrl,
378
+ resolveMatomoCredentials
379
+ };
380
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts","../src/acquisition.ts"],"sourcesContent":["import { normalizeMatomoUrl, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { MatomoClient, type MatomoCredentials } from './client.js';\nimport { MatomoProvider } from './provider.js';\nexport { MatomoClient, MATOMO_READ_METHODS, type MatomoBearerCredentials, type MatomoCredentials } from './client.js';\nexport { MatomoProvider, matomoSiteId, type MatomoSite } from './provider.js';\nexport { matomoBaseUrl, normalizeMatomoUrl } from '@adport/core';\n\n/** Stored data uses { url, token_auth }; both values are required. */\nexport function matomoCredentialsFromData(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n const url = data?.url?.trim(), tokenAuth = data?.token_auth?.trim();\n return url && tokenAuth ? { url: normalizeMatomoUrl(url), tokenAuth } : undefined;\n}\nexport function matomoEnvironmentData(): Record<string, string> {\n return { url: process.env.MATOMO_URL ?? '', token_auth: process.env.MATOMO_TOKEN_AUTH ?? '' };\n}\n/** Unusable values (e.g. a non-https URL) count as absent so one bad pair never stops other providers from loading. */\nfunction usableCredentials(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n try { return matomoCredentialsFromData(data); } catch { return undefined; }\n}\nexport async function resolveMatomoCredentials(store: CredentialStore): Promise<MatomoCredentials | undefined> {\n return usableCredentials((await store.get('matomo'))?.data) ?? usableCredentials(matomoEnvironmentData());\n}\nexport async function createMatomoModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMatomoCredentials(store);\n if (!credentials) return undefined;\n let client: MatomoClient;\n try { client = new MatomoClient(credentials); } catch { return undefined; }\n const provider = new MatomoProvider(client);\n return { provider, tools: [] };\n}\n","import { AdportError, normalizeMatomoUrl } from '@adport/core';\n\ntype MatomoFetch = (url: string, init: {\n method: 'POST'; redirect: 'error'; signal: AbortSignal; headers: Record<string, string>; body: URLSearchParams;\n}) => Promise<Pick<Response, 'ok' | 'status' | 'text'>>;\n\nexport interface MatomoCredentials {\n /** Instance base URL, e.g. https://example.matomo.cloud or https://analytics.example.com/matomo. */\n url: string;\n /** Personal auth token of a user with view access to the sites. */\n tokenAuth: string;\n}\n\nexport interface MatomoBearerCredentials {\n url: string;\n accessToken(): Promise<string>;\n}\n\n/** Documented read methods only. Every other Matomo API method is refused before any request. */\nexport const MATOMO_READ_METHODS = new Set([\n 'API.getReportMetadata', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSiteFromId', 'Goals.getGoals',\n 'Referrers.getReferrerType', 'Referrers.getCampaigns', 'MarketingCampaignsReporting.getName',\n 'MarketingCampaignsReporting.getSource', 'MarketingCampaignsReporting.getMedium', 'MarketingCampaignsReporting.getSourceMedium', 'Actions.getEntryPageUrls',\n]);\nconst RESERVED = new Set(['module', 'method', 'format', 'token_auth', 'force_api_session']);\n\n/**\n * Matomo Reporting API over POST so token_auth never appears in a URL. Matomo\n * answers most failures with HTTP 200 and {\"result\":\"error\"}; messages are\n * classified but never echoed, since they can contain instance details.\n */\nexport class MatomoClient {\n readonly baseUrl: string;\n constructor(private readonly credentials: MatomoCredentials | MatomoBearerCredentials, private readonly fetchImpl: MatomoFetch = fetch) {\n this.baseUrl = normalizeMatomoUrl(credentials.url);\n if ('tokenAuth' in credentials && !credentials.tokenAuth.trim()) throw new AdportError('INVALID_INPUT', 'matomo: token_auth is empty');\n }\n\n async call(method: string, params: Record<string, string> = {}): Promise<unknown> {\n if (!MATOMO_READ_METHODS.has(method)) throw new AdportError('INVALID_INPUT', 'Unsupported Matomo read method.');\n if (Object.keys(params).some(key => RESERVED.has(key))) throw new AdportError('INVALID_INPUT', 'Reserved Matomo request parameter.');\n const body = new URLSearchParams({ ...params, module: 'API', method, format: 'JSON' });\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };\n if ('accessToken' in this.credentials) headers.authorization = 'Bearer ' + await this.credentials.accessToken();\n else body.set('token_auth', this.credentials.tokenAuth.trim());\n let response: Awaited<ReturnType<MatomoFetch>>;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/index.php`, {\n method: 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),\n headers, body,\n });\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'Matomo could not be reached (network error, redirect or timeout). Check MATOMO_URL.');\n }\n if (response.status === 401) throw new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.');\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `Matomo read failed (HTTP ${response.status}).`, { status: response.status });\n let data: unknown;\n try { data = JSON.parse(await response.text()); }\n catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned a non-JSON response. Check that MATOMO_URL points to the Matomo instance, not a login page or proxy.'); }\n if (data && typeof data === 'object' && !Array.isArray(data) && (data as Record<string, unknown>).result === 'error') {\n throw classify(String((data as Record<string, unknown>).message ?? ''), method);\n }\n return data;\n }\n}\n\nfunction classify(message: string, method: string): AdportError {\n const authFailure = /\\b(?:unable to authenticate|authentication (?:failed|required)|not logged in|(?:must|please|need to) (?:log in|login))\\b/i;\n const badToken = /\\btoken_auth\\b.{0,60}\\b(?:invalid|not valid|expired|missing)|\\b(?:invalid|expired|missing) (?:authentication token|token_auth)\\b/i;\n if (authFailure.test(message) || badToken.test(message)) {\n return new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.', { reason: 'auth' });\n }\n // Before access: \"not enough permission to access the segment X\" is a segment problem, not a bad token.\n if (/segment/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the segment. This site must support aggregate entry-page segmentation to group by landing page.', { reason: 'segment' });\n if (/access|permission|not allowed/i.test(message)) {\n return new AdportError('PROVIDER_ERROR', 'Matomo denied access: the token is invalid or its user lacks view access to this site.', { reason: 'access_denied' });\n }\n if (/date|period/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the date or period.', { reason: 'date' });\n return new AdportError('PROVIDER_ERROR', `Matomo returned an error for ${method}. Check the site ID and parameters.`, { reason: 'provider' });\n}\n","import { AdportError, type AdProvider, type Account, type AnalyticsGoal, type AcquisitionQuery, type AcquisitionReport,\n type NormalizedQuery, type Report, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport { readAcquisition, records } from './acquisition.js';\n\nexport function matomoSiteId(value: unknown): string {\n if ((typeof value !== 'string' && typeof value !== 'number') || !/^[1-9]\\d{0,9}$/.test(String(value)))\n throw new AdportError('INVALID_INPUT', 'Matomo requires a positive numeric site ID.');\n return String(value);\n}\n\nexport interface MatomoSite { id: string; name: string; timezone?: string; currency?: string; ecommerce: boolean }\nfunction returnedSiteId(value: unknown) {\n try { return matomoSiteId(value); } catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid site ID.'); }\n}\nconst siteInfo = (raw: Record<string, unknown>): MatomoSite => ({\n id: returnedSiteId(raw.idsite), name: String(raw.name ?? raw.idsite),\n ...(typeof raw.timezone === 'string' ? { timezone: raw.timezone } : {}),\n ...(typeof raw.currency === 'string' ? { currency: raw.currency } : {}), ecommerce: Number(raw.ecommerce) === 1,\n});\n\nexport class MatomoProvider implements AdProvider {\n readonly id = 'matomo';\n get acquisitionAnalytics() { return this; }\n constructor(private readonly client: MatomoClient) {}\n capabilities() { return { serverDryRun: false, reporting: false }; }\n async report(_query: NormalizedQuery): Promise<Report> { throw new AdportError('INVALID_INPUT', 'Use analytics_acquisition_report for this website.'); }\n async previewWrite(_op: WriteOperation): Promise<WritePreview> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n async applyWrite(_op: WriteOperation): Promise<WriteResult> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n\n async listAccounts(): Promise<Account[]> {\n return records(await this.client.call('SitesManager.getSitesWithAtLeastViewAccess')).map(siteInfo).map(({ id, name, currency, timezone }) =>\n ({ provider: this.id, id, name, currency, timezone }));\n }\n\n private async site(accountId: string): Promise<MatomoSite> {\n const id = matomoSiteId(accountId);\n const raw = await this.client.call('SitesManager.getSiteFromId', { idSite: id });\n if (!raw || typeof raw !== 'object' || Array.isArray(raw) || String((raw as Record<string, unknown>).idsite) !== id)\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned no settings for the requested site.');\n return siteInfo(raw as Record<string, unknown>);\n }\n\n private async configuredGoals(site: MatomoSite): Promise<AnalyticsGoal[]> {\n const raw = await this.client.call('Goals.getGoals', { idSite: site.id });\n const goals: AnalyticsGoal[] = records(raw).filter(g => !Number(g.deleted)).map(g => {\n if (!/^[1-9]\\d*$/.test(String(g.idgoal)) || typeof g.name !== 'string' || (g.idsite != null && String(g.idsite) !== site.id))\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid goal for this site.');\n return { id: String(g.idgoal), name: g.name, counting_method: Number(g.allow_multiple) === 1 ? 'per_conversion' : 'once_per_visit' };\n });\n if (site.ecommerce) goals.push({ id: 'ecommerceOrder', name: 'Ecommerce orders', counting_method: 'per_order' });\n return goals;\n }\n\n async listGoals(accountId: string) { return this.configuredGoals(await this.site(accountId)); }\n\n async acquisitionReport(query: AcquisitionQuery): Promise<AcquisitionReport> {\n const site = await this.site(query.account_id);\n if (query.goal_ids) {\n const goals = await this.configuredGoals(site);\n if (query.goal_ids.some(id => !goals.some(g => g.id === id))) throw new AdportError('INVALID_INPUT', 'A selected goal is missing from this site. Refresh analytics_goals.');\n }\n return readAcquisition(this.client, site, query);\n }\n}\n","import { AdportError, type AcquisitionQuery, type AcquisitionReport, type AcquisitionRow } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport type { MatomoSite } from './provider.js';\n\ntype Row = Record<string, unknown>;\nconst object = (v: unknown): v is Row => typeof v === 'object' && v !== null && !Array.isArray(v);\nexport function records(raw: unknown): Row[] {\n const list = Array.isArray(raw) ? raw : object(raw) ? Object.values(raw) : null;\n if (!list || !list.every(object)) throw new AdportError('PROVIDER_ERROR', 'Unexpected Matomo report shape.');\n return list;\n}\nconst maxRows = 10000;\nfunction table(raw: unknown): Row[] {\n const rows = records(raw);\n if (rows.length > maxRows) throw new AdportError('PROVIDER_ERROR', 'This Matomo archive exceeds the report limit. Choose a shorter date range.');\n return rows;\n}\nconst summary = (r: Row) => r.label === 'Others' || r.label === '-1' || Boolean(Number(r.is_summary));\nconst numeric = (v: unknown): number | null => (typeof v === 'number' || typeof v === 'string' && v.trim()) && Number.isFinite(Number(v)) ? Number(v) : null;\n\ntype Measures = { sessions: number | null; conversions: number | null; revenue: number | null; [key: string]: number | null };\nfunction measures(r: Row, site: MatomoSite, ids: string[]): Measures {\n const goals = object(r.goals) ? r.goals : {};\n const goalMetric = (id: string, field: string) => {\n const goal = goals['idgoal=' + id];\n return goal === undefined ? 0 : object(goal) ? numeric(goal[field]) : null;\n };\n const m: Measures = {\n sessions: numeric(r.nb_visits), conversions: numeric(r.nb_conversions ?? (Object.keys(goals).length ? undefined : 0)),\n revenue: site.ecommerce ? goalMetric('ecommerceOrder', 'revenue') : numeric(r.revenue ?? (Object.keys(goals).length ? undefined : 0)),\n };\n for (const id of ids) m['goal:' + id] = goalMetric(id, 'nb_conversions');\n return m;\n}\n\nfunction combine(a: Measures, b: Measures, sign = 1): Measures {\n const result = { ...a };\n for (const key of Object.keys(a)) {\n const x = a[key], y = b[key];\n result[key] = x == null || y == null ? null : x + sign * y;\n }\n return result;\n}\nfunction hasData(m: Measures) { return Object.values(m).some(x => x === null || Math.abs(x) > 0.000001); }\nfunction residual(total: Measures, used: Measures, notes: Set<string>): Measures {\n const diff = combine(total, used, -1);\n for (const [key, value] of Object.entries(diff)) {\n if (value !== null && Math.abs(value) < 0.000001) diff[key] = 0;\n else if (key !== 'revenue' && value !== null && value < 0) {\n diff[key] = null;\n notes.add('Matomo archives disagree on a subtotal. An unreconciled measure is unavailable.');\n }\n }\n return diff;\n}\nfunction row(dims: AcquisitionRow['dimensions'], m: Measures, ids: string[]): AcquisitionRow {\n const counts = ids.map(id => m['goal:' + id] ?? null);\n return { dimensions: dims, metrics: { sessions: m.sessions, revenue: m.revenue,\n conversions: ids.length ? counts.some(v => v === null) ? null : counts.reduce<number>((a, b) => a + b!, 0) : m.conversions },\n ...(ids.length ? { goal_counts: Object.fromEntries(ids.map((id, i) => [id, counts[i] ?? null])) } : {}) };\n}\n\n/** Only the source/medium archive contains joint rows. The name archive retains campaigns whose source or medium was never captured. */\nasync function groups(client: MatomoClient, params: Record<string, string>, site: MatomoSite, plugin: boolean, ids: string[], notes: Set<string>) {\n const read = async (method: string, options = {}) => table(await client.call(method, { ...params, ...options }));\n const [channels, names, pairs, sources, media] = await Promise.all([\n read('Referrers.getReferrerType'), read(plugin ? 'MarketingCampaignsReporting.getName' : 'Referrers.getCampaigns'),\n plugin ? read('MarketingCampaignsReporting.getSourceMedium', { expanded: '1' }) : [],\n plugin ? read('MarketingCampaignsReporting.getSource') : [], plugin ? read('MarketingCampaignsReporting.getMedium') : [],\n ]);\n const zero = measures({ nb_visits: 0 }, site, ids);\n const measuresFor = (r: Row) => measures(r, site, ids);\n let siteTotal = zero, namedTotal = zero;\n for (const channel of channels) siteTotal = combine(siteTotal, measuresFor(channel));\n const namedChildren = new Map<string, Measures>(), rows: AcquisitionRow[] = [];\n const sourceLabels = new Set(sources.map(r => r.label)), mediumLabels = new Set(media.map(r => r.label));\n const archivedLabels = sources.some(summary) || media.some(summary);\n for (const pair of pairs) {\n if (summary(pair)) continue;\n const label = String(pair.label), candidates: Array<[string | null, string | null]> = [];\n // Matomo omits empty components and joins the others with a literal separator, also legal inside a UTM value.\n if (sourceLabels.has(label)) candidates.push([label, null]);\n if (mediumLabels.has(label)) candidates.push([null, label]);\n for (let pos = label.indexOf(' - '); pos >= 0; pos = label.indexOf(' - ', pos + 1)) {\n const source = label.slice(0, pos), medium = label.slice(pos + 3);\n if (sourceLabels.has(source) && mediumLabels.has(medium)) candidates.push([source, medium]);\n }\n if (candidates.length !== 1 || archivedLabels) {\n notes.add('Matomo returned an ambiguous or archived source/medium label. Its traffic stays in the unresolved dimensions.');\n continue;\n }\n const [source, medium] = candidates[0]!;\n let children = zero;\n const parent = measuresFor(pair);\n for (const child of table(pair.subtable ?? [])) {\n if (summary(child) || typeof child.label !== 'string' || !child.label) continue;\n const m = measuresFor(child);\n children = combine(children, m);\n namedChildren.set(child.label, combine(namedChildren.get(child.label) ?? zero, m));\n rows.push(row({ source, medium, campaign: child.label }, m, ids));\n }\n const remainder = residual(parent, children, notes);\n if (hasData(remainder)) rows.push(row({ source, medium, campaign: null }, remainder, ids));\n namedTotal = combine(namedTotal, parent);\n }\n for (const name of names) {\n if (summary(name) || typeof name.label !== 'string' || !name.label) continue;\n const m = residual(measuresFor(name), namedChildren.get(name.label) ?? zero, notes);\n if (hasData(m)) rows.push(row({ source: null, medium: null, campaign: name.label }, m, ids));\n namedTotal = combine(namedTotal, m);\n }\n const rest = residual(siteTotal, namedTotal, notes);\n if (hasData(rest)) rows.push(row({ source: null, medium: null, campaign: null }, rest, ids));\n return { rows, sessions: siteTotal.sessions };\n}\n\ninterface Landing { path: string; urls: Set<string>; visits: number }\nasync function landingPages(client: MatomoClient, params: Record<string, string>, notes: Set<string>): Promise<Landing[]> {\n const entries = table(await client.call('Actions.getEntryPageUrls', { ...params, flat: '1', showColumns: 'label,url,entry_nb_visits' }));\n const paths = new Map<string, Landing>();\n for (const entry of entries) {\n if (summary(entry) || typeof entry.url !== 'string') { notes.add('Matomo omitted exact URLs for some archived entry pages.'); continue; }\n const url = new URL(entry.url);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) continue;\n const path = url.origin + url.pathname;\n const page = paths.get(path) ?? { path, urls: new Set<string>(), visits: 0 };\n page.urls.add(entry.url);\n page.visits += numeric(entry.entry_nb_visits) ?? 0;\n paths.set(path, page);\n }\n return [...paths.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);\n}\n\nexport async function readAcquisition(client: MatomoClient, site: MatomoSite, q: AcquisitionQuery): Promise<AcquisitionReport> {\n const cursor = q.cursor ?? '0.0';\n if (!/^\\d{1,6}\\.\\d{1,7}$/.test(cursor)) throw new AdportError('INVALID_INPUT', 'Invalid Matomo report cursor.');\n const [bucket, offset] = cursor.split('.').map(Number) as [number, number];\n if (!q.landing_page && bucket !== 0) throw new AdportError('INVALID_INPUT', 'This cursor belongs to a landing-page report.');\n const params = { idSite: site.id, period: q.start_date === q.end_date ? 'day' : 'range',\n date: q.start_date === q.end_date ? q.start_date : q.start_date + ',' + q.end_date,\n filter_limit: String(maxRows + 1), filter_limit_subtable: String(maxRows + 1), format_metrics: '0', language: 'en' };\n const metadata = records(await client.call('API.getReportMetadata', { idSite: site.id, idSites: site.id, apiModule: 'MarketingCampaignsReporting', hideMetricsDoc: '1' }));\n const plugin = metadata.some(r => r.module === 'MarketingCampaignsReporting' && r.action === 'getSourceMedium');\n const notes = new Set<string>();\n if (!plugin) notes.add('This site lacks the Marketing Campaigns Reporting source/medium archive. Campaign names are available; source and medium are unavailable.');\n const pages = q.landing_page ? await landingPages(client, params, notes) : undefined;\n const page = pages?.[bucket];\n const rows: AcquisitionRow[] = [];\n let next: string | undefined;\n if (!pages || page) {\n const segment = page ? [...page.urls].map(url => 'entryPageUrl==' + encodeURIComponent(url)).join(',') : undefined;\n const result = await groups(client, { ...params, ...(segment ? { segment } : {}) }, site, plugin, q.goal_ids ?? [], notes);\n if (page && result.sessions !== page.visits) throw new AdportError('PROVIDER_ERROR', 'Matomo has no matching segmented archive for this entry page. Enable read-time segment archiving or run the report without landing_page.');\n const sorted = result.rows.sort((a, b) => {\n const x = JSON.stringify(a.dimensions), y = JSON.stringify(b.dimensions);\n return x < y ? -1 : x > y ? 1 : 0;\n });\n rows.push(...sorted.slice(offset, offset + q.limit));\n if (page) for (const r of rows) r.dimensions.landing_page = page.path;\n if (offset + rows.length < sorted.length) next = `${bucket}.${offset + rows.length}`;\n else if (pages && bucket + 1 < pages.length) next = `${bucket + 1}.0`;\n }\n return { rows, date_range: { start: q.start_date, end: q.end_date, timezone: site.timezone ?? null }, currency: site.currency ?? null,\n attribution: 'Matomo archived campaign parameters and native conversion attribution. Null dimensions include untagged or unresolved traffic.',\n revenue_basis: site.ecommerce ? 'Recorded ecommerce order revenue in site currency, across all goals.' : 'Recorded converted goal revenue in site currency, across all goals.',\n notes: [...notes], ...(next ? { next_cursor: next } : {}) };\n}\n"],"mappings":";AAAA,SAAS,sBAAAA,2B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,QAAI,MAAM,UAAU;AAClB,YAAM,QAAQ,MAAM,KAAK,gBAAgB,IAAI;AAC7C,UAAI,MAAM,SAAS,KAAK,QAAM,CAAC,MAAM,KAAK,OAAK,EAAE,OAAO,EAAE,CAAC,EAAG,OAAM,IAAIA,aAAY,iBAAiB,qEAAqE;AAAA,IAC5K;AACA,WAAO,gBAAgB,KAAK,QAAQ,MAAM,KAAK;AAAA,EACjD;AACF;;;AF3DA,SAAS,eAAe,sBAAAC,2BAA0B;AAG3C,SAAS,0BAA0B,MAAyE;AACjH,QAAM,MAAM,MAAM,KAAK,KAAK,GAAG,YAAY,MAAM,YAAY,KAAK;AAClE,SAAO,OAAO,YAAY,EAAE,KAAKA,oBAAmB,GAAG,GAAG,UAAU,IAAI;AAC1E;AACO,SAAS,wBAAgD;AAC9D,SAAO,EAAE,KAAK,QAAQ,IAAI,cAAc,IAAI,YAAY,QAAQ,IAAI,qBAAqB,GAAG;AAC9F;AAEA,SAAS,kBAAkB,MAAyE;AAClG,MAAI;AAAE,WAAO,0BAA0B,IAAI;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAW;AAC5E;AACA,eAAsB,yBAAyB,OAAgE;AAC7G,SAAO,mBAAmB,MAAM,MAAM,IAAI,QAAQ,IAAI,IAAI,KAAK,kBAAkB,sBAAsB,CAAC;AAC1G;AACA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI;AACJ,MAAI;AAAE,aAAS,IAAI,aAAa,WAAW;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAW;AAC1E,QAAM,WAAW,IAAI,eAAe,MAAM;AAC1C,SAAO,EAAE,UAAU,OAAO,CAAC,EAAE;AAC/B;","names":["normalizeMatomoUrl","AdportError","AdportError","source","medium","AdportError","normalizeMatomoUrl"]}
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@adport/provider-matomo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.15.0",
4
+ "description": "Read-only Matomo analytics provider for adport",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "dependencies": {
19
+ "zod": "^4.6.7",
20
+ "@adport/core": "0.15.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.6.6",
24
+ "tsup": "^8.3.0",
25
+ "typescript": "^5.8.0",
26
+ "vitest": "^5.1.1"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/ynnickw/adport.git",
31
+ "directory": "packages/matomo"
32
+ },
33
+ "homepage": "https://github.com/ynnickw/adport#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/ynnickw/adport/issues"
36
+ },
37
+ "engines": {
38
+ "node": ">=22.13"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
45
+ "test": "vitest run",
46
+ "typecheck": "tsc --noEmit"
47
+ }
6
48
  }