@ogcio/analytics-sdk 0.0.1-beta.2 → 0.0.1-beta.3

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 (50) hide show
  1. package/dist/base/base-client.d.ts +2 -7
  2. package/dist/base/base-client.d.ts.map +1 -1
  3. package/dist/base/base-client.js +3 -15
  4. package/dist/base/base-client.js.map +1 -0
  5. package/{types.d.ts → dist/browser-types.d.ts} +1 -1
  6. package/dist/index.d.ts +397 -1138
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +311 -254
  9. package/dist/index.js.map +1 -0
  10. package/dist/matomo/helpers.d.ts +8 -1
  11. package/dist/matomo/helpers.d.ts.map +1 -1
  12. package/dist/matomo/helpers.js +2 -1
  13. package/dist/matomo/helpers.js.map +1 -0
  14. package/dist/matomo/types.d.ts +2 -1
  15. package/dist/matomo/types.d.ts.map +1 -1
  16. package/dist/matomo/types.js +1 -0
  17. package/dist/matomo/types.js.map +1 -0
  18. package/dist/schema.d.ts +84 -444
  19. package/dist/schema.d.ts.map +1 -1
  20. package/dist/schema.js +1 -0
  21. package/dist/schema.js.map +1 -0
  22. package/dist/support-files/auth/index.js +1 -0
  23. package/dist/support-files/auth/index.js.map +1 -0
  24. package/dist/support-files/auth/types.d.ts +1 -1
  25. package/dist/support-files/auth/types.d.ts.map +1 -1
  26. package/dist/support-files/auth/types.js +1 -0
  27. package/dist/support-files/auth/types.js.map +1 -0
  28. package/dist/support-files/building-blocks-sdk.d.ts +1 -1
  29. package/dist/support-files/building-blocks-sdk.d.ts.map +1 -1
  30. package/dist/support-files/building-blocks-sdk.js +1 -0
  31. package/dist/support-files/building-blocks-sdk.js.map +1 -0
  32. package/dist/utils/index.js +1 -0
  33. package/dist/utils/index.js.map +1 -0
  34. package/package.json +19 -11
  35. package/examples/environment.d.ts +0 -11
  36. package/examples/index.ts +0 -201
  37. package/examples/tsconfig.json +0 -15
  38. package/src/base/base-client.ts +0 -172
  39. package/src/index.test.ts +0 -92
  40. package/src/index.ts +0 -543
  41. package/src/matomo/helpers.ts +0 -115
  42. package/src/matomo/types.ts +0 -64
  43. package/src/schema.ts +0 -1491
  44. package/src/support-files/auth/index.ts +0 -116
  45. package/src/support-files/auth/types.ts +0 -38
  46. package/src/support-files/building-blocks-sdk.ts +0 -32
  47. package/src/utils/index.test.ts +0 -46
  48. package/src/utils/index.ts +0 -20
  49. package/test-report.xml +0 -181
  50. package/tsconfig.json +0 -18
package/src/index.test.ts DELETED
@@ -1,92 +0,0 @@
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 DELETED
@@ -1,543 +0,0 @@
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 {
6
- getTracker,
7
- initMatomoArray,
8
- initTracker,
9
- push,
10
- } from "./matomo/helpers.js";
11
- import { TrackEventMethods } from "./matomo/types.js";
12
-
13
- export * from "./support-files/auth/index.js";
14
-
15
- // 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
16
- // 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
17
- import BaseClient, {
18
- ANALYTICS,
19
- BaseApiClientParams,
20
- needsBackend,
21
- } from "./base/base-client.js";
22
-
23
- /*
24
- *
25
- * @note This is a workaround to correctly get the keyname of the "x-matomo-token" header from the create website endpoint.
26
- * and be type-safe, since we know that the /api/v1/websites/ endpoint has the "x-matomo-token" header.
27
- * So even if in the future the name of the header changes, the SDK will be aware of that and will not break.
28
- */
29
- type CreateWebsiteHeadersKeys = keyof NonNullable<
30
- paths["/api/v1/websites/"]["post"]["parameters"]["header"]
31
- >;
32
-
33
- /*
34
- * @note This type collects all the possible endpoints that can be used to track events.
35
- * This is useful to be type-safe and avoid errors when developing the track methods.
36
- * If in the future the name of the endpoint changes, the SDK will be aware of that and will not break.
37
- * The only convention to follow is to use the prefix 'track-' for each api endpoint that is used to track events.
38
- */
39
- export type TrackEndpoints = {
40
- [K in keyof paths]: K extends `/api/v1/websites/{id}/track-${string}`
41
- ? K
42
- : never;
43
- }[keyof paths];
44
-
45
- type AnalyticsOptions = BaseApiClientParams & {
46
- trackingWebsiteId?: string;
47
- // @note This is the organization ID that will be used to retrieve the website configuration
48
- // This is mandatory when the SDK is used in a client-side application
49
- organizationId?: string;
50
- // @note This token that will be used for valudation purposes on the create/update website endpoints
51
- matomoToken?: string;
52
- };
53
-
54
- export type WebsiteConfiguration =
55
- paths["/api/v1/websites/{id}"]["get"]["responses"]["200"]["content"]["application/json"]["data"];
56
-
57
- export type WebsiteTrackingCode =
58
- paths["/api/v1/websites/{id}/tracking-code"]["get"]["parameters"]["query"];
59
-
60
- export class Analytics extends BaseClient<paths> {
61
- protected declare client: ReturnType<typeof createClient<paths>>;
62
- protected serviceName = ANALYTICS;
63
-
64
- private organizationId?: string;
65
- private matomoToken?: string;
66
- private isDryRun = false;
67
- private isOptOut = false;
68
- private trackingWebsiteId?: string;
69
- private trackingMetadata?: Record<string, string>;
70
- private websiteConfiguration?: WebsiteConfiguration;
71
- private websiteConfigurationPromise?: Promise<void>;
72
-
73
- constructor({
74
- trackingWebsiteId,
75
- organizationId,
76
- matomoToken,
77
- ...baseApiClientOptions
78
- }: AnalyticsOptions) {
79
- super(baseApiClientOptions);
80
- this.organizationId = organizationId;
81
-
82
- if (matomoToken) {
83
- this.setMatomoToken(matomoToken);
84
- }
85
-
86
- if (trackingWebsiteId) {
87
- this.setTrackingWebsiteId(trackingWebsiteId);
88
- }
89
-
90
- if (isBrowser()) {
91
- initMatomoArray();
92
- }
93
- }
94
-
95
- private async retrieveWebsiteConfiguration(websiteId: string) {
96
- if (!this.organizationId) {
97
- throw new Error("Organization ID is not set");
98
- }
99
-
100
- const { data } = await this.getWebsiteById(websiteId, {
101
- org_id: this.organizationId,
102
- });
103
-
104
- if (!data) throw new Error(`Website ${websiteId} not found`);
105
-
106
- this.websiteConfiguration = data.data;
107
- }
108
-
109
- private matomoOnRequestMiddleware({ request }: MiddlewareCallbackParams) {
110
- const headerTokenName = "x-matomo-token" satisfies CreateWebsiteHeadersKeys;
111
-
112
- request.headers.set(headerTokenName, this.matomoToken || "");
113
- return request;
114
- }
115
-
116
- setMatomoToken(matomoToken: string) {
117
- this.client.eject({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
118
- this.matomoToken = matomoToken;
119
- this.client.use({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
120
- }
121
-
122
- private clientRequest = async <T extends Record<string, unknown>, O>(
123
- promise: Promise<FetchResponse<T, O, "application/json">>,
124
- ) => {
125
- if (this.isDryRun) {
126
- console.warn("Dry run is enabled, skipping request");
127
- return { data: undefined, error: undefined };
128
- }
129
-
130
- if (this.isOptOut) {
131
- console.warn("Opt out is enabled, skipping request");
132
- return { data: undefined, error: undefined };
133
- }
134
-
135
- try {
136
- const result = await promise;
137
- return { data: result.data, error: result.error };
138
- } catch (error) {
139
- console.error("Error tracking event", error);
140
- return { error, data: undefined };
141
- }
142
- };
143
-
144
- /*
145
- * Set the tracking website ID and retrieve the website configuration.
146
- */
147
- setTrackingWebsiteId(websiteId: string) {
148
- this.trackingWebsiteId = websiteId;
149
-
150
- if (this.organizationId) {
151
- // We intentionally don't await the promise here to allow for non-blocking initialization.
152
- // The website configuration will be ensured before any client-tracking operations in the `ensureWebsiteConfiguration` method.
153
- this.websiteConfigurationPromise =
154
- this.retrieveWebsiteConfiguration(websiteId);
155
- }
156
- }
157
-
158
- getTrackingWebsiteId() {
159
- return this.trackingWebsiteId;
160
- }
161
-
162
- setTrackingMetadata(metadata: Record<string, string>) {
163
- this.trackingMetadata = metadata;
164
- }
165
-
166
- getTrackingMetadata() {
167
- return this.trackingMetadata;
168
- }
169
-
170
- /*
171
- * The dryRun flag, when set, prevents any data from being sent to the API.
172
- * This is useful for testing/debugging purposes.
173
- */
174
- setDryRun(dryRun: boolean) {
175
- this.isDryRun = dryRun;
176
- console.warn(`Dry run set to: ${this.isDryRun}`);
177
- }
178
-
179
- /*
180
- * The optOut flag, when set, prevents any data from being sent to the API.
181
- * This is useful for users who want to opt out of data collection.
182
- */
183
- setOptOut(optOut: boolean) {
184
- this.isOptOut = optOut;
185
- console.warn(`Opt out set to: ${this.isOptOut}`);
186
- }
187
-
188
- getAnalyticsConfig() {
189
- return {
190
- dryRun: this.isDryRun,
191
- optOut: this.isOptOut,
192
- };
193
- }
194
-
195
- setAnalyticsConfig(config: { dryRun: boolean; optOut: boolean }) {
196
- this.isDryRun = config.dryRun;
197
- this.isOptOut = config.optOut;
198
- }
199
-
200
- private async ensureWebsiteConfiguration() {
201
- try {
202
- await this.websiteConfigurationPromise;
203
- } catch (error) {
204
- console.error("Error retrieving website configuration", error);
205
- }
206
-
207
- if (!this.websiteConfiguration) {
208
- throw new Error("Website configuration cannot be retrieved");
209
- }
210
- }
211
-
212
- /*
213
- * Initialize the client-side tracker.
214
- * This method is used to initialize the Matomo tracker on the client-side, appending a script tag to the head of the document.
215
- *
216
- * @param overrideConfig - Optional configuration to override the default website configuration, you can also pass a user_id to set the Matomo user ID.
217
- * @example
218
- * await analytics.initClientTracker({ user_id: "123" });
219
- */
220
- async initClientTracker(overrideConfig?: Partial<WebsiteTrackingCode>) {
221
- await this.ensureWebsiteConfiguration();
222
-
223
- initTracker({
224
- websiteConfiguration: this.websiteConfiguration!,
225
- overrideConfig,
226
- });
227
- }
228
-
229
- private async trackPush(
230
- eventName: TrackEventMethods,
231
- eventArguments: (string | number)[],
232
- siteIds?: number[],
233
- ) {
234
- await this.ensureWebsiteConfiguration();
235
-
236
- if (this.isDryRun) {
237
- console.warn("Dry run is enabled, skipping request");
238
- return;
239
- }
240
- if (this.isOptOut) {
241
- console.warn("Opt out is enabled, skipping request");
242
- return;
243
- }
244
-
245
- if (!siteIds?.length) return push([eventName, ...eventArguments]);
246
-
247
- const trackerEndpoint = `${this.websiteConfiguration!.tracker_url}/${
248
- this.websiteConfiguration!.bypass_adblockers ? "tr4ck3rp" : "matomo.php"
249
- }`;
250
-
251
- try {
252
- for (const siteId of siteIds.map(String)) {
253
- const matomoTracker = getTracker(trackerEndpoint, siteId);
254
- matomoTracker[eventName](...eventArguments);
255
- }
256
-
257
- return { data: "success" };
258
- } catch (error) {
259
- console.error("Error tracking event", error);
260
- return { error };
261
- }
262
- }
263
-
264
- @needsBackend
265
- private async trackBackendAction<
266
- T extends
267
- paths[TrackEndpoints]["post"]["requestBody"]["content"]["application/json"],
268
- >(params: { url: TrackEndpoints; data: T; generateCode: boolean }) {
269
- if (!this.trackingWebsiteId) {
270
- throw new Error("Tracking website ID is not set");
271
- }
272
-
273
- const { url, data, generateCode } = params;
274
-
275
- return this.clientRequest(
276
- this.client.POST(url, {
277
- params: {
278
- path: {
279
- id: this.trackingWebsiteId,
280
- },
281
- query: {
282
- code: generateCode,
283
- },
284
- },
285
- body: {
286
- ...data,
287
- ...this.trackingMetadata,
288
- },
289
- }),
290
- );
291
- }
292
-
293
- @needsBackend
294
- async getWebsites() {
295
- return this.clientRequest(this.client.GET("/api/v1/websites/"));
296
- }
297
-
298
- async getWebsiteById(
299
- id: paths["/api/v1/websites/{id}"]["get"]["parameters"]["path"]["id"],
300
- query?: paths["/api/v1/websites/{id}"]["get"]["parameters"]["query"],
301
- ) {
302
- return this.clientRequest(
303
- this.client.GET("/api/v1/websites/{id}", {
304
- params: {
305
- path: {
306
- id,
307
- },
308
- query,
309
- },
310
- }),
311
- );
312
- }
313
-
314
- @needsBackend
315
- async createWebsite(
316
- data: paths["/api/v1/websites/"]["post"]["requestBody"]["content"]["application/json"],
317
- ) {
318
- return this.clientRequest(
319
- this.client.POST("/api/v1/websites/", {
320
- body: data,
321
- }),
322
- );
323
- }
324
-
325
- @needsBackend
326
- async updateWebsite(
327
- id: paths["/api/v1/websites/{id}"]["patch"]["parameters"]["path"]["id"],
328
- data: NonNullable<
329
- paths["/api/v1/websites/{id}"]["patch"]["requestBody"]
330
- >["content"]["application/json"],
331
- ) {
332
- return this.clientRequest(
333
- this.client.PATCH("/api/v1/websites/{id}", {
334
- params: {
335
- path: {
336
- id,
337
- },
338
- },
339
- body: data,
340
- }),
341
- );
342
- }
343
-
344
- @needsBackend
345
- async generateTrackingCode(query: WebsiteTrackingCode) {
346
- if (!this.trackingWebsiteId)
347
- throw new Error("Tracking website ID is not set");
348
-
349
- return this.clientRequest(
350
- this.client.GET("/api/v1/websites/{id}/tracking-code", {
351
- params: {
352
- path: {
353
- id: this.trackingWebsiteId,
354
- },
355
- query,
356
- },
357
- }),
358
- );
359
- }
360
-
361
- async trackEvent(
362
- data: paths["/api/v1/websites/{id}/track-event"]["post"]["requestBody"]["content"]["application/json"],
363
- ) {
364
- if (!isBrowser()) {
365
- return this.trackBackendAction({
366
- url: "/api/v1/websites/{id}/track-event",
367
- data,
368
- generateCode: false,
369
- });
370
- }
371
-
372
- const { event, site_ids } = data;
373
- const eventArguments = [
374
- event.category,
375
- event.action,
376
- ...(event.name ? [event.name] : []),
377
- ...(event.value ? [event.value] : []),
378
- ];
379
-
380
- return this.trackPush("trackEvent", eventArguments, site_ids);
381
- }
382
-
383
- @needsBackend
384
- async generateTrackEventCode(
385
- data: paths["/api/v1/websites/{id}/track-event"]["post"]["requestBody"]["content"]["application/json"],
386
- ) {
387
- return this.trackBackendAction({
388
- url: "/api/v1/websites/{id}/track-event",
389
- data,
390
- generateCode: true,
391
- });
392
- }
393
-
394
- async trackPageView(
395
- data: paths["/api/v1/websites/{id}/track-page-view"]["post"]["requestBody"]["content"]["application/json"],
396
- ) {
397
- if (!isBrowser()) {
398
- return this.trackBackendAction({
399
- url: "/api/v1/websites/{id}/track-page-view",
400
- data,
401
- generateCode: false,
402
- });
403
- }
404
-
405
- const { event, site_ids } = data;
406
- const eventArguments = [event.action_name];
407
-
408
- return this.trackPush("trackPageView", eventArguments, site_ids);
409
- }
410
-
411
- @needsBackend
412
- async generateTrackPageViewCode(
413
- data: paths["/api/v1/websites/{id}/track-page-view"]["post"]["requestBody"]["content"]["application/json"],
414
- ) {
415
- return this.trackBackendAction({
416
- url: "/api/v1/websites/{id}/track-page-view",
417
- data,
418
- generateCode: true,
419
- });
420
- }
421
-
422
- async trackSiteSearch(
423
- data: paths["/api/v1/websites/{id}/track-search"]["post"]["requestBody"]["content"]["application/json"],
424
- ) {
425
- if (!isBrowser()) {
426
- return this.trackBackendAction({
427
- url: "/api/v1/websites/{id}/track-search",
428
- data,
429
- generateCode: false,
430
- });
431
- }
432
-
433
- const { event, site_ids } = data;
434
- const eventArguments = [
435
- event.search_keyword,
436
- ...(event.search_category ? [event.search_category] : []),
437
- ...(event.search_count ? [event.search_count] : []),
438
- ];
439
-
440
- return this.trackPush("trackSiteSearch", eventArguments, site_ids);
441
- }
442
-
443
- @needsBackend
444
- async generateTrackSiteSearchCode(
445
- data: paths["/api/v1/websites/{id}/track-search"]["post"]["requestBody"]["content"]["application/json"],
446
- ) {
447
- return this.trackBackendAction({
448
- url: "/api/v1/websites/{id}/track-search",
449
- data,
450
- generateCode: true,
451
- });
452
- }
453
-
454
- async trackLink(
455
- data: paths["/api/v1/websites/{id}/track-link"]["post"]["requestBody"]["content"]["application/json"],
456
- ) {
457
- if (!isBrowser()) {
458
- return this.trackBackendAction({
459
- url: "/api/v1/websites/{id}/track-link",
460
- data,
461
- generateCode: false,
462
- });
463
- }
464
- const { event, site_ids } = data;
465
- const eventArguments = [event.link, event.linkType];
466
-
467
- return this.trackPush("trackLink", eventArguments, site_ids);
468
- }
469
-
470
- @needsBackend
471
- async generateTrackLinkCode(
472
- data: paths["/api/v1/websites/{id}/track-link"]["post"]["requestBody"]["content"]["application/json"],
473
- ) {
474
- return this.trackBackendAction({
475
- url: "/api/v1/websites/{id}/track-link",
476
- data,
477
- generateCode: true,
478
- });
479
- }
480
-
481
- async trackContentImpression(
482
- data: paths["/api/v1/websites/{id}/track-content-impression"]["post"]["requestBody"]["content"]["application/json"],
483
- ) {
484
- if (!isBrowser()) {
485
- return this.trackBackendAction({
486
- url: "/api/v1/websites/{id}/track-content-impression",
487
- data,
488
- generateCode: false,
489
- });
490
- }
491
- const { event, site_ids } = data;
492
- const eventArguments = [
493
- event.content_name,
494
- event.content_piece,
495
- event.content_target,
496
- ];
497
-
498
- return this.trackPush("trackContentImpression", eventArguments, site_ids);
499
- }
500
-
501
- @needsBackend
502
- async generateTrackContentImpressionCode(
503
- data: paths["/api/v1/websites/{id}/track-content-impression"]["post"]["requestBody"]["content"]["application/json"],
504
- ) {
505
- return this.trackBackendAction({
506
- url: "/api/v1/websites/{id}/track-content-impression",
507
- data,
508
- generateCode: true,
509
- });
510
- }
511
-
512
- async trackContentInteraction(
513
- data: paths["/api/v1/websites/{id}/track-content-interaction"]["post"]["requestBody"]["content"]["application/json"],
514
- ) {
515
- if (!isBrowser()) {
516
- return this.trackBackendAction({
517
- url: "/api/v1/websites/{id}/track-content-interaction",
518
- data,
519
- generateCode: false,
520
- });
521
- }
522
- const { event, site_ids } = data;
523
- const eventArguments = [
524
- event.content_interaction,
525
- event.content_name,
526
- event.content_piece,
527
- event.content_target,
528
- ];
529
-
530
- return this.trackPush("trackContentInteraction", eventArguments, site_ids);
531
- }
532
-
533
- @needsBackend
534
- async generateTrackContentInteractionCode(
535
- data: paths["/api/v1/websites/{id}/track-content-interaction"]["post"]["requestBody"]["content"]["application/json"],
536
- ) {
537
- return this.trackBackendAction({
538
- url: "/api/v1/websites/{id}/track-content-interaction",
539
- data,
540
- generateCode: true,
541
- });
542
- }
543
- }