@zerodot/google-analytics 0.0.0-stage → 1.1.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 +661 -0
- package/README.md +49 -2
- package/dist/index.cjs +1284 -0
- package/google-analytics.svg +1 -0
- package/package.json +46 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1284 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
let _zerodot_node_sdk = require("@zerodot/node-sdk");
|
|
4
|
+
// src/api.ts
|
|
5
|
+
const ANALYTICS_OAUTH2_CREDENTIAL = "google_analytics.oauth2";
|
|
6
|
+
const ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
|
|
7
|
+
/** The Data API of Google Analytics 4. */
|
|
8
|
+
const DATA_API = "https://analyticsdata.googleapis.com";
|
|
9
|
+
/** The Reporting API v4 of Universal Analytics. It also has the user activity search. */
|
|
10
|
+
const REPORTING_API = "https://analyticsreporting.googleapis.com";
|
|
11
|
+
/** The Admin API. The credential check uses it. */
|
|
12
|
+
const ADMIN_API = "https://analyticsadmin.googleapis.com";
|
|
13
|
+
/** The Management and Metadata APIs v3 of Universal Analytics. */
|
|
14
|
+
const LEGACY_API = "https://www.googleapis.com";
|
|
15
|
+
const text$1 = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
16
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
/** The access token of a credential. The server refreshes it. */
|
|
18
|
+
function analyticsToken(credential) {
|
|
19
|
+
if (credential?.type === "google_analytics.oauth2") {
|
|
20
|
+
const token = text$1(credential.data.accessToken);
|
|
21
|
+
if (!token) throw new Error("The Google Analytics credential is not connected to an account yet");
|
|
22
|
+
return token;
|
|
23
|
+
}
|
|
24
|
+
throw new Error("The node needs a Google Analytics credential");
|
|
25
|
+
}
|
|
26
|
+
const HINTS = {
|
|
27
|
+
401: " Connect the credential again.",
|
|
28
|
+
403: " Check that the account can see the property or view, and turn on the Google Analytics API in the Google Cloud project.",
|
|
29
|
+
404: " Check the property ID or the view ID.",
|
|
30
|
+
429: " Google limits the number of requests. Try again later."
|
|
31
|
+
};
|
|
32
|
+
/** A clear error from a Google answer: `{ error: { code, message, status } }`. */
|
|
33
|
+
function analyticsError(status, answer, action) {
|
|
34
|
+
const error = isObject(answer) && isObject(answer.error) ? answer.error : {};
|
|
35
|
+
const message = text$1(error.message) ?? "no message";
|
|
36
|
+
const code = text$1(error.status);
|
|
37
|
+
const hint = HINTS[status] ?? "";
|
|
38
|
+
return /* @__PURE__ */ new Error(`Google Analytics could not ${action} (${status}${code ? ` ${code}` : ""}): ${message}.${hint}`);
|
|
39
|
+
}
|
|
40
|
+
const BASE = {
|
|
41
|
+
data: DATA_API,
|
|
42
|
+
reporting: REPORTING_API,
|
|
43
|
+
admin: ADMIN_API,
|
|
44
|
+
legacy: LEGACY_API
|
|
45
|
+
};
|
|
46
|
+
function urlOf(request) {
|
|
47
|
+
const url = new URL(`${BASE[request.api]}${request.path}`);
|
|
48
|
+
for (const [key, value] of Object.entries(request.query ?? {})) if (value !== void 0 && value !== "") url.searchParams.set(key, value);
|
|
49
|
+
return url.toString();
|
|
50
|
+
}
|
|
51
|
+
/** One call with a JSON answer. The error text never has the token. */
|
|
52
|
+
async function callAnalytics(token, request, options) {
|
|
53
|
+
const json = request.body ? JSON.stringify(request.body) : void 0;
|
|
54
|
+
const response = await fetch(urlOf(request), {
|
|
55
|
+
method: request.method,
|
|
56
|
+
headers: {
|
|
57
|
+
authorization: `Bearer ${token}`,
|
|
58
|
+
accept: "application/json",
|
|
59
|
+
...json ? { "content-type": "application/json" } : {}
|
|
60
|
+
},
|
|
61
|
+
body: json,
|
|
62
|
+
redirect: "error",
|
|
63
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
|
|
64
|
+
});
|
|
65
|
+
const answer = await response.json().catch(() => null);
|
|
66
|
+
if (!response.ok) throw analyticsError(response.status, answer, request.action);
|
|
67
|
+
return answer;
|
|
68
|
+
}
|
|
69
|
+
// src/icon.ts
|
|
70
|
+
const ANALYTICS_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../google-analytics.svg");
|
|
71
|
+
// src/credential.ts
|
|
72
|
+
const TIMEOUT_MS = 1e4;
|
|
73
|
+
/** Google sign-in. `access_type=offline` and `prompt=consent` give a refresh token. */
|
|
74
|
+
const GOOGLE_OAUTH2 = {
|
|
75
|
+
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
76
|
+
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
77
|
+
scopes: [ANALYTICS_SCOPE],
|
|
78
|
+
authQuery: {
|
|
79
|
+
access_type: "offline",
|
|
80
|
+
prompt: "consent"
|
|
81
|
+
},
|
|
82
|
+
authentication: "body",
|
|
83
|
+
pkce: true
|
|
84
|
+
};
|
|
85
|
+
/** Fields that only the server writes, after the user connects the account. */
|
|
86
|
+
const OAUTH2_TOKEN_FIELDS = [
|
|
87
|
+
"accessToken",
|
|
88
|
+
"refreshToken",
|
|
89
|
+
"expiresAt",
|
|
90
|
+
"tokenType",
|
|
91
|
+
"grantedScope"
|
|
92
|
+
];
|
|
93
|
+
/** Lists one account summary. A 401 or a 403 throws with the text of Google. */
|
|
94
|
+
async function check(credential) {
|
|
95
|
+
const options = {
|
|
96
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
97
|
+
timeoutMs: TIMEOUT_MS
|
|
98
|
+
};
|
|
99
|
+
await callAnalytics(analyticsToken(credential), {
|
|
100
|
+
api: "admin",
|
|
101
|
+
method: "GET",
|
|
102
|
+
path: "/v1beta/accountSummaries",
|
|
103
|
+
query: { pageSize: "1" },
|
|
104
|
+
action: "check the credential"
|
|
105
|
+
}, options);
|
|
106
|
+
}
|
|
107
|
+
const analyticsOAuth2Credential = {
|
|
108
|
+
type: ANALYTICS_OAUTH2_CREDENTIAL,
|
|
109
|
+
label: "Google Analytics OAuth2",
|
|
110
|
+
fields: zod.z.object({
|
|
111
|
+
clientId: zod.z.string().min(1).meta({ placeholder: "…apps.googleusercontent.com" }),
|
|
112
|
+
clientSecret: zod.z.string().min(1),
|
|
113
|
+
accessToken: zod.z.string().min(1).optional(),
|
|
114
|
+
refreshToken: zod.z.string().min(1).optional(),
|
|
115
|
+
/** ISO 8601 time. */
|
|
116
|
+
expiresAt: zod.z.iso.datetime().optional(),
|
|
117
|
+
tokenType: zod.z.string().min(1).optional(),
|
|
118
|
+
grantedScope: zod.z.string().optional()
|
|
119
|
+
}),
|
|
120
|
+
secretFields: [
|
|
121
|
+
"clientSecret",
|
|
122
|
+
"accessToken",
|
|
123
|
+
"refreshToken"
|
|
124
|
+
],
|
|
125
|
+
serverFields: [...OAUTH2_TOKEN_FIELDS],
|
|
126
|
+
oauth2: GOOGLE_OAUTH2,
|
|
127
|
+
icon: "Analytics01Icon",
|
|
128
|
+
iconUrl: ANALYTICS_ICON,
|
|
129
|
+
test: check
|
|
130
|
+
};
|
|
131
|
+
// src/config.ts
|
|
132
|
+
/** The ID in the URL of a GA4 property or a view in Google Analytics. */
|
|
133
|
+
const PROPERTY_URL_PATTERN = "analytics\\.google\\.com/analytics.*/p([0-9]+)";
|
|
134
|
+
const VIEW_URL_PATTERN = "analytics\\.google\\.com/analytics.*p([0-9]+)";
|
|
135
|
+
const RESOURCES = ["report", "userActivity"];
|
|
136
|
+
const OPERATIONS_OF = {
|
|
137
|
+
report: ["get"],
|
|
138
|
+
userActivity: ["search"]
|
|
139
|
+
};
|
|
140
|
+
const PROPERTY_TYPES = ["ga4", "universal"];
|
|
141
|
+
const DATE_RANGES = [
|
|
142
|
+
"last7days",
|
|
143
|
+
"last30days",
|
|
144
|
+
"today",
|
|
145
|
+
"yesterday",
|
|
146
|
+
"lastCalendarWeek",
|
|
147
|
+
"lastCalendarMonth",
|
|
148
|
+
"custom"
|
|
149
|
+
];
|
|
150
|
+
const ACTIVITY_TYPES = [
|
|
151
|
+
"ECOMMERCE",
|
|
152
|
+
"EVENT",
|
|
153
|
+
"GOAL",
|
|
154
|
+
"PAGEVIEW",
|
|
155
|
+
"SCREENVIEW"
|
|
156
|
+
];
|
|
157
|
+
/** The most rows of one `runReport` page. */
|
|
158
|
+
const GA4_PAGE_SIZE = 1e5;
|
|
159
|
+
const valuesOf = (options) => options.map(([value]) => value);
|
|
160
|
+
const labelsOf = (options) => Object.fromEntries(options.map(([value, label]) => [value, label]));
|
|
161
|
+
const GA4_DIMENSIONS = [
|
|
162
|
+
["browser", "Browser"],
|
|
163
|
+
["campaignName", "Campaign"],
|
|
164
|
+
["city", "City"],
|
|
165
|
+
["country", "Country"],
|
|
166
|
+
["date", "Date"],
|
|
167
|
+
["deviceCategory", "Device Category"],
|
|
168
|
+
["itemName", "Item Name"],
|
|
169
|
+
["language", "Language"],
|
|
170
|
+
["pageLocation", "Page Location"],
|
|
171
|
+
["sourceMedium", "Source / Medium"],
|
|
172
|
+
["other", "Other dimensions…"]
|
|
173
|
+
];
|
|
174
|
+
const GA4_METRICS = [
|
|
175
|
+
["active1DayUsers", "1 Day Active Users"],
|
|
176
|
+
["active28DayUsers", "28 Day Active Users"],
|
|
177
|
+
["active7DayUsers", "7 Day Active Users"],
|
|
178
|
+
["checkouts", "Checkouts"],
|
|
179
|
+
["eventCount", "Events"],
|
|
180
|
+
["screenPageViews", "Page Views"],
|
|
181
|
+
["userEngagementDuration", "Session Duration"],
|
|
182
|
+
["sessions", "Sessions"],
|
|
183
|
+
["sessionsPerUser", "Sessions per User"],
|
|
184
|
+
["totalUsers", "Total Users"],
|
|
185
|
+
["other", "Other metrics…"],
|
|
186
|
+
["custom", "Custom metric…"]
|
|
187
|
+
];
|
|
188
|
+
const UA_DIMENSIONS = [
|
|
189
|
+
["ga:browser", "Browser"],
|
|
190
|
+
["ga:campaign", "Campaign"],
|
|
191
|
+
["ga:city", "City"],
|
|
192
|
+
["ga:country", "Country"],
|
|
193
|
+
["ga:date", "Date"],
|
|
194
|
+
["ga:deviceCategory", "Device Category"],
|
|
195
|
+
["ga:productName", "Item Name"],
|
|
196
|
+
["ga:language", "Language"],
|
|
197
|
+
["ga:pagePath", "Page"],
|
|
198
|
+
["ga:sourceMedium", "Source / Medium"],
|
|
199
|
+
["other", "Other dimensions…"]
|
|
200
|
+
];
|
|
201
|
+
const UA_METRICS = [
|
|
202
|
+
["ga:productCheckouts", "Checkouts"],
|
|
203
|
+
["ga:totalEvents", "Events"],
|
|
204
|
+
["ga:pageviews", "Page Views"],
|
|
205
|
+
["ga:sessionDuration", "Session Duration"],
|
|
206
|
+
["ga:sessions", "Sessions"],
|
|
207
|
+
["ga:sessionsPerUser", "Sessions per User"],
|
|
208
|
+
["ga:users", "Total Users"],
|
|
209
|
+
["other", "Other metrics…"],
|
|
210
|
+
["custom", "Custom metric…"]
|
|
211
|
+
];
|
|
212
|
+
const ga4Dimension = zod.z.enum(valuesOf(GA4_DIMENSIONS)).default("date").meta({
|
|
213
|
+
title: "Dimension",
|
|
214
|
+
labels: labelsOf(GA4_DIMENSIONS)
|
|
215
|
+
});
|
|
216
|
+
const ga4Metric = zod.z.enum(valuesOf(GA4_METRICS)).default("totalUsers").meta({
|
|
217
|
+
title: "Metric",
|
|
218
|
+
labels: labelsOf(GA4_METRICS)
|
|
219
|
+
});
|
|
220
|
+
const valueType = zod.z.enum(["doubleValue", "int64Value"]).default("doubleValue").meta({
|
|
221
|
+
title: "Value Type",
|
|
222
|
+
labels: {
|
|
223
|
+
doubleValue: "Double Value",
|
|
224
|
+
int64Value: "Integer Value"
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
const numericOperation = zod.z.enum([
|
|
228
|
+
"EQUAL",
|
|
229
|
+
"GREATER_THAN",
|
|
230
|
+
"GREATER_THAN_OR_EQUAL",
|
|
231
|
+
"LESS_THAN",
|
|
232
|
+
"LESS_THAN_OR_EQUAL"
|
|
233
|
+
]).default("EQUAL").meta({
|
|
234
|
+
title: "Operation",
|
|
235
|
+
labels: {
|
|
236
|
+
EQUAL: "Equal",
|
|
237
|
+
GREATER_THAN: "Greater Than",
|
|
238
|
+
GREATER_THAN_OR_EQUAL: "Greater than or Equal",
|
|
239
|
+
LESS_THAN: "Less Than",
|
|
240
|
+
LESS_THAN_OR_EQUAL: "Less than or Equal"
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
const filterGroup$1 = zod.z.enum(["andGroup", "orGroup"]).default("andGroup").meta({
|
|
244
|
+
title: "Filter Expression Type",
|
|
245
|
+
labels: {
|
|
246
|
+
andGroup: "And Group",
|
|
247
|
+
orGroup: "Or Group"
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
/** A name field that loads its options. The user can still type any name. */
|
|
251
|
+
const loadedName = (loadOptions, dependsOn) => zod.z.string().optional().meta({
|
|
252
|
+
title: "Name",
|
|
253
|
+
description: "The API name. Used when the list name is \"other\"",
|
|
254
|
+
loadOptions,
|
|
255
|
+
dependsOn
|
|
256
|
+
});
|
|
257
|
+
const ga4MetricName = loadedName("ga4Metrics", ["propertyId"]);
|
|
258
|
+
const ga4DimensionName = loadedName("ga4Dimensions", ["propertyId"]);
|
|
259
|
+
const uaMetricName = loadedName("uaMetrics", ["viewId"]);
|
|
260
|
+
const uaDimensionName = loadedName("uaDimensions", ["viewId"]);
|
|
261
|
+
const ga4MetricItem = zod.z.object({
|
|
262
|
+
listName: ga4Metric,
|
|
263
|
+
name: ga4MetricName.meta({ description: "The API name of the metric. For \"Custom metric\", any name for the column" }),
|
|
264
|
+
expression: zod.z.string().optional().meta({
|
|
265
|
+
title: "Expression",
|
|
266
|
+
description: "A mathematical expression for derived metrics. For example, the metric Event count per user is eventCount/totalUsers"
|
|
267
|
+
}),
|
|
268
|
+
invisible: zod.z.boolean().default(false).meta({
|
|
269
|
+
title: "Invisible",
|
|
270
|
+
description: "Whether a metric is invisible in the report response. An invisible metric has no column, but a filter, an order, or an expression can use it"
|
|
271
|
+
})
|
|
272
|
+
});
|
|
273
|
+
const ga4DimensionItem = zod.z.object({
|
|
274
|
+
listName: ga4Dimension,
|
|
275
|
+
name: ga4DimensionName
|
|
276
|
+
});
|
|
277
|
+
const stringFilter = zod.z.object({
|
|
278
|
+
listName: ga4Dimension,
|
|
279
|
+
name: ga4DimensionName,
|
|
280
|
+
value: zod.z.string().default(""),
|
|
281
|
+
caseSensitive: zod.z.boolean().default(true),
|
|
282
|
+
matchType: zod.z.enum([
|
|
283
|
+
"BEGINS_WITH",
|
|
284
|
+
"CONTAINS",
|
|
285
|
+
"ENDS_WITH",
|
|
286
|
+
"EXACT",
|
|
287
|
+
"FULL_REGEXP",
|
|
288
|
+
"PARTIAL_REGEXP"
|
|
289
|
+
]).default("EXACT").meta({
|
|
290
|
+
title: "Match Type",
|
|
291
|
+
labels: {
|
|
292
|
+
BEGINS_WITH: "Begins With",
|
|
293
|
+
CONTAINS: "Contains Value",
|
|
294
|
+
ENDS_WITH: "Ends With",
|
|
295
|
+
EXACT: "Exact Match",
|
|
296
|
+
FULL_REGEXP: "Full Match for the Regular Expression",
|
|
297
|
+
PARTIAL_REGEXP: "Partial Match for the Regular Expression"
|
|
298
|
+
}
|
|
299
|
+
})
|
|
300
|
+
});
|
|
301
|
+
const inListFilter = zod.z.object({
|
|
302
|
+
listName: ga4Dimension,
|
|
303
|
+
name: ga4DimensionName,
|
|
304
|
+
values: zod.z.string().default("").meta({ description: "Comma separated list of values. Must be non-empty" }),
|
|
305
|
+
caseSensitive: zod.z.boolean().default(true)
|
|
306
|
+
});
|
|
307
|
+
const dimensionNumericFilter = zod.z.object({
|
|
308
|
+
listName: ga4Dimension,
|
|
309
|
+
name: ga4DimensionName,
|
|
310
|
+
valueType,
|
|
311
|
+
value: zod.z.string().default(""),
|
|
312
|
+
operation: numericOperation
|
|
313
|
+
});
|
|
314
|
+
const metricNumericFilter = zod.z.object({
|
|
315
|
+
listName: ga4Metric,
|
|
316
|
+
name: ga4MetricName,
|
|
317
|
+
valueType,
|
|
318
|
+
value: zod.z.string().default(""),
|
|
319
|
+
operation: numericOperation
|
|
320
|
+
});
|
|
321
|
+
const betweenFilter = zod.z.object({
|
|
322
|
+
listName: ga4Metric,
|
|
323
|
+
name: ga4MetricName,
|
|
324
|
+
valueType,
|
|
325
|
+
fromValue: zod.z.string().default(""),
|
|
326
|
+
toValue: zod.z.string().default("")
|
|
327
|
+
});
|
|
328
|
+
const dimensionFilters = zod.z.object({ filterExpressions: zod.z.object({
|
|
329
|
+
filterExpressionType: filterGroup$1,
|
|
330
|
+
expression: zod.z.object({
|
|
331
|
+
stringFilter: zod.z.array(stringFilter).default([]),
|
|
332
|
+
inListFilter: zod.z.array(inListFilter).default([]),
|
|
333
|
+
numericFilter: zod.z.array(dimensionNumericFilter).default([])
|
|
334
|
+
}).optional()
|
|
335
|
+
}).optional() });
|
|
336
|
+
const metricFilters = zod.z.object({ filterExpressions: zod.z.object({
|
|
337
|
+
filterExpressionType: filterGroup$1,
|
|
338
|
+
expression: zod.z.object({
|
|
339
|
+
betweenFilter: zod.z.array(betweenFilter).default([]),
|
|
340
|
+
numericFilter: zod.z.array(metricNumericFilter).default([])
|
|
341
|
+
}).optional()
|
|
342
|
+
}).optional() });
|
|
343
|
+
const orderBy = zod.z.object({
|
|
344
|
+
metricOrderBy: zod.z.array(zod.z.object({
|
|
345
|
+
desc: zod.z.boolean().default(false).meta({ title: "Descending" }),
|
|
346
|
+
metricName: zod.z.string().default("").meta({
|
|
347
|
+
title: "Metric Name",
|
|
348
|
+
loadOptions: "ga4Metrics",
|
|
349
|
+
dependsOn: ["propertyId"]
|
|
350
|
+
})
|
|
351
|
+
})).default([]),
|
|
352
|
+
dimmensionOrderBy: zod.z.array(zod.z.object({
|
|
353
|
+
desc: zod.z.boolean().default(false).meta({ title: "Descending" }),
|
|
354
|
+
dimensionName: zod.z.string().default("").meta({
|
|
355
|
+
title: "Dimension Name",
|
|
356
|
+
loadOptions: "ga4Dimensions",
|
|
357
|
+
dependsOn: ["propertyId"]
|
|
358
|
+
}),
|
|
359
|
+
orderType: zod.z.enum([
|
|
360
|
+
"ALPHANUMERIC",
|
|
361
|
+
"CASE_INSENSITIVE_ALPHANUMERIC",
|
|
362
|
+
"NUMERIC",
|
|
363
|
+
"ORDER_TYPE_UNSPECIFIED"
|
|
364
|
+
]).default("ORDER_TYPE_UNSPECIFIED").meta({
|
|
365
|
+
title: "Order Type",
|
|
366
|
+
labels: {
|
|
367
|
+
ALPHANUMERIC: "Alphanumeric",
|
|
368
|
+
CASE_INSENSITIVE_ALPHANUMERIC: "Case Insensitive Alphanumeric",
|
|
369
|
+
NUMERIC: "Numeric",
|
|
370
|
+
ORDER_TYPE_UNSPECIFIED: "Unspecified"
|
|
371
|
+
}
|
|
372
|
+
})
|
|
373
|
+
})).default([])
|
|
374
|
+
});
|
|
375
|
+
const ga4AdditionalFields = zod.z.object({
|
|
376
|
+
currencyCode: zod.z.string().optional().meta({
|
|
377
|
+
title: "Currency Code",
|
|
378
|
+
description: "A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\". Empty: the default currency of the property"
|
|
379
|
+
}),
|
|
380
|
+
dimensionFiltersUI: dimensionFilters.optional().meta({ title: "Dimensions Filters" }),
|
|
381
|
+
metricAggregations: zod.z.array(zod.z.enum([
|
|
382
|
+
"MAXIMUM",
|
|
383
|
+
"MINIMUM",
|
|
384
|
+
"TOTAL"
|
|
385
|
+
])).default([]).meta({
|
|
386
|
+
title: "Metric Aggregation",
|
|
387
|
+
description: "Only when Simplify Output is off"
|
|
388
|
+
}),
|
|
389
|
+
metricsFiltersUI: metricFilters.optional().meta({ title: "Metrics Filters" }),
|
|
390
|
+
keepEmptyRows: zod.z.boolean().default(false).meta({
|
|
391
|
+
title: "Keep Empty Rows",
|
|
392
|
+
description: "Off: a row with all metrics equal to 0 is not returned. On: these rows are returned if no filter removes them"
|
|
393
|
+
}),
|
|
394
|
+
orderByUI: orderBy.optional().meta({
|
|
395
|
+
title: "Order By",
|
|
396
|
+
description: "How rows are ordered in the response"
|
|
397
|
+
}),
|
|
398
|
+
returnPropertyQuota: zod.z.boolean().default(false).meta({
|
|
399
|
+
title: "Return Property Quota",
|
|
400
|
+
description: "Return the state of the quota of the property. Only when Simplify Output is off"
|
|
401
|
+
})
|
|
402
|
+
});
|
|
403
|
+
const uaMetricItem = zod.z.object({
|
|
404
|
+
listName: zod.z.enum(valuesOf(UA_METRICS)).default("ga:users").meta({
|
|
405
|
+
title: "Metric",
|
|
406
|
+
labels: labelsOf(UA_METRICS)
|
|
407
|
+
}),
|
|
408
|
+
name: uaMetricName.meta({ description: "The name of the metric. For \"Custom metric\", any name for the column" }),
|
|
409
|
+
expression: zod.z.string().optional().meta({
|
|
410
|
+
title: "Expression",
|
|
411
|
+
description: "A metric expression, for example ga:totalRefunds/ga:users"
|
|
412
|
+
}),
|
|
413
|
+
formattingType: zod.z.enum([
|
|
414
|
+
"CURRENCY",
|
|
415
|
+
"FLOAT",
|
|
416
|
+
"INTEGER",
|
|
417
|
+
"PERCENT",
|
|
418
|
+
"TIME"
|
|
419
|
+
]).default("INTEGER").meta({
|
|
420
|
+
title: "Formatting Type",
|
|
421
|
+
description: "How the metric expression is formatted",
|
|
422
|
+
labels: {
|
|
423
|
+
CURRENCY: "Currency",
|
|
424
|
+
FLOAT: "Float",
|
|
425
|
+
INTEGER: "Integer",
|
|
426
|
+
PERCENT: "Percent",
|
|
427
|
+
TIME: "Time"
|
|
428
|
+
}
|
|
429
|
+
})
|
|
430
|
+
});
|
|
431
|
+
const uaDimension = zod.z.enum(valuesOf(UA_DIMENSIONS)).default("ga:date").meta({
|
|
432
|
+
title: "Dimension",
|
|
433
|
+
labels: labelsOf(UA_DIMENSIONS)
|
|
434
|
+
});
|
|
435
|
+
const uaDimensionItem = zod.z.object({
|
|
436
|
+
listName: uaDimension,
|
|
437
|
+
name: uaDimensionName
|
|
438
|
+
});
|
|
439
|
+
const uaDimensionFilter = zod.z.object({
|
|
440
|
+
listName: uaDimension,
|
|
441
|
+
name: uaDimensionName,
|
|
442
|
+
operator: zod.z.enum([
|
|
443
|
+
"BEGINS_WITH",
|
|
444
|
+
"ENDS_WITH",
|
|
445
|
+
"NUMERIC_EQUAL",
|
|
446
|
+
"EXACT",
|
|
447
|
+
"NUMERIC_GREATER_THAN",
|
|
448
|
+
"NUMERIC_LESS_THAN",
|
|
449
|
+
"PARTIAL",
|
|
450
|
+
"REGEXP"
|
|
451
|
+
]).default("EXACT").meta({
|
|
452
|
+
title: "Operator",
|
|
453
|
+
description: "Operator to use in combination with the value",
|
|
454
|
+
labels: {
|
|
455
|
+
BEGINS_WITH: "Begins With",
|
|
456
|
+
ENDS_WITH: "Ends With",
|
|
457
|
+
NUMERIC_EQUAL: "Equals (Number)",
|
|
458
|
+
EXACT: "Exactly Matches",
|
|
459
|
+
NUMERIC_GREATER_THAN: "Greater Than (Number)",
|
|
460
|
+
NUMERIC_LESS_THAN: "Less Than (Number)",
|
|
461
|
+
PARTIAL: "Partly Matches",
|
|
462
|
+
REGEXP: "Regular Expression"
|
|
463
|
+
}
|
|
464
|
+
}),
|
|
465
|
+
expressions: zod.z.string().default("").meta({
|
|
466
|
+
title: "Value",
|
|
467
|
+
description: "A string or a regular expression to match against"
|
|
468
|
+
})
|
|
469
|
+
});
|
|
470
|
+
const uaAdditionalFields = zod.z.object({
|
|
471
|
+
dimensionFiltersUi: zod.z.object({ filterValues: zod.z.array(uaDimensionFilter).default([]) }).optional().meta({
|
|
472
|
+
title: "Dimension Filters",
|
|
473
|
+
description: "Dimension filters in the request"
|
|
474
|
+
}),
|
|
475
|
+
hideTotals: zod.z.boolean().default(false).meta({
|
|
476
|
+
title: "Hide Totals",
|
|
477
|
+
description: "Hide the total of all metrics for all the matching rows, for every date range"
|
|
478
|
+
}),
|
|
479
|
+
hideValueRanges: zod.z.boolean().default(false).meta({
|
|
480
|
+
title: "Hide Value Ranges",
|
|
481
|
+
description: "Hide the minimum and the maximum across all matching rows"
|
|
482
|
+
}),
|
|
483
|
+
includeEmptyRows: zod.z.boolean().default(false).meta({
|
|
484
|
+
title: "Include Empty Rows",
|
|
485
|
+
description: "Return rows where all the metrics are equal to zero"
|
|
486
|
+
}),
|
|
487
|
+
useResourceQuotas: zod.z.boolean().default(false).meta({
|
|
488
|
+
title: "Use Resource Quotas",
|
|
489
|
+
description: "Turn on resource based quotas"
|
|
490
|
+
})
|
|
491
|
+
});
|
|
492
|
+
const report = (extra = {}) => ({
|
|
493
|
+
resource: ["report"],
|
|
494
|
+
operation: ["get"],
|
|
495
|
+
...extra
|
|
496
|
+
});
|
|
497
|
+
const GA4 = report({ propertyType: ["ga4"] });
|
|
498
|
+
const UNIVERSAL = report({ propertyType: ["universal"] });
|
|
499
|
+
const USER_ACTIVITY = {
|
|
500
|
+
resource: ["userActivity"],
|
|
501
|
+
operation: ["search"]
|
|
502
|
+
};
|
|
503
|
+
const analyticsConfig = zod.z.object({
|
|
504
|
+
resource: zod.z.enum(RESOURCES).default("report").meta({
|
|
505
|
+
labels: {
|
|
506
|
+
report: "Report",
|
|
507
|
+
userActivity: "User Activity"
|
|
508
|
+
},
|
|
509
|
+
hints: {
|
|
510
|
+
report: "Get the analytics data of a property or a view",
|
|
511
|
+
userActivity: "Get the activity of one user"
|
|
512
|
+
}
|
|
513
|
+
}),
|
|
514
|
+
operation: zod.z.enum(["get", "search"]).default("get").meta({
|
|
515
|
+
labels: {
|
|
516
|
+
get: "Get",
|
|
517
|
+
search: "Search"
|
|
518
|
+
},
|
|
519
|
+
hints: {
|
|
520
|
+
get: "Return the analytics data",
|
|
521
|
+
search: "Return user activity data"
|
|
522
|
+
}
|
|
523
|
+
}),
|
|
524
|
+
propertyType: zod.z.enum(PROPERTY_TYPES).default("ga4").meta({
|
|
525
|
+
showWhen: report(),
|
|
526
|
+
title: "Property Type",
|
|
527
|
+
description: "Google Analytics 4 is the latest version. Universal Analytics is an older version that is not fully functional after the end of June 2023",
|
|
528
|
+
labels: {
|
|
529
|
+
ga4: "Google Analytics 4",
|
|
530
|
+
universal: "Universal Analytics"
|
|
531
|
+
}
|
|
532
|
+
}),
|
|
533
|
+
propertyId: zod.z.string().optional().meta({
|
|
534
|
+
showWhen: GA4,
|
|
535
|
+
title: "Property",
|
|
536
|
+
description: "The ID of the property, for example 123456, or the URL of the property in Google Analytics",
|
|
537
|
+
loadOptions: "properties",
|
|
538
|
+
urlPattern: PROPERTY_URL_PATTERN
|
|
539
|
+
}),
|
|
540
|
+
viewId: zod.z.string().optional().meta({
|
|
541
|
+
showWhen: [UNIVERSAL, USER_ACTIVITY],
|
|
542
|
+
title: "View",
|
|
543
|
+
description: "The ID of the view, for example 123456. For a report, the URL of the view in Google Analytics also works",
|
|
544
|
+
loadOptions: "views",
|
|
545
|
+
urlPattern: VIEW_URL_PATTERN
|
|
546
|
+
}),
|
|
547
|
+
userId: zod.z.string().optional().meta({
|
|
548
|
+
showWhen: USER_ACTIVITY,
|
|
549
|
+
title: "User ID",
|
|
550
|
+
description: "ID of a user"
|
|
551
|
+
}),
|
|
552
|
+
dateRange: zod.z.enum(DATE_RANGES).default("last7days").meta({
|
|
553
|
+
showWhen: report(),
|
|
554
|
+
title: "Date Range",
|
|
555
|
+
labels: {
|
|
556
|
+
last7days: "Last 7 Days",
|
|
557
|
+
last30days: "Last 30 Days",
|
|
558
|
+
today: "Today",
|
|
559
|
+
yesterday: "Yesterday",
|
|
560
|
+
lastCalendarWeek: "Last Complete Calendar Week",
|
|
561
|
+
lastCalendarMonth: "Last Complete Calendar Month",
|
|
562
|
+
custom: "Custom"
|
|
563
|
+
}
|
|
564
|
+
}),
|
|
565
|
+
startDate: zod.z.string().optional().meta({
|
|
566
|
+
showWhen: report({ dateRange: ["custom"] }),
|
|
567
|
+
title: "Start",
|
|
568
|
+
description: "A date in ISO 8601 format, for example 2026-01-31"
|
|
569
|
+
}),
|
|
570
|
+
endDate: zod.z.string().optional().meta({
|
|
571
|
+
showWhen: report({ dateRange: ["custom"] }),
|
|
572
|
+
title: "End",
|
|
573
|
+
description: "A date in ISO 8601 format, for example 2026-02-28"
|
|
574
|
+
}),
|
|
575
|
+
metricsGA4: zod.z.object({ metricValues: zod.z.array(ga4MetricItem).default([]) }).default({ metricValues: [{
|
|
576
|
+
listName: "totalUsers",
|
|
577
|
+
invisible: false
|
|
578
|
+
}] }).meta({
|
|
579
|
+
showWhen: GA4,
|
|
580
|
+
title: "Metrics",
|
|
581
|
+
description: "The quantitative measurements of a report. For example, the metric eventCount is the total number of events. A request allows up to 10 metrics"
|
|
582
|
+
}),
|
|
583
|
+
dimensionsGA4: zod.z.object({ dimensionValues: zod.z.array(ga4DimensionItem).default([]) }).default({ dimensionValues: [{ listName: "date" }] }).meta({
|
|
584
|
+
showWhen: GA4,
|
|
585
|
+
title: "Dimensions to split by",
|
|
586
|
+
description: "Dimensions are attributes of your data. For example, the dimension city is the city from which an event comes. A request allows up to 9 dimensions"
|
|
587
|
+
}),
|
|
588
|
+
metricsUA: zod.z.object({ metricValues: zod.z.array(uaMetricItem).default([]) }).default({ metricValues: [{
|
|
589
|
+
listName: "ga:users",
|
|
590
|
+
formattingType: "INTEGER"
|
|
591
|
+
}] }).meta({
|
|
592
|
+
showWhen: UNIVERSAL,
|
|
593
|
+
title: "Metrics",
|
|
594
|
+
description: "Metrics in the request"
|
|
595
|
+
}),
|
|
596
|
+
dimensionsUA: zod.z.object({ dimensionValues: zod.z.array(uaDimensionItem).default([]) }).default({ dimensionValues: [{ listName: "ga:date" }] }).meta({
|
|
597
|
+
showWhen: UNIVERSAL,
|
|
598
|
+
title: "Dimensions to split by",
|
|
599
|
+
description: "Dimensions are attributes of your data. For example, the dimension ga:city is the city, for example \"Paris\", from which a session comes"
|
|
600
|
+
}),
|
|
601
|
+
returnAll: zod.z.boolean().default(false).meta({
|
|
602
|
+
showWhen: [report(), USER_ACTIVITY],
|
|
603
|
+
title: "Return All",
|
|
604
|
+
description: "Whether to return all results or only up to a given limit"
|
|
605
|
+
}),
|
|
606
|
+
limit: zod.z.number().int().min(1).max(1e3).default(50).meta({
|
|
607
|
+
showWhen: [report({ returnAll: [false] }), {
|
|
608
|
+
...USER_ACTIVITY,
|
|
609
|
+
returnAll: [false]
|
|
610
|
+
}],
|
|
611
|
+
title: "Limit",
|
|
612
|
+
description: "Max number of results to return. User activity allows up to 500"
|
|
613
|
+
}),
|
|
614
|
+
simple: zod.z.boolean().default(true).meta({
|
|
615
|
+
showWhen: report(),
|
|
616
|
+
title: "Simplify Output",
|
|
617
|
+
description: "Whether to return a simplified version of the response instead of the raw data"
|
|
618
|
+
}),
|
|
619
|
+
additionalFields: ga4AdditionalFields.default({
|
|
620
|
+
keepEmptyRows: false,
|
|
621
|
+
returnPropertyQuota: false,
|
|
622
|
+
metricAggregations: []
|
|
623
|
+
}).meta({
|
|
624
|
+
showWhen: GA4,
|
|
625
|
+
title: "Additional Fields",
|
|
626
|
+
ui: "collection"
|
|
627
|
+
}),
|
|
628
|
+
additionalFieldsUA: uaAdditionalFields.default({
|
|
629
|
+
hideTotals: false,
|
|
630
|
+
hideValueRanges: false,
|
|
631
|
+
includeEmptyRows: false,
|
|
632
|
+
useResourceQuotas: false
|
|
633
|
+
}).meta({
|
|
634
|
+
showWhen: UNIVERSAL,
|
|
635
|
+
title: "Additional Fields",
|
|
636
|
+
ui: "collection"
|
|
637
|
+
}),
|
|
638
|
+
activityTypes: zod.z.array(zod.z.enum(ACTIVITY_TYPES)).default([]).meta({
|
|
639
|
+
showWhen: USER_ACTIVITY,
|
|
640
|
+
title: "Activity Types",
|
|
641
|
+
description: "Type of activities requested",
|
|
642
|
+
labels: {
|
|
643
|
+
ECOMMERCE: "Ecommerce",
|
|
644
|
+
EVENT: "Event",
|
|
645
|
+
GOAL: "Goal",
|
|
646
|
+
PAGEVIEW: "Pageview",
|
|
647
|
+
SCREENVIEW: "Screenview"
|
|
648
|
+
}
|
|
649
|
+
}),
|
|
650
|
+
timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
|
|
651
|
+
}).superRefine((config, context) => {
|
|
652
|
+
if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
|
|
653
|
+
code: "custom",
|
|
654
|
+
path: ["operation"],
|
|
655
|
+
message: `"${config.operation}" is not an operation of "${config.resource}"`
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
// src/request.ts
|
|
659
|
+
const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
660
|
+
const asList$1 = (value) => Array.isArray(value) ? value : [];
|
|
661
|
+
const records$1 = (value) => asList$1(value).filter(isRecord$2);
|
|
662
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
663
|
+
/** The ID of a GA4 property, from its URL, `properties/123`, or the bare number. */
|
|
664
|
+
function parsePropertyId(input) {
|
|
665
|
+
const value = (input ?? "").trim();
|
|
666
|
+
if (!value) throw new Error("\"propertyId\" is needed: the ID or the URL of the property");
|
|
667
|
+
const fromUrl = /analytics\.google\.com\/analytics.*\/p(\d+)/.exec(value)?.[1];
|
|
668
|
+
if (fromUrl) return fromUrl;
|
|
669
|
+
const fromName = /^properties\/(\d+)$/.exec(value)?.[1];
|
|
670
|
+
if (fromName) return fromName;
|
|
671
|
+
if (/^\d+$/.test(value)) return value;
|
|
672
|
+
throw new Error(`"${value}" is not a Google Analytics property ID or URL`);
|
|
673
|
+
}
|
|
674
|
+
/** The ID of a Universal Analytics view, from its URL or the bare number. */
|
|
675
|
+
function parseViewId(input) {
|
|
676
|
+
const value = (input ?? "").trim();
|
|
677
|
+
if (!value) throw new Error("\"viewId\" is needed: the ID of the view");
|
|
678
|
+
const fromUrl = /analytics\.google\.com\/analytics.*p(\d+)/.exec(value)?.[1];
|
|
679
|
+
if (fromUrl) return fromUrl;
|
|
680
|
+
if (/^\d+$/.test(value)) return value;
|
|
681
|
+
throw new Error(`"${value}" is not a Google Analytics view ID or URL`);
|
|
682
|
+
}
|
|
683
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
684
|
+
const isoDate = (date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
685
|
+
const addDays = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
|
|
686
|
+
/** A date as `YYYY-MM-DD`. A date with a time keeps its date part. */
|
|
687
|
+
function dateOf(value, name) {
|
|
688
|
+
const text = (value ?? "").trim();
|
|
689
|
+
const match = /^(\d{4}-\d{2}-\d{2})/.exec(text);
|
|
690
|
+
if (match?.[1]) return match[1];
|
|
691
|
+
const parsed = new Date(text);
|
|
692
|
+
if (!text || Number.isNaN(parsed.getTime())) throw new Error(`"${name}" is needed for a custom date range, as a date like 2026-01-31`);
|
|
693
|
+
return isoDate(parsed);
|
|
694
|
+
}
|
|
695
|
+
/** The date range of a period, in local time. Weeks start on Monday. */
|
|
696
|
+
function prepareDateRange(period, custom = {}, now = /* @__PURE__ */ new Date()) {
|
|
697
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
698
|
+
switch (period) {
|
|
699
|
+
case "today": return [{
|
|
700
|
+
startDate: isoDate(today),
|
|
701
|
+
endDate: isoDate(today)
|
|
702
|
+
}];
|
|
703
|
+
case "yesterday": {
|
|
704
|
+
const day = isoDate(addDays(today, -1));
|
|
705
|
+
return [{
|
|
706
|
+
startDate: day,
|
|
707
|
+
endDate: day
|
|
708
|
+
}];
|
|
709
|
+
}
|
|
710
|
+
case "lastCalendarWeek": {
|
|
711
|
+
const monday = addDays(today, -((today.getDay() + 6) % 7));
|
|
712
|
+
return [{
|
|
713
|
+
startDate: isoDate(addDays(monday, -7)),
|
|
714
|
+
endDate: isoDate(addDays(monday, -1))
|
|
715
|
+
}];
|
|
716
|
+
}
|
|
717
|
+
case "lastCalendarMonth": {
|
|
718
|
+
const first = new Date(today.getFullYear(), today.getMonth() - 1, 1);
|
|
719
|
+
const last = new Date(today.getFullYear(), today.getMonth(), 0);
|
|
720
|
+
return [{
|
|
721
|
+
startDate: isoDate(first),
|
|
722
|
+
endDate: isoDate(last)
|
|
723
|
+
}];
|
|
724
|
+
}
|
|
725
|
+
case "last7days": return [{
|
|
726
|
+
startDate: isoDate(addDays(today, -7)),
|
|
727
|
+
endDate: isoDate(today)
|
|
728
|
+
}];
|
|
729
|
+
case "last30days": return [{
|
|
730
|
+
startDate: isoDate(addDays(today, -30)),
|
|
731
|
+
endDate: isoDate(today)
|
|
732
|
+
}];
|
|
733
|
+
case "custom": {
|
|
734
|
+
const startDate = dateOf(custom.startDate, "startDate");
|
|
735
|
+
const endDate = dateOf(custom.endDate, "endDate");
|
|
736
|
+
if (startDate > endDate) throw new Error(`Parameter Start: ${startDate} cannot be after End: ${endDate}`);
|
|
737
|
+
return [{
|
|
738
|
+
startDate,
|
|
739
|
+
endDate
|
|
740
|
+
}];
|
|
741
|
+
}
|
|
742
|
+
default: throw new Error(`The period '${period}' is not supported, to specify own period use 'custom' option`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
/** Throws when a name is in the list more than once. */
|
|
746
|
+
function checkDuplicates(items, key, type) {
|
|
747
|
+
const names = items.map((item) => String(item[key]));
|
|
748
|
+
const duplicates = [...new Set(names.filter((name, i) => names.indexOf(name) !== i))];
|
|
749
|
+
if (duplicates.length > 0) throw new Error(`A ${type} is specified more than once (${duplicates.join(", ")})`);
|
|
750
|
+
}
|
|
751
|
+
/** The API name of a list entry. "other" (and "custom") use the free name field. */
|
|
752
|
+
function nameOf(item, kind) {
|
|
753
|
+
const listName = str(item.listName);
|
|
754
|
+
if (listName === "other") {
|
|
755
|
+
const name = str(item.name).trim();
|
|
756
|
+
if (!name) throw new Error(`"name" is needed when the ${kind} is "Other"`);
|
|
757
|
+
return name;
|
|
758
|
+
}
|
|
759
|
+
return listName;
|
|
760
|
+
}
|
|
761
|
+
/** A number for a filter. `doubleValue` is a JSON number, `int64Value` stays a string. */
|
|
762
|
+
const numberValue = (type, value) => {
|
|
763
|
+
const text = str(value).trim();
|
|
764
|
+
if (type === "doubleValue") {
|
|
765
|
+
const number = Number(text);
|
|
766
|
+
if (text === "" || !Number.isFinite(number)) throw new Error(`"${text}" is not a number`);
|
|
767
|
+
return { doubleValue: number };
|
|
768
|
+
}
|
|
769
|
+
if (!/^-?\d+$/.test(text)) throw new Error(`"${text}" is not an integer`);
|
|
770
|
+
return { int64Value: text };
|
|
771
|
+
};
|
|
772
|
+
/** One filter entry, with the field name and the kind of filter. */
|
|
773
|
+
function fieldOf(item, kind) {
|
|
774
|
+
const listName = str(item.listName);
|
|
775
|
+
if (listName === "other" || listName === "custom") {
|
|
776
|
+
const name = str(item.name).trim();
|
|
777
|
+
if (!name) throw new Error(`"name" is needed when the ${kind} is "${listName}"`);
|
|
778
|
+
return name;
|
|
779
|
+
}
|
|
780
|
+
return listName;
|
|
781
|
+
}
|
|
782
|
+
/** The filter entries of a group, in the form of the API. */
|
|
783
|
+
function processFilters(expression, source) {
|
|
784
|
+
const out = [];
|
|
785
|
+
for (const item of records$1(expression.stringFilter)) out.push({ filter: {
|
|
786
|
+
fieldName: fieldOf(item, source),
|
|
787
|
+
stringFilter: {
|
|
788
|
+
value: str(item.value),
|
|
789
|
+
caseSensitive: item.caseSensitive,
|
|
790
|
+
matchType: item.matchType
|
|
791
|
+
}
|
|
792
|
+
} });
|
|
793
|
+
for (const item of records$1(expression.inListFilter)) out.push({ filter: {
|
|
794
|
+
fieldName: fieldOf(item, source),
|
|
795
|
+
inListFilter: {
|
|
796
|
+
values: str(item.values).split(",").map((value) => value.trim()).filter((value) => value !== ""),
|
|
797
|
+
caseSensitive: item.caseSensitive
|
|
798
|
+
}
|
|
799
|
+
} });
|
|
800
|
+
for (const item of records$1(expression.betweenFilter)) {
|
|
801
|
+
const type = str(item.valueType);
|
|
802
|
+
out.push({ filter: {
|
|
803
|
+
fieldName: fieldOf(item, source),
|
|
804
|
+
betweenFilter: {
|
|
805
|
+
fromValue: numberValue(type, item.fromValue),
|
|
806
|
+
toValue: numberValue(type, item.toValue)
|
|
807
|
+
}
|
|
808
|
+
} });
|
|
809
|
+
}
|
|
810
|
+
for (const item of records$1(expression.numericFilter)) out.push({ filter: {
|
|
811
|
+
fieldName: fieldOf(item, source),
|
|
812
|
+
numericFilter: {
|
|
813
|
+
operation: item.operation,
|
|
814
|
+
value: numberValue(str(item.valueType), item.value)
|
|
815
|
+
}
|
|
816
|
+
} });
|
|
817
|
+
return out;
|
|
818
|
+
}
|
|
819
|
+
/** A filter group: `{ andGroup: { expressions } }`. Empty gives undefined. */
|
|
820
|
+
function filterGroup(ui, source) {
|
|
821
|
+
const group = isRecord$2(ui) && isRecord$2(ui.filterExpressions) ? ui.filterExpressions : void 0;
|
|
822
|
+
if (!group || !isRecord$2(group.expression)) return void 0;
|
|
823
|
+
const expressions = processFilters(group.expression, source);
|
|
824
|
+
if (expressions.length === 0) return void 0;
|
|
825
|
+
return { [str(group.filterExpressionType) || "andGroup"]: { expressions } };
|
|
826
|
+
}
|
|
827
|
+
function ga4Metrics$1(collection) {
|
|
828
|
+
const metrics = records$1(isRecord$2(collection) ? collection.metricValues : []).map((metric) => {
|
|
829
|
+
switch (metric.listName) {
|
|
830
|
+
case "other": return { name: nameOf(metric, "metric") };
|
|
831
|
+
case "custom": {
|
|
832
|
+
const out = { name: str(metric.name).trim() || "custom_metric" };
|
|
833
|
+
if (str(metric.expression) !== "") out.expression = metric.expression;
|
|
834
|
+
if (metric.invisible === true) out.invisible = true;
|
|
835
|
+
return out;
|
|
836
|
+
}
|
|
837
|
+
default: return { name: metric.listName };
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
checkDuplicates(metrics, "name", "metrics");
|
|
841
|
+
return metrics;
|
|
842
|
+
}
|
|
843
|
+
function ga4Dimensions$1(collection) {
|
|
844
|
+
const dimensions = records$1(isRecord$2(collection) ? collection.dimensionValues : []).map((dimension) => ({ name: nameOf(dimension, "dimension") }));
|
|
845
|
+
checkDuplicates(dimensions, "name", "dimensions");
|
|
846
|
+
return dimensions;
|
|
847
|
+
}
|
|
848
|
+
function orderBys(ui) {
|
|
849
|
+
if (!isRecord$2(ui)) return [];
|
|
850
|
+
return [...records$1(ui.metricOrderBy).map((order) => ({
|
|
851
|
+
desc: order.desc,
|
|
852
|
+
metric: { metricName: order.metricName }
|
|
853
|
+
})), ...records$1(ui.dimmensionOrderBy).map((order) => ({
|
|
854
|
+
desc: order.desc,
|
|
855
|
+
dimension: {
|
|
856
|
+
dimensionName: order.dimensionName,
|
|
857
|
+
orderType: order.orderType
|
|
858
|
+
}
|
|
859
|
+
}))];
|
|
860
|
+
}
|
|
861
|
+
/** The body of `runReport`, without `limit` and `offset`. */
|
|
862
|
+
function ga4Body(config, dateRanges) {
|
|
863
|
+
const fields = config.additionalFields;
|
|
864
|
+
const body = { dateRanges };
|
|
865
|
+
const metrics = ga4Metrics$1(config.metricsGA4);
|
|
866
|
+
if (metrics.length > 0) body.metrics = metrics;
|
|
867
|
+
const dimensions = ga4Dimensions$1(config.dimensionsGA4);
|
|
868
|
+
if (dimensions.length > 0) body.dimensions = dimensions;
|
|
869
|
+
if (fields.currencyCode) body.currencyCode = fields.currencyCode;
|
|
870
|
+
const dimensionFilter = filterGroup(fields.dimensionFiltersUI, "dimension");
|
|
871
|
+
if (dimensionFilter) body.dimensionFilter = dimensionFilter;
|
|
872
|
+
const metricFilter = filterGroup(fields.metricsFiltersUI, "metric");
|
|
873
|
+
if (metricFilter) body.metricFilter = metricFilter;
|
|
874
|
+
if (fields.metricAggregations.length > 0) body.metricAggregations = fields.metricAggregations;
|
|
875
|
+
if (fields.keepEmptyRows) body.keepEmptyRows = true;
|
|
876
|
+
const order = orderBys(fields.orderByUI);
|
|
877
|
+
if (order.length > 0) body.orderBys = order;
|
|
878
|
+
if (fields.returnPropertyQuota) body.returnPropertyQuota = true;
|
|
879
|
+
return body;
|
|
880
|
+
}
|
|
881
|
+
const runReportRequest = (propertyId, body) => ({
|
|
882
|
+
api: "data",
|
|
883
|
+
method: "POST",
|
|
884
|
+
path: `/v1beta/properties/${encodeURIComponent(propertyId)}:runReport`,
|
|
885
|
+
body,
|
|
886
|
+
action: "get the report"
|
|
887
|
+
});
|
|
888
|
+
/** The rows of a `runReport` answer as flat objects: dimension and metric names are the keys. */
|
|
889
|
+
function simplifyGA4(response) {
|
|
890
|
+
if (!isRecord$2(response) || !Array.isArray(response.rows)) return [];
|
|
891
|
+
const dimensionNames = records$1(response.dimensionHeaders).map((header) => str(header.name));
|
|
892
|
+
const metricNames = records$1(response.metricHeaders).map((header) => str(header.name));
|
|
893
|
+
const out = [];
|
|
894
|
+
for (const row of records$1(response.rows)) {
|
|
895
|
+
const dimensionValues = records$1(row.dimensionValues);
|
|
896
|
+
const metricValues = records$1(row.metricValues);
|
|
897
|
+
const item = {};
|
|
898
|
+
dimensionNames.forEach((name, index) => {
|
|
899
|
+
item[name] = dimensionValues[index]?.value;
|
|
900
|
+
});
|
|
901
|
+
metricNames.forEach((name, index) => {
|
|
902
|
+
item[name] = metricValues[index]?.value;
|
|
903
|
+
});
|
|
904
|
+
out.push(item);
|
|
905
|
+
}
|
|
906
|
+
return out;
|
|
907
|
+
}
|
|
908
|
+
function uaMetrics$1(collection) {
|
|
909
|
+
const metrics = records$1(isRecord$2(collection) ? collection.metricValues : []).map((metric) => {
|
|
910
|
+
switch (metric.listName) {
|
|
911
|
+
case "other": {
|
|
912
|
+
const name = nameOf(metric, "metric");
|
|
913
|
+
return {
|
|
914
|
+
alias: name,
|
|
915
|
+
expression: name
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
case "custom": return {
|
|
919
|
+
alias: str(metric.name).trim() || "custom_metric",
|
|
920
|
+
expression: metric.expression,
|
|
921
|
+
formattingType: metric.formattingType
|
|
922
|
+
};
|
|
923
|
+
default: return {
|
|
924
|
+
alias: metric.listName,
|
|
925
|
+
expression: metric.listName
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
});
|
|
929
|
+
checkDuplicates(metrics, "alias", "metrics");
|
|
930
|
+
return metrics;
|
|
931
|
+
}
|
|
932
|
+
/** The body of one report request of `reports:batchGet`, without `pageSize` and `pageToken`. */
|
|
933
|
+
function uaBody(config, dateRanges) {
|
|
934
|
+
const fields = config.additionalFieldsUA;
|
|
935
|
+
const body = {
|
|
936
|
+
viewId: parseViewId(config.viewId),
|
|
937
|
+
dateRanges
|
|
938
|
+
};
|
|
939
|
+
const metrics = uaMetrics$1(config.metricsUA);
|
|
940
|
+
if (metrics.length > 0) body.metrics = metrics;
|
|
941
|
+
const dimensions = records$1(isRecord$2(config.dimensionsUA) ? config.dimensionsUA.dimensionValues : []).map((dimension) => ({ name: nameOf(dimension, "dimension") }));
|
|
942
|
+
checkDuplicates(dimensions, "name", "dimensions");
|
|
943
|
+
if (dimensions.length > 0) body.dimensions = dimensions;
|
|
944
|
+
const filters = records$1(fields.dimensionFiltersUi?.filterValues).map((filter) => ({
|
|
945
|
+
dimensionName: nameOf(filter, "dimension"),
|
|
946
|
+
operator: filter.operator,
|
|
947
|
+
expressions: [filter.expressions]
|
|
948
|
+
}));
|
|
949
|
+
if (filters.length > 0) body.dimensionFilterClauses = [{ filters }];
|
|
950
|
+
if (fields.includeEmptyRows) body.includeEmptyRows = true;
|
|
951
|
+
if (fields.hideTotals) body.hideTotals = true;
|
|
952
|
+
if (fields.hideValueRanges) body.hideValueRanges = true;
|
|
953
|
+
return body;
|
|
954
|
+
}
|
|
955
|
+
const batchGetRequest = (reportRequest, useResourceQuotas) => ({
|
|
956
|
+
api: "reporting",
|
|
957
|
+
method: "POST",
|
|
958
|
+
path: "/v4/reports:batchGet",
|
|
959
|
+
query: { useResourceQuotas: useResourceQuotas ? "true" : void 0 },
|
|
960
|
+
body: { reportRequests: [reportRequest] },
|
|
961
|
+
action: "get the report"
|
|
962
|
+
});
|
|
963
|
+
/** The rows of the reports as flat objects. A report with no rows gives nothing. */
|
|
964
|
+
function simplifyUA(reports) {
|
|
965
|
+
const out = [];
|
|
966
|
+
for (const report of records$1(reports)) {
|
|
967
|
+
const header = isRecord$2(report.columnHeader) ? report.columnHeader : {};
|
|
968
|
+
const data = isRecord$2(report.data) ? report.data : {};
|
|
969
|
+
if (!Array.isArray(data.rows)) continue;
|
|
970
|
+
const dimensions = asList$1(header.dimensions).map(str);
|
|
971
|
+
const metricHeader = isRecord$2(header.metricHeader) ? header.metricHeader : {};
|
|
972
|
+
const metrics = records$1(metricHeader.metricHeaderEntries).map((entry) => str(entry.name));
|
|
973
|
+
for (const row of records$1(data.rows)) {
|
|
974
|
+
const item = {};
|
|
975
|
+
const rowDimensions = asList$1(row.dimensions);
|
|
976
|
+
dimensions.forEach((name, index) => {
|
|
977
|
+
item[name] = rowDimensions[index];
|
|
978
|
+
});
|
|
979
|
+
const firstMetrics = records$1(row.metrics)[0];
|
|
980
|
+
const values = asList$1(firstMetrics?.values);
|
|
981
|
+
metrics.forEach((name, index) => {
|
|
982
|
+
item[name] = values[index];
|
|
983
|
+
});
|
|
984
|
+
out.push(item);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return out;
|
|
988
|
+
}
|
|
989
|
+
/** One report with the rows of all the reports. */
|
|
990
|
+
function mergeUA(reports) {
|
|
991
|
+
const list = records$1(reports);
|
|
992
|
+
const first = list[0];
|
|
993
|
+
if (!first) return [];
|
|
994
|
+
const data = isRecord$2(first.data) ? first.data : {};
|
|
995
|
+
const rows = list.flatMap((report) => isRecord$2(report.data) ? asList$1(report.data.rows) : []);
|
|
996
|
+
return [{
|
|
997
|
+
columnHeader: first.columnHeader,
|
|
998
|
+
data: {
|
|
999
|
+
...data,
|
|
1000
|
+
rows
|
|
1001
|
+
}
|
|
1002
|
+
}];
|
|
1003
|
+
}
|
|
1004
|
+
function userActivityBody(config) {
|
|
1005
|
+
const userId = (config.userId ?? "").trim();
|
|
1006
|
+
if (!userId) throw new Error("\"userId\" is needed to search user activity");
|
|
1007
|
+
const body = {
|
|
1008
|
+
viewId: parseViewId(config.viewId),
|
|
1009
|
+
user: { userId }
|
|
1010
|
+
};
|
|
1011
|
+
if (config.activityTypes.length > 0) body.activityTypes = config.activityTypes;
|
|
1012
|
+
return body;
|
|
1013
|
+
}
|
|
1014
|
+
const userActivityRequest = (body) => ({
|
|
1015
|
+
api: "reporting",
|
|
1016
|
+
method: "POST",
|
|
1017
|
+
path: "/v4/userActivity:search",
|
|
1018
|
+
body,
|
|
1019
|
+
action: "search the user activity"
|
|
1020
|
+
});
|
|
1021
|
+
// src/loaders.ts
|
|
1022
|
+
const LOAD_TIMEOUT_MS = 2e4;
|
|
1023
|
+
/** The most pages of one list, so a loop never runs for ever. */
|
|
1024
|
+
const MAX_PAGES$1 = 50;
|
|
1025
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1026
|
+
const records = (value) => Array.isArray(value) ? value.filter(isRecord$1) : [];
|
|
1027
|
+
const text = (value) => typeof value === "string" ? value : "";
|
|
1028
|
+
const get = async (context, api, path, query = {}) => {
|
|
1029
|
+
const answer = await callAnalytics(analyticsToken(context.credential), {
|
|
1030
|
+
api,
|
|
1031
|
+
method: "GET",
|
|
1032
|
+
path,
|
|
1033
|
+
query,
|
|
1034
|
+
action: "load the options"
|
|
1035
|
+
}, {
|
|
1036
|
+
signal: context.signal,
|
|
1037
|
+
timeoutMs: LOAD_TIMEOUT_MS
|
|
1038
|
+
});
|
|
1039
|
+
return isRecord$1(answer) ? answer : {};
|
|
1040
|
+
};
|
|
1041
|
+
/** Sort by label, as the lists of the app do. Not by case. */
|
|
1042
|
+
const sortOptions = (options) => [...options].sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase()));
|
|
1043
|
+
/** The GA4 properties of all accounts: the Admin API account summaries. */
|
|
1044
|
+
async function properties(context) {
|
|
1045
|
+
const options = [];
|
|
1046
|
+
let pageToken;
|
|
1047
|
+
for (let page = 0; page < MAX_PAGES$1; page++) {
|
|
1048
|
+
const answer = await get(context, "admin", "/v1beta/accountSummaries", {
|
|
1049
|
+
pageSize: "200",
|
|
1050
|
+
pageToken
|
|
1051
|
+
});
|
|
1052
|
+
for (const account of records(answer.accountSummaries)) for (const property of records(account.propertySummaries)) {
|
|
1053
|
+
const name = text(property.property);
|
|
1054
|
+
const value = name.split("/")[1] || name;
|
|
1055
|
+
if (!value) continue;
|
|
1056
|
+
options.push({
|
|
1057
|
+
label: text(property.displayName) || value,
|
|
1058
|
+
value,
|
|
1059
|
+
description: text(account.displayName) || void 0
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
pageToken = text(answer.nextPageToken) || void 0;
|
|
1063
|
+
if (!pageToken) break;
|
|
1064
|
+
}
|
|
1065
|
+
return sortOptions(options);
|
|
1066
|
+
}
|
|
1067
|
+
/** The Universal Analytics views of all accounts. */
|
|
1068
|
+
async function views(context) {
|
|
1069
|
+
const answer = await get(context, "legacy", "/analytics/v3/management/accounts/~all/webproperties/~all/profiles");
|
|
1070
|
+
return sortOptions(records(answer.items).map((item) => ({
|
|
1071
|
+
label: text(item.name),
|
|
1072
|
+
value: text(item.id),
|
|
1073
|
+
description: text(item.websiteUrl) || void 0
|
|
1074
|
+
})));
|
|
1075
|
+
}
|
|
1076
|
+
/** The property of the editor. The loader does not run while it is empty. */
|
|
1077
|
+
const propertyOf = (context) => {
|
|
1078
|
+
const value = context.config.propertyId;
|
|
1079
|
+
return parsePropertyId(typeof value === "string" ? value : void 0);
|
|
1080
|
+
};
|
|
1081
|
+
async function ga4Metadata(context, field) {
|
|
1082
|
+
const answer = await get(context, "data", `/v1beta/properties/${encodeURIComponent(propertyOf(context))}/metadata`, { fields: field });
|
|
1083
|
+
return sortOptions(records(answer[field]).map((item) => ({
|
|
1084
|
+
label: text(item.uiName),
|
|
1085
|
+
value: text(item.apiName),
|
|
1086
|
+
description: text(item.description) || void 0
|
|
1087
|
+
})));
|
|
1088
|
+
}
|
|
1089
|
+
const ga4Metrics = (context) => ga4Metadata(context, "metrics");
|
|
1090
|
+
const ga4Dimensions = (context) => ga4Metadata(context, "dimensions");
|
|
1091
|
+
/** The columns of Universal Analytics. A deprecated column is left out. */
|
|
1092
|
+
async function uaColumns(context, type) {
|
|
1093
|
+
const answer = await get(context, "legacy", "/analytics/v3/metadata/ga/columns");
|
|
1094
|
+
const options = [];
|
|
1095
|
+
for (const item of records(answer.items)) {
|
|
1096
|
+
const attributes = isRecord$1(item.attributes) ? item.attributes : {};
|
|
1097
|
+
if (attributes.type !== type || attributes.status === "DEPRECATED") continue;
|
|
1098
|
+
options.push({
|
|
1099
|
+
label: text(attributes.uiName),
|
|
1100
|
+
value: text(item.id),
|
|
1101
|
+
description: text(attributes.description) || void 0
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
return sortOptions(options);
|
|
1105
|
+
}
|
|
1106
|
+
const uaMetrics = (context) => uaColumns(context, "METRIC");
|
|
1107
|
+
const uaDimensions = (context) => uaColumns(context, "DIMENSION");
|
|
1108
|
+
// src/node.ts
|
|
1109
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1110
|
+
const asList = (value) => Array.isArray(value) ? value : [];
|
|
1111
|
+
/** The most pages of one Return All, so a loop never runs for ever. */
|
|
1112
|
+
const MAX_PAGES = 1e3;
|
|
1113
|
+
const dateRangeOf = (config) => prepareDateRange(config.dateRange, {
|
|
1114
|
+
startDate: config.startDate,
|
|
1115
|
+
endDate: config.endDate
|
|
1116
|
+
});
|
|
1117
|
+
/** A report of Google Analytics 4. */
|
|
1118
|
+
async function ga4Report(call, config) {
|
|
1119
|
+
const propertyId = parsePropertyId(config.propertyId);
|
|
1120
|
+
const body = ga4Body(config, dateRangeOf(config));
|
|
1121
|
+
let response;
|
|
1122
|
+
if (config.returnAll) {
|
|
1123
|
+
const first = await call(runReportRequest(propertyId, {
|
|
1124
|
+
...body,
|
|
1125
|
+
limit: GA4_PAGE_SIZE,
|
|
1126
|
+
offset: 0
|
|
1127
|
+
}));
|
|
1128
|
+
response = isRecord(first) ? first : {};
|
|
1129
|
+
const rows = asList(response.rows);
|
|
1130
|
+
const total = typeof response.rowCount === "number" ? response.rowCount : rows.length;
|
|
1131
|
+
for (let page = 1; total > rows.length && page < MAX_PAGES; page++) {
|
|
1132
|
+
const next = await call(runReportRequest(propertyId, {
|
|
1133
|
+
...body,
|
|
1134
|
+
limit: GA4_PAGE_SIZE,
|
|
1135
|
+
offset: rows.length
|
|
1136
|
+
}));
|
|
1137
|
+
const more = isRecord(next) ? asList(next.rows) : [];
|
|
1138
|
+
if (more.length === 0) break;
|
|
1139
|
+
rows.push(...more);
|
|
1140
|
+
}
|
|
1141
|
+
response = {
|
|
1142
|
+
...response,
|
|
1143
|
+
rows
|
|
1144
|
+
};
|
|
1145
|
+
} else {
|
|
1146
|
+
const answer = await call(runReportRequest(propertyId, {
|
|
1147
|
+
...body,
|
|
1148
|
+
limit: config.limit
|
|
1149
|
+
}));
|
|
1150
|
+
response = isRecord(answer) ? answer : {};
|
|
1151
|
+
}
|
|
1152
|
+
return config.simple ? simplifyGA4(response) : response;
|
|
1153
|
+
}
|
|
1154
|
+
/** A report of Universal Analytics. */
|
|
1155
|
+
async function universalReport(call, config) {
|
|
1156
|
+
const body = uaBody(config, dateRangeOf(config));
|
|
1157
|
+
const quotas = config.additionalFieldsUA.useResourceQuotas;
|
|
1158
|
+
let reports = [];
|
|
1159
|
+
if (config.returnAll) {
|
|
1160
|
+
let pageToken;
|
|
1161
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
1162
|
+
const answer = await call(batchGetRequest(pageToken ? {
|
|
1163
|
+
...body,
|
|
1164
|
+
pageToken
|
|
1165
|
+
} : body, quotas));
|
|
1166
|
+
const pageReports = isRecord(answer) ? asList(answer.reports) : [];
|
|
1167
|
+
reports.push(...pageReports);
|
|
1168
|
+
const token = isRecord(pageReports[0]) ? pageReports[0].nextPageToken : void 0;
|
|
1169
|
+
pageToken = typeof token === "string" && token !== "" ? token : void 0;
|
|
1170
|
+
if (!pageToken) break;
|
|
1171
|
+
}
|
|
1172
|
+
} else {
|
|
1173
|
+
const answer = await call(batchGetRequest({
|
|
1174
|
+
...body,
|
|
1175
|
+
pageSize: config.limit
|
|
1176
|
+
}, quotas));
|
|
1177
|
+
reports = isRecord(answer) ? asList(answer.reports) : [];
|
|
1178
|
+
}
|
|
1179
|
+
if (config.simple) return simplifyUA(reports);
|
|
1180
|
+
return config.returnAll && reports.length > 1 ? mergeUA(reports) : reports;
|
|
1181
|
+
}
|
|
1182
|
+
/** The sessions of one user. */
|
|
1183
|
+
async function userActivity(call, config) {
|
|
1184
|
+
const body = userActivityBody(config);
|
|
1185
|
+
if (!config.returnAll) {
|
|
1186
|
+
if (config.limit > 500) throw new Error(`"limit" is at most 500 for user activity`);
|
|
1187
|
+
const answer = await call(userActivityRequest({
|
|
1188
|
+
...body,
|
|
1189
|
+
pageSize: config.limit
|
|
1190
|
+
}));
|
|
1191
|
+
return isRecord(answer) ? asList(answer.sessions) : [];
|
|
1192
|
+
}
|
|
1193
|
+
const sessions = [];
|
|
1194
|
+
let pageToken;
|
|
1195
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
1196
|
+
const answer = await call(userActivityRequest(pageToken ? {
|
|
1197
|
+
...body,
|
|
1198
|
+
pageToken
|
|
1199
|
+
} : body));
|
|
1200
|
+
if (!isRecord(answer)) break;
|
|
1201
|
+
sessions.push(...asList(answer.sessions));
|
|
1202
|
+
pageToken = typeof answer.nextPageToken === "string" && answer.nextPageToken !== "" ? answer.nextPageToken : void 0;
|
|
1203
|
+
if (!pageToken) break;
|
|
1204
|
+
}
|
|
1205
|
+
return sessions;
|
|
1206
|
+
}
|
|
1207
|
+
// src/index.ts
|
|
1208
|
+
const nodes = [(0, _zerodot_node_sdk.defineNode)({
|
|
1209
|
+
type: "google_analytics.api",
|
|
1210
|
+
label: "Google Analytics",
|
|
1211
|
+
description: "Get reports and user activity from Google Analytics",
|
|
1212
|
+
category: "integration",
|
|
1213
|
+
app: "Google Analytics",
|
|
1214
|
+
actions: [{
|
|
1215
|
+
label: "Get a report",
|
|
1216
|
+
config: {
|
|
1217
|
+
resource: "report",
|
|
1218
|
+
operation: "get"
|
|
1219
|
+
}
|
|
1220
|
+
}, {
|
|
1221
|
+
label: "Search user activity data",
|
|
1222
|
+
config: {
|
|
1223
|
+
resource: "userActivity",
|
|
1224
|
+
operation: "search"
|
|
1225
|
+
}
|
|
1226
|
+
}],
|
|
1227
|
+
icon: "Analytics01Icon",
|
|
1228
|
+
iconUrl: ANALYTICS_ICON,
|
|
1229
|
+
config: analyticsConfig,
|
|
1230
|
+
loadOptions: {
|
|
1231
|
+
properties,
|
|
1232
|
+
views,
|
|
1233
|
+
ga4Metrics,
|
|
1234
|
+
ga4Dimensions,
|
|
1235
|
+
uaMetrics,
|
|
1236
|
+
uaDimensions
|
|
1237
|
+
},
|
|
1238
|
+
defaultConfig: {
|
|
1239
|
+
resource: "report",
|
|
1240
|
+
operation: "get",
|
|
1241
|
+
propertyType: "ga4",
|
|
1242
|
+
dateRange: "last7days",
|
|
1243
|
+
metricsGA4: { metricValues: [{
|
|
1244
|
+
listName: "totalUsers",
|
|
1245
|
+
invisible: false
|
|
1246
|
+
}] },
|
|
1247
|
+
dimensionsGA4: { dimensionValues: [{ listName: "date" }] },
|
|
1248
|
+
metricsUA: { metricValues: [{
|
|
1249
|
+
listName: "ga:users",
|
|
1250
|
+
formattingType: "INTEGER"
|
|
1251
|
+
}] },
|
|
1252
|
+
dimensionsUA: { dimensionValues: [{ listName: "ga:date" }] },
|
|
1253
|
+
returnAll: false,
|
|
1254
|
+
limit: 50,
|
|
1255
|
+
simple: true,
|
|
1256
|
+
activityTypes: [],
|
|
1257
|
+
timeoutMs: 3e4
|
|
1258
|
+
},
|
|
1259
|
+
credentialTypes: [ANALYTICS_OAUTH2_CREDENTIAL],
|
|
1260
|
+
ports: {
|
|
1261
|
+
in: ["in"],
|
|
1262
|
+
out: ["out"]
|
|
1263
|
+
},
|
|
1264
|
+
subtitle: (config) => typeof config.operation === "string" ? `${String(config.operation)}: ${String(config.resource ?? "report")}` : void 0,
|
|
1265
|
+
async run({ config, credential, signal }) {
|
|
1266
|
+
const options = {
|
|
1267
|
+
signal,
|
|
1268
|
+
timeoutMs: config.timeoutMs
|
|
1269
|
+
};
|
|
1270
|
+
const token = analyticsToken(credential);
|
|
1271
|
+
const call = (request) => callAnalytics(token, request, options);
|
|
1272
|
+
if (config.resource === "userActivity") return {
|
|
1273
|
+
port: "out",
|
|
1274
|
+
data: await userActivity(call, config)
|
|
1275
|
+
};
|
|
1276
|
+
return {
|
|
1277
|
+
port: "out",
|
|
1278
|
+
data: config.propertyType === "universal" ? await universalReport(call, config) : await ga4Report(call, config)
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
})];
|
|
1282
|
+
const credentialTypes = [analyticsOAuth2Credential];
|
|
1283
|
+
exports.credentialTypes = credentialTypes;
|
|
1284
|
+
exports.nodes = nodes;
|