@ogcio/analytics-sdk 0.0.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/base/base-client.d.ts +36 -0
  2. package/dist/base/base-client.d.ts.map +1 -0
  3. package/dist/base/base-client.js +96 -0
  4. package/dist/index.d.ts +651 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +321 -0
  7. package/dist/matomo/helpers.d.ts +9 -0
  8. package/dist/matomo/helpers.d.ts.map +1 -0
  9. package/dist/matomo/helpers.js +10 -0
  10. package/dist/matomo/types.d.ts +33 -0
  11. package/dist/matomo/types.d.ts.map +1 -0
  12. package/dist/matomo/types.js +1 -0
  13. package/dist/ogcio-analytics-sdk-0.0.1.tgz +0 -0
  14. package/dist/package/dist/base/base-client.d.ts +36 -0
  15. package/dist/package/dist/base/base-client.d.ts.map +1 -0
  16. package/dist/package/dist/base/base-client.js +96 -0
  17. package/dist/package/dist/index.d.ts +651 -0
  18. package/dist/package/dist/index.d.ts.map +1 -0
  19. package/dist/package/dist/index.js +321 -0
  20. package/dist/package/dist/matomo/helpers.d.ts +9 -0
  21. package/dist/package/dist/matomo/helpers.d.ts.map +1 -0
  22. package/dist/package/dist/matomo/helpers.js +10 -0
  23. package/dist/package/dist/matomo/types.d.ts +33 -0
  24. package/dist/package/dist/matomo/types.d.ts.map +1 -0
  25. package/dist/package/dist/matomo/types.js +1 -0
  26. package/dist/package/dist/schema.d.ts +1295 -0
  27. package/dist/package/dist/schema.d.ts.map +1 -0
  28. package/dist/package/dist/schema.js +5 -0
  29. package/dist/package/dist/support-files/auth/index.d.ts +3 -0
  30. package/dist/package/dist/support-files/auth/index.d.ts.map +1 -0
  31. package/dist/package/dist/support-files/auth/index.js +76 -0
  32. package/dist/package/dist/support-files/auth/types.d.ts +31 -0
  33. package/dist/package/dist/support-files/auth/types.d.ts.map +1 -0
  34. package/dist/package/dist/support-files/auth/types.js +1 -0
  35. package/dist/package/dist/support-files/building-blocks-sdk.d.ts +17 -0
  36. package/dist/package/dist/support-files/building-blocks-sdk.d.ts.map +1 -0
  37. package/dist/package/dist/support-files/building-blocks-sdk.js +11 -0
  38. package/dist/package/dist/utils/index.d.ts +7 -0
  39. package/dist/package/dist/utils/index.d.ts.map +1 -0
  40. package/dist/package/dist/utils/index.js +19 -0
  41. package/dist/package/examples/environment.d.ts +11 -0
  42. package/dist/package/examples/index.ts +201 -0
  43. package/dist/package/examples/tsconfig.json +15 -0
  44. package/dist/package/package.json +56 -0
  45. package/dist/package/tsconfig.json +18 -0
  46. package/dist/package/types.d.ts +19 -0
  47. package/dist/schema.d.ts +1295 -0
  48. package/dist/schema.d.ts.map +1 -0
  49. package/dist/schema.js +5 -0
  50. package/dist/support-files/auth/index.d.ts +3 -0
  51. package/dist/support-files/auth/index.d.ts.map +1 -0
  52. package/dist/support-files/auth/index.js +76 -0
  53. package/dist/support-files/auth/types.d.ts +31 -0
  54. package/dist/support-files/auth/types.d.ts.map +1 -0
  55. package/dist/support-files/auth/types.js +1 -0
  56. package/dist/support-files/building-blocks-sdk.d.ts +17 -0
  57. package/dist/support-files/building-blocks-sdk.d.ts.map +1 -0
  58. package/dist/support-files/building-blocks-sdk.js +11 -0
  59. package/dist/utils/index.d.ts +7 -0
  60. package/dist/utils/index.d.ts.map +1 -0
  61. package/dist/utils/index.js +19 -0
  62. package/examples/environment.d.ts +11 -0
  63. package/examples/index.ts +201 -0
  64. package/examples/tsconfig.json +15 -0
  65. package/package.json +56 -0
  66. package/src/base/base-client.ts +172 -0
  67. package/src/index.test.ts +92 -0
  68. package/src/index.ts +449 -0
  69. package/src/matomo/helpers.ts +14 -0
  70. package/src/matomo/types.ts +48 -0
  71. package/src/schema.ts +1295 -0
  72. package/src/support-files/auth/index.ts +116 -0
  73. package/src/support-files/auth/types.ts +38 -0
  74. package/src/support-files/building-blocks-sdk.ts +32 -0
  75. package/src/utils/index.test.ts +46 -0
  76. package/src/utils/index.ts +20 -0
  77. package/tsconfig.json +18 -0
  78. package/types.d.ts +19 -0
@@ -0,0 +1,172 @@
1
+ import createClient, {
2
+ type Middleware,
3
+ type FetchResponse,
4
+ ParseAsResponse,
5
+ } from "openapi-fetch";
6
+ import type {
7
+ ErrorStatus,
8
+ FilterKeys,
9
+ OkStatus,
10
+ ResponseContent,
11
+ ResponseObjectMap,
12
+ } from "openapi-typescript-helpers";
13
+
14
+ export const ANALYTICS = "analytics" as const;
15
+
16
+ export type SERVICE_NAME = typeof ANALYTICS;
17
+
18
+ export type TokenFunction = (
19
+ serviceName: SERVICE_NAME,
20
+ ) => Promise<string> | string;
21
+
22
+ export type SDKClientParams = {
23
+ baseUrl?: string;
24
+ };
25
+
26
+ export type BaseApiClientParams = SDKClientParams & {
27
+ getTokenFn?: TokenFunction;
28
+ };
29
+
30
+ export type DataResponseValue<T, O> = ParseAsResponse<
31
+ FilterKeys<
32
+ ResponseContent<FilterKeys<ResponseObjectMap<T>, OkStatus>>,
33
+ "application/json"
34
+ >,
35
+ O
36
+ > & {
37
+ error: ParseAsResponse<
38
+ FilterKeys<
39
+ ResponseContent<FilterKeys<ResponseObjectMap<T>, ErrorStatus>>,
40
+ "application/json"
41
+ >,
42
+ O
43
+ >;
44
+ };
45
+
46
+ /**
47
+ * This decorator is used to check if the baseUrl or token of the client are set.
48
+ * If the baseUrl or token are not set, it throws an error
49
+ */
50
+ export function needsBackend(
51
+ target: unknown,
52
+ propertyKey: string,
53
+ descriptor: PropertyDescriptor,
54
+ ) {
55
+ const originalMethod = descriptor.value;
56
+ descriptor.value = async function (
57
+ this: BaseClient<never>,
58
+ ...args: unknown[]
59
+ ) {
60
+ this.checkBackend();
61
+ return originalMethod.apply(this, args);
62
+ };
63
+ return descriptor;
64
+ }
65
+
66
+ abstract class BaseClient<T extends object> {
67
+ private baseUrl?: string;
68
+ private initialized;
69
+
70
+ protected token?: string;
71
+ protected getTokenFn?: TokenFunction;
72
+ protected serviceName: SERVICE_NAME | undefined;
73
+
74
+ protected client: ReturnType<typeof createClient<T>>;
75
+
76
+ constructor({ baseUrl, getTokenFn }: BaseApiClientParams) {
77
+ this.initialized = false;
78
+ if (baseUrl) {
79
+ this.baseUrl = baseUrl;
80
+ this.initialized = true;
81
+ }
82
+
83
+ if (getTokenFn) {
84
+ this.getTokenFn = getTokenFn;
85
+ }
86
+
87
+ this.token = undefined;
88
+ this.client = createClient<T>({ baseUrl: this.baseUrl });
89
+ const authMiddleware: Middleware = {
90
+ onRequest: async ({ request }) => {
91
+ if (!this.token && this.getTokenFn) {
92
+ this.token = await this.getTokenFn(this.serviceName as SERVICE_NAME);
93
+ }
94
+
95
+ if (this.token) {
96
+ request.headers.set("Authorization", `Bearer ${this.token}`);
97
+ }
98
+ return request;
99
+ },
100
+ };
101
+
102
+ this.client.use(authMiddleware);
103
+ }
104
+
105
+ public deleteToken() {
106
+ this.token = undefined;
107
+ }
108
+
109
+ protected async getToken() {
110
+ if (this.getTokenFn) {
111
+ const token = await this.getTokenFn(this.serviceName as SERVICE_NAME);
112
+ this.token = token;
113
+ }
114
+
115
+ return this.token;
116
+ }
117
+
118
+ public isInitialized() {
119
+ return this.initialized;
120
+ }
121
+
122
+ protected formatResponse<G extends Record<string, unknown>, O>(
123
+ response: FetchResponse<G, O, "application/json">,
124
+ ): DataResponseValue<G, O> {
125
+ let outputData = undefined;
126
+ let outputMetadata = undefined;
127
+ if (!response) {
128
+ return {} as DataResponseValue<G, O>;
129
+ }
130
+ if (response.data) {
131
+ const dataEntries = Object.entries(response.data);
132
+ // by docs the body should contain a "data"
133
+ // properties with the response values
134
+ const containsData = dataEntries.find((x) => x[0] === "data");
135
+ const containsMetadata = dataEntries.find((x) => x[0] === "metadata");
136
+
137
+ if (containsMetadata) {
138
+ outputMetadata = containsMetadata[1];
139
+ }
140
+ outputData = containsData ? containsData[1] : response.data;
141
+ }
142
+
143
+ return {
144
+ data: outputData,
145
+ metadata: outputMetadata,
146
+ error: response.error,
147
+ } as unknown as DataResponseValue<G, O>;
148
+ }
149
+
150
+ protected formatError<G, O>(reason: unknown): DataResponseValue<G, O> {
151
+ return { error: reason } as unknown as DataResponseValue<G, O>;
152
+ }
153
+
154
+ /* checkBackend is a protected method used by needsBackend decorator */
155
+ protected async checkBackend() {
156
+ const className = this.constructor.name;
157
+
158
+ if (!this.baseUrl) {
159
+ throw new Error(
160
+ `${className} baseUrl is not set. Please provide a valid baseUrl when initializing ${className} SDK methods.`,
161
+ );
162
+ }
163
+
164
+ if (!this.token && !this.getTokenFn) {
165
+ throw new Error(
166
+ `${className} token is not set. Please provide a valid getTokenFn function when initializing ${className} SDK methods.`,
167
+ );
168
+ }
169
+ }
170
+ }
171
+
172
+ export default BaseClient;
@@ -0,0 +1,92 @@
1
+ import t from "tap";
2
+ import { Analytics } from "./index.js";
3
+
4
+ t.test("Analytics - Dry Run and Opt Out", async (t) => {
5
+ const baseUrl = "http://example.com";
6
+ const trackingWebsiteId = "123";
7
+
8
+ t.test("Analytics Config", async (t) => {
9
+ const analytics = new Analytics({
10
+ baseUrl,
11
+ trackingWebsiteId,
12
+ getTokenFn: () => "token",
13
+ });
14
+ analytics.setAnalyticsConfig({ dryRun: true, optOut: false });
15
+
16
+ let config = analytics.getAnalyticsConfig();
17
+ t.equal(config.dryRun, true, "Dry run should be set to true");
18
+ t.equal(config.optOut, false, "Opt out should be set to false");
19
+
20
+ analytics.setAnalyticsConfig({ dryRun: false, optOut: true });
21
+
22
+ config = analytics.getAnalyticsConfig();
23
+ t.equal(config.dryRun, false, "Dry run should be set to false");
24
+ t.equal(config.optOut, true, "Opt out should be set to true");
25
+ });
26
+
27
+ t.test("Dry Run", async (t) => {
28
+ const analytics = new Analytics({
29
+ baseUrl,
30
+ trackingWebsiteId,
31
+ getTokenFn: () => "token",
32
+ });
33
+ analytics.setDryRun(true);
34
+
35
+ const consoleSpy = t.capture(console, "warn");
36
+ const result = await analytics.trackEvent({
37
+ event: { category: "test_event", action: "test_event" },
38
+ });
39
+
40
+ t.equal(
41
+ result?.data,
42
+ undefined,
43
+ "No data should be returned in dry run mode",
44
+ );
45
+ t.equal(
46
+ result?.error,
47
+ undefined,
48
+ "No error should be returned in dry run mode",
49
+ );
50
+
51
+ t.match(
52
+ consoleSpy.calls[0].args[0],
53
+ "Dry run is enabled, skipping request",
54
+ "Console warning should be logged",
55
+ );
56
+
57
+ analytics.setDryRun(false);
58
+ });
59
+
60
+ t.test("Opt Out", async (t) => {
61
+ const analytics = new Analytics({
62
+ baseUrl,
63
+ trackingWebsiteId,
64
+ getTokenFn: () => "token",
65
+ });
66
+
67
+ analytics.setOptOut(true);
68
+
69
+ const consoleSpy = t.capture(console, "warn");
70
+ const result = await analytics.trackEvent({
71
+ event: { category: "test_event", action: "test_event" },
72
+ });
73
+
74
+ t.equal(
75
+ result?.data,
76
+ undefined,
77
+ "No data should be returned when opted out",
78
+ );
79
+ t.equal(
80
+ result?.error,
81
+ undefined,
82
+ "No error should be returned when opted out",
83
+ );
84
+ t.match(
85
+ consoleSpy.calls[0].args[0],
86
+ "Opt out is enabled, skipping request",
87
+ "Console warning should be logged",
88
+ );
89
+
90
+ analytics.setOptOut(false);
91
+ });
92
+ });
package/src/index.ts ADDED
@@ -0,0 +1,449 @@
1
+ import type { FetchResponse, MiddlewareCallbackParams } from "openapi-fetch";
2
+ import type createClient from "openapi-fetch";
3
+ import type { paths } from "./schema.js";
4
+ import { isBrowser } from "./utils/index.js";
5
+ import { getTracker, push } from "./matomo/helpers.js";
6
+ import { TrackEventMethods } from "./matomo/types.js";
7
+
8
+ export * from "./support-files/auth/index.js";
9
+
10
+ // Since Analytics is a client of the Building-Blocks-SDK, we need to temporarily copy and import the base client from the Building-Blocks-SDK
11
+ // in the future, we should move the base client to a base-building-blocks package, in order to avoid circular dependencies and copy-pasting code
12
+ import BaseClient, {
13
+ ANALYTICS,
14
+ BaseApiClientParams,
15
+ needsBackend,
16
+ } from "./base/base-client.js";
17
+
18
+ /*
19
+ *
20
+ * @note This is a workaround to correctly get the keyname of the "x-matomo-token" header from the create website endpoint.
21
+ * and be type-safe, since we know that the /api/v1/websites/ endpoint has the "x-matomo-token" header.
22
+ * So even if in the future the name of the header changes, the SDK will be aware of that and will not break.
23
+ */
24
+ type CreateWebsiteHeadersKeys = keyof NonNullable<
25
+ paths["/api/v1/websites/"]["post"]["parameters"]["header"]
26
+ >;
27
+
28
+ /*
29
+ * @note This type collects all the possible endpoints that can be used to track events.
30
+ * This is useful to be type-safe and avoid errors when developing the track methods.
31
+ * If in the future the name of the endpoint changes, the SDK will be aware of that and will not break.
32
+ * The only convention to follow is to use the prefix 'track-' for each api endpoint that is used to track events.
33
+ */
34
+ export type TrackEndpoints = {
35
+ [K in keyof paths]: K extends `/api/v1/websites/{id}/track-${string}`
36
+ ? K
37
+ : never;
38
+ }[keyof paths];
39
+
40
+ type AnalyticsOptions = BaseApiClientParams & {
41
+ trackingWebsiteId?: string;
42
+ // @note This is the organization ID that will be used to retrieve the website configuration
43
+ // This is mandatory when the SDK is used in a client-side application
44
+ organizationId?: string;
45
+ // @note This token that will be used for valudation purposes on the create/update website endpoints
46
+ matomoToken?: string;
47
+ };
48
+
49
+ type WebsiteConfiguration =
50
+ paths["/api/v1/websites/{id}"]["get"]["responses"]["200"]["content"]["application/json"]["data"];
51
+
52
+ export class Analytics extends BaseClient<paths> {
53
+ protected declare client: ReturnType<typeof createClient<paths>>;
54
+ protected serviceName = ANALYTICS;
55
+
56
+ private organizationId?: string;
57
+ private matomoToken?: string;
58
+ private isDryRun = false;
59
+ private isOptOut = false;
60
+ private trackingWebsiteId?: string;
61
+ private trackingMetadata?: Record<string, string>;
62
+ private websiteConfiguration?: WebsiteConfiguration;
63
+ private websiteConfigurationPromise?: Promise<void>;
64
+
65
+ constructor({
66
+ trackingWebsiteId,
67
+ organizationId,
68
+ matomoToken,
69
+ ...baseApiClientOptions
70
+ }: AnalyticsOptions) {
71
+ super(baseApiClientOptions);
72
+ this.organizationId = organizationId;
73
+
74
+ if (matomoToken) {
75
+ this.setMatomoToken(matomoToken);
76
+ }
77
+
78
+ if (trackingWebsiteId) {
79
+ this.setTrackingWebsiteId(trackingWebsiteId);
80
+ }
81
+ }
82
+
83
+ private async retrieveWebsiteConfiguration(websiteId: string) {
84
+ if (!this.organizationId) {
85
+ throw new Error("Organization ID is not set");
86
+ }
87
+
88
+ const { data } = await this.getWebsiteById(websiteId, {
89
+ org_id: this.organizationId,
90
+ });
91
+
92
+ if (!data) throw new Error(`Website ${websiteId} not found`);
93
+
94
+ this.websiteConfiguration = data.data;
95
+ }
96
+
97
+ private matomoOnRequestMiddleware({ request }: MiddlewareCallbackParams) {
98
+ const headerTokenName = "x-matomo-token" satisfies CreateWebsiteHeadersKeys;
99
+
100
+ request.headers.set(headerTokenName, this.matomoToken || "");
101
+ return request;
102
+ }
103
+
104
+ setMatomoToken(matomoToken: string) {
105
+ this.client.eject({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
106
+ this.matomoToken = matomoToken;
107
+ this.client.use({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
108
+ }
109
+
110
+ private clientRequest = async <T extends Record<string, unknown>, O>(
111
+ promise: Promise<FetchResponse<T, O, "application/json">>,
112
+ ) => {
113
+ if (this.isDryRun) {
114
+ console.warn("Dry run is enabled, skipping request");
115
+ return { data: undefined, error: undefined };
116
+ }
117
+
118
+ if (this.isOptOut) {
119
+ console.warn("Opt out is enabled, skipping request");
120
+ return { data: undefined, error: undefined };
121
+ }
122
+
123
+ const result = await promise;
124
+
125
+ return { data: result.data, error: result.error };
126
+ };
127
+
128
+ /*
129
+ * Set the tracking website ID and retrieve the website configuration.
130
+ */
131
+ setTrackingWebsiteId(websiteId: string) {
132
+ this.trackingWebsiteId = websiteId;
133
+
134
+ if (this.organizationId) {
135
+ // We intentionally don't await the promise here to allow for non-blocking initialization.
136
+ // The website configuration will be ensured before any client-tracking operations in the `ensureWebsiteConfiguration` method.
137
+ this.websiteConfigurationPromise =
138
+ this.retrieveWebsiteConfiguration(websiteId);
139
+ }
140
+ }
141
+
142
+ getTrackingWebsiteId() {
143
+ return this.trackingWebsiteId;
144
+ }
145
+
146
+ setTrackingMetadata(metadata: Record<string, string>) {
147
+ this.trackingMetadata = metadata;
148
+ }
149
+
150
+ getTrackingMetadata() {
151
+ return this.trackingMetadata;
152
+ }
153
+
154
+ /*
155
+ * The dryRun flag, when set, prevents any data from being sent to the API.
156
+ * This is useful for testing/debugging purposes.
157
+ */
158
+ setDryRun(dryRun: boolean) {
159
+ this.isDryRun = dryRun;
160
+ console.warn(`Dry run set to: ${this.isDryRun}`);
161
+ }
162
+
163
+ /*
164
+ * The optOut flag, when set, prevents any data from being sent to the API.
165
+ * This is useful for users who want to opt out of data collection.
166
+ */
167
+ setOptOut(optOut: boolean) {
168
+ this.isOptOut = optOut;
169
+ console.warn(`Opt out set to: ${this.isOptOut}`);
170
+ }
171
+
172
+ getAnalyticsConfig() {
173
+ return {
174
+ dryRun: this.isDryRun,
175
+ optOut: this.isOptOut,
176
+ };
177
+ }
178
+
179
+ setAnalyticsConfig(config: { dryRun: boolean; optOut: boolean }) {
180
+ this.isDryRun = config.dryRun;
181
+ this.isOptOut = config.optOut;
182
+ }
183
+
184
+ private async ensureWebsiteConfiguration() {
185
+ try {
186
+ await this.websiteConfigurationPromise;
187
+ } catch (error) {
188
+ console.error("Error retrieving website configuration", error);
189
+ }
190
+
191
+ if (!this.websiteConfiguration) {
192
+ throw new Error("Website configuration cannot be retrieved");
193
+ }
194
+ }
195
+
196
+ private async trackPush(
197
+ eventName: TrackEventMethods,
198
+ eventArguments: (string | number)[],
199
+ siteIds?: number[],
200
+ ) {
201
+ await this.ensureWebsiteConfiguration();
202
+
203
+ if (this.isDryRun) {
204
+ console.warn("Dry run is enabled, skipping request");
205
+ return;
206
+ }
207
+ if (this.isOptOut) {
208
+ console.warn("Opt out is enabled, skipping request");
209
+ return;
210
+ }
211
+
212
+ if (!siteIds?.length) return push([eventName, ...eventArguments]);
213
+
214
+ const trackerEndpoint = `${this.websiteConfiguration!.tracker_url}/${
215
+ this.websiteConfiguration!.bypass_adblockers ? "tr4ck3rp" : "matomo.php"
216
+ }`;
217
+
218
+ try {
219
+ for (const siteId of siteIds.map(String)) {
220
+ const matomoTracker = getTracker(trackerEndpoint, siteId);
221
+ matomoTracker[eventName](...eventArguments);
222
+ }
223
+
224
+ return { data: "success" };
225
+ } catch (error) {
226
+ console.error("Error tracking event", error);
227
+ return { error };
228
+ }
229
+ }
230
+
231
+ @needsBackend
232
+ private async trackBackendAction<
233
+ T extends
234
+ paths[TrackEndpoints]["post"]["requestBody"]["content"]["application/json"],
235
+ >(params: { url: TrackEndpoints; data: T; generateCode: boolean }) {
236
+ if (!this.trackingWebsiteId) {
237
+ throw new Error("Tracking website ID is not set");
238
+ }
239
+
240
+ const { url, data, generateCode } = params;
241
+
242
+ return this.clientRequest(
243
+ this.client.POST(url, {
244
+ params: {
245
+ path: {
246
+ id: this.trackingWebsiteId,
247
+ },
248
+ query: {
249
+ code: generateCode,
250
+ },
251
+ },
252
+ body: {
253
+ ...data,
254
+ ...this.trackingMetadata,
255
+ },
256
+ }),
257
+ );
258
+ }
259
+
260
+ @needsBackend
261
+ async getWebsites() {
262
+ return this.clientRequest(this.client.GET("/api/v1/websites/"));
263
+ }
264
+
265
+ async getWebsiteById(
266
+ id: paths["/api/v1/websites/{id}"]["get"]["parameters"]["path"]["id"],
267
+ query?: paths["/api/v1/websites/{id}"]["get"]["parameters"]["query"],
268
+ ) {
269
+ return this.clientRequest(
270
+ this.client.GET("/api/v1/websites/{id}", {
271
+ params: {
272
+ path: {
273
+ id,
274
+ },
275
+ query,
276
+ },
277
+ }),
278
+ );
279
+ }
280
+
281
+ @needsBackend
282
+ async createWebsite(
283
+ data: paths["/api/v1/websites/"]["post"]["requestBody"]["content"]["application/json"],
284
+ ) {
285
+ return this.clientRequest(
286
+ this.client.POST("/api/v1/websites/", {
287
+ body: data,
288
+ }),
289
+ );
290
+ }
291
+
292
+ @needsBackend
293
+ async updateWebsite(
294
+ id: paths["/api/v1/websites/{id}"]["patch"]["parameters"]["path"]["id"],
295
+ data: NonNullable<
296
+ paths["/api/v1/websites/{id}"]["patch"]["requestBody"]
297
+ >["content"]["application/json"],
298
+ ) {
299
+ return this.clientRequest(
300
+ this.client.PATCH("/api/v1/websites/{id}", {
301
+ params: {
302
+ path: {
303
+ id,
304
+ },
305
+ },
306
+ body: data,
307
+ }),
308
+ );
309
+ }
310
+
311
+ @needsBackend
312
+ async generateTrackingCode(
313
+ query: paths["/api/v1/websites/{id}/tracking-code"]["get"]["parameters"]["query"],
314
+ ) {
315
+ if (!this.trackingWebsiteId)
316
+ throw new Error("Tracking website ID is not set");
317
+
318
+ return this.clientRequest(
319
+ this.client.GET("/api/v1/websites/{id}/tracking-code", {
320
+ params: {
321
+ path: {
322
+ id: this.trackingWebsiteId,
323
+ },
324
+ query,
325
+ },
326
+ }),
327
+ );
328
+ }
329
+
330
+ async trackEvent(
331
+ data: paths["/api/v1/websites/{id}/track-event"]["post"]["requestBody"]["content"]["application/json"],
332
+ ) {
333
+ if (!isBrowser()) {
334
+ return this.trackBackendAction({
335
+ url: "/api/v1/websites/{id}/track-event",
336
+ data,
337
+ generateCode: false,
338
+ });
339
+ }
340
+
341
+ const { event, site_ids } = data;
342
+ const eventArguments = [
343
+ event.category,
344
+ event.action,
345
+ ...(event.name ? [event.name] : []),
346
+ ...(event.value ? [event.value] : []),
347
+ ];
348
+
349
+ return this.trackPush("trackEvent", eventArguments, site_ids);
350
+ }
351
+
352
+ @needsBackend
353
+ async generateTrackEventCode(
354
+ data: paths["/api/v1/websites/{id}/track-event"]["post"]["requestBody"]["content"]["application/json"],
355
+ ) {
356
+ return this.trackBackendAction({
357
+ url: "/api/v1/websites/{id}/track-event",
358
+ data,
359
+ generateCode: true,
360
+ });
361
+ }
362
+
363
+ async trackPageView(
364
+ data: paths["/api/v1/websites/{id}/track-page-view"]["post"]["requestBody"]["content"]["application/json"],
365
+ ) {
366
+ if (!isBrowser()) {
367
+ return this.trackBackendAction({
368
+ url: "/api/v1/websites/{id}/track-page-view",
369
+ data,
370
+ generateCode: false,
371
+ });
372
+ }
373
+
374
+ const { event, site_ids } = data;
375
+ const eventArguments = [event.action_name];
376
+
377
+ return this.trackPush("trackPageView", eventArguments, site_ids);
378
+ }
379
+
380
+ @needsBackend
381
+ async generateTrackPageViewCode(
382
+ data: paths["/api/v1/websites/{id}/track-page-view"]["post"]["requestBody"]["content"]["application/json"],
383
+ ) {
384
+ return this.trackBackendAction({
385
+ url: "/api/v1/websites/{id}/track-page-view",
386
+ data,
387
+ generateCode: true,
388
+ });
389
+ }
390
+
391
+ async trackSiteSearch(
392
+ data: paths["/api/v1/websites/{id}/track-search"]["post"]["requestBody"]["content"]["application/json"],
393
+ ) {
394
+ if (!isBrowser()) {
395
+ return this.trackBackendAction({
396
+ url: "/api/v1/websites/{id}/track-search",
397
+ data,
398
+ generateCode: false,
399
+ });
400
+ }
401
+
402
+ const { event, site_ids } = data;
403
+ const eventArguments = [
404
+ event.search_keyword,
405
+ ...(event.search_category ? [event.search_category] : []),
406
+ ...(event.search_count ? [event.search_count] : []),
407
+ ];
408
+
409
+ return this.trackPush("trackSiteSearch", eventArguments, site_ids);
410
+ }
411
+
412
+ @needsBackend
413
+ async generateTrackSiteSearchCode(
414
+ data: paths["/api/v1/websites/{id}/track-search"]["post"]["requestBody"]["content"]["application/json"],
415
+ ) {
416
+ return this.trackBackendAction({
417
+ url: "/api/v1/websites/{id}/track-search",
418
+ data,
419
+ generateCode: true,
420
+ });
421
+ }
422
+
423
+ async trackOutLink(
424
+ data: paths["/api/v1/websites/{id}/track-out-link"]["post"]["requestBody"]["content"]["application/json"],
425
+ ) {
426
+ if (!isBrowser()) {
427
+ return this.trackBackendAction({
428
+ url: "/api/v1/websites/{id}/track-out-link",
429
+ data,
430
+ generateCode: false,
431
+ });
432
+ }
433
+ const { event, site_ids } = data;
434
+ const eventArguments = [event.link];
435
+
436
+ return this.trackPush("trackLink", eventArguments, site_ids);
437
+ }
438
+
439
+ @needsBackend
440
+ async generateTrackOutLinkCode(
441
+ data: paths["/api/v1/websites/{id}/track-out-link"]["post"]["requestBody"]["content"]["application/json"],
442
+ ) {
443
+ return this.trackBackendAction({
444
+ url: "/api/v1/websites/{id}/track-out-link",
445
+ data,
446
+ generateCode: true,
447
+ });
448
+ }
449
+ }