@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
package/dist/index.js ADDED
@@ -0,0 +1,321 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { isBrowser } from "./utils/index.js";
8
+ import { getTracker, push } from "./matomo/helpers.js";
9
+ export * from "./support-files/auth/index.js";
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, { ANALYTICS, needsBackend, } from "./base/base-client.js";
13
+ export class Analytics extends BaseClient {
14
+ serviceName = ANALYTICS;
15
+ organizationId;
16
+ matomoToken;
17
+ isDryRun = false;
18
+ isOptOut = false;
19
+ trackingWebsiteId;
20
+ trackingMetadata;
21
+ websiteConfiguration;
22
+ websiteConfigurationPromise;
23
+ constructor({ trackingWebsiteId, organizationId, matomoToken, ...baseApiClientOptions }) {
24
+ super(baseApiClientOptions);
25
+ this.organizationId = organizationId;
26
+ if (matomoToken) {
27
+ this.setMatomoToken(matomoToken);
28
+ }
29
+ if (trackingWebsiteId) {
30
+ this.setTrackingWebsiteId(trackingWebsiteId);
31
+ }
32
+ }
33
+ async retrieveWebsiteConfiguration(websiteId) {
34
+ if (!this.organizationId) {
35
+ throw new Error("Organization ID is not set");
36
+ }
37
+ const { data } = await this.getWebsiteById(websiteId, {
38
+ org_id: this.organizationId,
39
+ });
40
+ if (!data)
41
+ throw new Error(`Website ${websiteId} not found`);
42
+ this.websiteConfiguration = data.data;
43
+ }
44
+ matomoOnRequestMiddleware({ request }) {
45
+ const headerTokenName = "x-matomo-token";
46
+ request.headers.set(headerTokenName, this.matomoToken || "");
47
+ return request;
48
+ }
49
+ setMatomoToken(matomoToken) {
50
+ this.client.eject({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
51
+ this.matomoToken = matomoToken;
52
+ this.client.use({ onRequest: this.matomoOnRequestMiddleware.bind(this) });
53
+ }
54
+ clientRequest = async (promise) => {
55
+ if (this.isDryRun) {
56
+ console.warn("Dry run is enabled, skipping request");
57
+ return { data: undefined, error: undefined };
58
+ }
59
+ if (this.isOptOut) {
60
+ console.warn("Opt out is enabled, skipping request");
61
+ return { data: undefined, error: undefined };
62
+ }
63
+ const result = await promise;
64
+ return { data: result.data, error: result.error };
65
+ };
66
+ /*
67
+ * Set the tracking website ID and retrieve the website configuration.
68
+ */
69
+ setTrackingWebsiteId(websiteId) {
70
+ this.trackingWebsiteId = websiteId;
71
+ if (this.organizationId) {
72
+ // We intentionally don't await the promise here to allow for non-blocking initialization.
73
+ // The website configuration will be ensured before any client-tracking operations in the `ensureWebsiteConfiguration` method.
74
+ this.websiteConfigurationPromise =
75
+ this.retrieveWebsiteConfiguration(websiteId);
76
+ }
77
+ }
78
+ getTrackingWebsiteId() {
79
+ return this.trackingWebsiteId;
80
+ }
81
+ setTrackingMetadata(metadata) {
82
+ this.trackingMetadata = metadata;
83
+ }
84
+ getTrackingMetadata() {
85
+ return this.trackingMetadata;
86
+ }
87
+ /*
88
+ * The dryRun flag, when set, prevents any data from being sent to the API.
89
+ * This is useful for testing/debugging purposes.
90
+ */
91
+ setDryRun(dryRun) {
92
+ this.isDryRun = dryRun;
93
+ console.warn(`Dry run set to: ${this.isDryRun}`);
94
+ }
95
+ /*
96
+ * The optOut flag, when set, prevents any data from being sent to the API.
97
+ * This is useful for users who want to opt out of data collection.
98
+ */
99
+ setOptOut(optOut) {
100
+ this.isOptOut = optOut;
101
+ console.warn(`Opt out set to: ${this.isOptOut}`);
102
+ }
103
+ getAnalyticsConfig() {
104
+ return {
105
+ dryRun: this.isDryRun,
106
+ optOut: this.isOptOut,
107
+ };
108
+ }
109
+ setAnalyticsConfig(config) {
110
+ this.isDryRun = config.dryRun;
111
+ this.isOptOut = config.optOut;
112
+ }
113
+ async ensureWebsiteConfiguration() {
114
+ try {
115
+ await this.websiteConfigurationPromise;
116
+ }
117
+ catch (error) {
118
+ console.error("Error retrieving website configuration", error);
119
+ }
120
+ if (!this.websiteConfiguration) {
121
+ throw new Error("Website configuration cannot be retrieved");
122
+ }
123
+ }
124
+ async trackPush(eventName, eventArguments, siteIds) {
125
+ await this.ensureWebsiteConfiguration();
126
+ if (this.isDryRun) {
127
+ console.warn("Dry run is enabled, skipping request");
128
+ return;
129
+ }
130
+ if (this.isOptOut) {
131
+ console.warn("Opt out is enabled, skipping request");
132
+ return;
133
+ }
134
+ if (!siteIds?.length)
135
+ return push([eventName, ...eventArguments]);
136
+ const trackerEndpoint = `${this.websiteConfiguration.tracker_url}/${this.websiteConfiguration.bypass_adblockers ? "tr4ck3rp" : "matomo.php"}`;
137
+ try {
138
+ for (const siteId of siteIds.map(String)) {
139
+ const matomoTracker = getTracker(trackerEndpoint, siteId);
140
+ matomoTracker[eventName](...eventArguments);
141
+ }
142
+ return { data: "success" };
143
+ }
144
+ catch (error) {
145
+ console.error("Error tracking event", error);
146
+ return { error };
147
+ }
148
+ }
149
+ async trackBackendAction(params) {
150
+ if (!this.trackingWebsiteId) {
151
+ throw new Error("Tracking website ID is not set");
152
+ }
153
+ const { url, data, generateCode } = params;
154
+ return this.clientRequest(this.client.POST(url, {
155
+ params: {
156
+ path: {
157
+ id: this.trackingWebsiteId,
158
+ },
159
+ query: {
160
+ code: generateCode,
161
+ },
162
+ },
163
+ body: {
164
+ ...data,
165
+ ...this.trackingMetadata,
166
+ },
167
+ }));
168
+ }
169
+ async getWebsites() {
170
+ return this.clientRequest(this.client.GET("/api/v1/websites/"));
171
+ }
172
+ async getWebsiteById(id, query) {
173
+ return this.clientRequest(this.client.GET("/api/v1/websites/{id}", {
174
+ params: {
175
+ path: {
176
+ id,
177
+ },
178
+ query,
179
+ },
180
+ }));
181
+ }
182
+ async createWebsite(data) {
183
+ return this.clientRequest(this.client.POST("/api/v1/websites/", {
184
+ body: data,
185
+ }));
186
+ }
187
+ async updateWebsite(id, data) {
188
+ return this.clientRequest(this.client.PATCH("/api/v1/websites/{id}", {
189
+ params: {
190
+ path: {
191
+ id,
192
+ },
193
+ },
194
+ body: data,
195
+ }));
196
+ }
197
+ async generateTrackingCode(query) {
198
+ if (!this.trackingWebsiteId)
199
+ throw new Error("Tracking website ID is not set");
200
+ return this.clientRequest(this.client.GET("/api/v1/websites/{id}/tracking-code", {
201
+ params: {
202
+ path: {
203
+ id: this.trackingWebsiteId,
204
+ },
205
+ query,
206
+ },
207
+ }));
208
+ }
209
+ async trackEvent(data) {
210
+ if (!isBrowser()) {
211
+ return this.trackBackendAction({
212
+ url: "/api/v1/websites/{id}/track-event",
213
+ data,
214
+ generateCode: false,
215
+ });
216
+ }
217
+ const { event, site_ids } = data;
218
+ const eventArguments = [
219
+ event.category,
220
+ event.action,
221
+ ...(event.name ? [event.name] : []),
222
+ ...(event.value ? [event.value] : []),
223
+ ];
224
+ return this.trackPush("trackEvent", eventArguments, site_ids);
225
+ }
226
+ async generateTrackEventCode(data) {
227
+ return this.trackBackendAction({
228
+ url: "/api/v1/websites/{id}/track-event",
229
+ data,
230
+ generateCode: true,
231
+ });
232
+ }
233
+ async trackPageView(data) {
234
+ if (!isBrowser()) {
235
+ return this.trackBackendAction({
236
+ url: "/api/v1/websites/{id}/track-page-view",
237
+ data,
238
+ generateCode: false,
239
+ });
240
+ }
241
+ const { event, site_ids } = data;
242
+ const eventArguments = [event.action_name];
243
+ return this.trackPush("trackPageView", eventArguments, site_ids);
244
+ }
245
+ async generateTrackPageViewCode(data) {
246
+ return this.trackBackendAction({
247
+ url: "/api/v1/websites/{id}/track-page-view",
248
+ data,
249
+ generateCode: true,
250
+ });
251
+ }
252
+ async trackSiteSearch(data) {
253
+ if (!isBrowser()) {
254
+ return this.trackBackendAction({
255
+ url: "/api/v1/websites/{id}/track-search",
256
+ data,
257
+ generateCode: false,
258
+ });
259
+ }
260
+ const { event, site_ids } = data;
261
+ const eventArguments = [
262
+ event.search_keyword,
263
+ ...(event.search_category ? [event.search_category] : []),
264
+ ...(event.search_count ? [event.search_count] : []),
265
+ ];
266
+ return this.trackPush("trackSiteSearch", eventArguments, site_ids);
267
+ }
268
+ async generateTrackSiteSearchCode(data) {
269
+ return this.trackBackendAction({
270
+ url: "/api/v1/websites/{id}/track-search",
271
+ data,
272
+ generateCode: true,
273
+ });
274
+ }
275
+ async trackOutLink(data) {
276
+ if (!isBrowser()) {
277
+ return this.trackBackendAction({
278
+ url: "/api/v1/websites/{id}/track-out-link",
279
+ data,
280
+ generateCode: false,
281
+ });
282
+ }
283
+ const { event, site_ids } = data;
284
+ const eventArguments = [event.link];
285
+ return this.trackPush("trackLink", eventArguments, site_ids);
286
+ }
287
+ async generateTrackOutLinkCode(data) {
288
+ return this.trackBackendAction({
289
+ url: "/api/v1/websites/{id}/track-out-link",
290
+ data,
291
+ generateCode: true,
292
+ });
293
+ }
294
+ }
295
+ __decorate([
296
+ needsBackend
297
+ ], Analytics.prototype, "trackBackendAction", null);
298
+ __decorate([
299
+ needsBackend
300
+ ], Analytics.prototype, "getWebsites", null);
301
+ __decorate([
302
+ needsBackend
303
+ ], Analytics.prototype, "createWebsite", null);
304
+ __decorate([
305
+ needsBackend
306
+ ], Analytics.prototype, "updateWebsite", null);
307
+ __decorate([
308
+ needsBackend
309
+ ], Analytics.prototype, "generateTrackingCode", null);
310
+ __decorate([
311
+ needsBackend
312
+ ], Analytics.prototype, "generateTrackEventCode", null);
313
+ __decorate([
314
+ needsBackend
315
+ ], Analytics.prototype, "generateTrackPageViewCode", null);
316
+ __decorate([
317
+ needsBackend
318
+ ], Analytics.prototype, "generateTrackSiteSearchCode", null);
319
+ __decorate([
320
+ needsBackend
321
+ ], Analytics.prototype, "generateTrackOutLinkCode", null);
@@ -0,0 +1,9 @@
1
+ import type { PushQueueItem } from "./types.js";
2
+ export declare function push(collection: PushQueueItem): number;
3
+ export declare function getTracker(trackerUrl: string, siteId: string): {
4
+ trackSiteSearch: (...eventArguments: (string | number)[]) => void;
5
+ trackEvent: (...eventArguments: (string | number)[]) => void;
6
+ trackPageView: (...eventArguments: (string | number)[]) => void;
7
+ trackLink: (...eventArguments: (string | number)[]) => void;
8
+ };
9
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/matomo/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wBAAgB,IAAI,CAAC,UAAU,EAAE,aAAa,UAO7C;AAED,wBAAgB,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;;;;;EAE5D"}
@@ -0,0 +1,10 @@
1
+ export function push(collection) {
2
+ if (!window._paq)
3
+ window._paq = [];
4
+ window._paq.push(["setCustomUrl", window.location.href]);
5
+ window._paq.push(["setDocumentTitle", document.title]);
6
+ return window._paq.push(collection);
7
+ }
8
+ export function getTracker(trackerUrl, siteId) {
9
+ return window.Matomo.getTracker(trackerUrl, siteId);
10
+ }
@@ -0,0 +1,33 @@
1
+ type SiteSearchTrackEvent = "trackSiteSearch";
2
+ type CustomEventTrackEvent = "trackEvent";
3
+ type PageViewsTrackEvent = "trackPageView";
4
+ type OutlinkTrackEvent = "trackLink";
5
+ type PaqServiceMethods = "setCustomUrl" | "setDocumentTitle";
6
+ type CustomDimensionsMethods = "setCustomDimensionValue" | "deleteCustomDimension" | "setCustomDimension";
7
+ export type TrackEventMethods = SiteSearchTrackEvent | CustomEventTrackEvent | PageViewsTrackEvent | OutlinkTrackEvent;
8
+ export type PushQueueMethods = CustomDimensionsMethods | TrackEventMethods | PaqServiceMethods;
9
+ export type VisitorInfo = [
10
+ isNew: "0" | "1",
11
+ visitorId: string,
12
+ firstVisitTS: number,
13
+ previousVisitCount: string | number,
14
+ currentVisitTS: number,
15
+ lastVisitTS: number | "",
16
+ lastEcommerceOrderTS: number | ""
17
+ ];
18
+ export type Tracker = {
19
+ hasCookies: () => boolean;
20
+ getCookieDomain: () => string;
21
+ getCookiePath: () => string;
22
+ getSessionCookieTimeout: () => number;
23
+ getConfigVisitorCookieTimeout: () => number;
24
+ getCustomDimensionValue: (id: string | number) => string | undefined;
25
+ getLinkTrackingTimer: () => number;
26
+ getEcommerceItems: () => object;
27
+ getUserId: () => string;
28
+ getVisitorId: () => string;
29
+ getVisitorInfo: () => VisitorInfo;
30
+ };
31
+ export type PushQueueItem = [PushQueueMethods, ...unknown[]] | [(this: Tracker) => void];
32
+ export {};
33
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/matomo/types.ts"],"names":[],"mappings":"AAAA,KAAK,oBAAoB,GAAG,iBAAiB,CAAC;AAC9C,KAAK,qBAAqB,GAAG,YAAY,CAAC;AAC1C,KAAK,mBAAmB,GAAG,eAAe,CAAC;AAC3C,KAAK,iBAAiB,GAAG,WAAW,CAAC;AACrC,KAAK,iBAAiB,GAAG,cAAc,GAAG,kBAAkB,CAAC;AAC7D,KAAK,uBAAuB,GACxB,yBAAyB,GACzB,uBAAuB,GACvB,oBAAoB,CAAC;AAEzB,MAAM,MAAM,iBAAiB,GACzB,oBAAoB,GACpB,qBAAqB,GACrB,mBAAmB,GACnB,iBAAiB,CAAC;AAEtB,MAAM,MAAM,gBAAgB,GACxB,uBAAuB,GACvB,iBAAiB,GACjB,iBAAiB,CAAC;AAEtB,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,GAAG,GAAG,GAAG;IAChB,SAAS,EAAE,MAAM;IACjB,YAAY,EAAE,MAAM;IACpB,kBAAkB,EAAE,MAAM,GAAG,MAAM;IACnC,cAAc,EAAE,MAAM;IACtB,WAAW,EAAE,MAAM,GAAG,EAAE;IACxB,oBAAoB,EAAE,MAAM,GAAG,EAAE;CAClC,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,UAAU,EAAE,MAAM,OAAO,CAAC;IAC1B,eAAe,EAAE,MAAM,MAAM,CAAC;IAC9B,aAAa,EAAE,MAAM,MAAM,CAAC;IAC5B,uBAAuB,EAAE,MAAM,MAAM,CAAC;IACtC,6BAA6B,EAAE,MAAM,MAAM,CAAC;IAC5C,uBAAuB,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IACrE,oBAAoB,EAAE,MAAM,MAAM,CAAC;IACnC,iBAAiB,EAAE,MAAM,MAAM,CAAC;IAChC,SAAS,EAAE,MAAM,MAAM,CAAC;IACxB,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B,cAAc,EAAE,MAAM,WAAW,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,aAAa,GACrB,CAAC,gBAAgB,EAAE,GAAG,OAAO,EAAE,CAAC,GAChC,CAAC,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import createClient, { type FetchResponse, ParseAsResponse } from "openapi-fetch";
2
+ import type { ErrorStatus, FilterKeys, OkStatus, ResponseContent, ResponseObjectMap } from "openapi-typescript-helpers";
3
+ export declare const ANALYTICS: "analytics";
4
+ export type SERVICE_NAME = typeof ANALYTICS;
5
+ export type TokenFunction = (serviceName: SERVICE_NAME) => Promise<string> | string;
6
+ export type SDKClientParams = {
7
+ baseUrl?: string;
8
+ };
9
+ export type BaseApiClientParams = SDKClientParams & {
10
+ getTokenFn?: TokenFunction;
11
+ };
12
+ export type DataResponseValue<T, O> = ParseAsResponse<FilterKeys<ResponseContent<FilterKeys<ResponseObjectMap<T>, OkStatus>>, "application/json">, O> & {
13
+ error: ParseAsResponse<FilterKeys<ResponseContent<FilterKeys<ResponseObjectMap<T>, ErrorStatus>>, "application/json">, O>;
14
+ };
15
+ /**
16
+ * This decorator is used to check if the baseUrl or token of the client are set.
17
+ * If the baseUrl or token are not set, it throws an error
18
+ */
19
+ export declare function needsBackend(target: unknown, propertyKey: string, descriptor: PropertyDescriptor): PropertyDescriptor;
20
+ declare abstract class BaseClient<T extends object> {
21
+ private baseUrl?;
22
+ private initialized;
23
+ protected token?: string;
24
+ protected getTokenFn?: TokenFunction;
25
+ protected serviceName: SERVICE_NAME | undefined;
26
+ protected client: ReturnType<typeof createClient<T>>;
27
+ constructor({ baseUrl, getTokenFn }: BaseApiClientParams);
28
+ deleteToken(): void;
29
+ protected getToken(): Promise<string | undefined>;
30
+ isInitialized(): boolean;
31
+ protected formatResponse<G extends Record<string, unknown>, O>(response: FetchResponse<G, O, "application/json">): DataResponseValue<G, O>;
32
+ protected formatError<G, O>(reason: unknown): DataResponseValue<G, O>;
33
+ protected checkBackend(): Promise<void>;
34
+ }
35
+ export default BaseClient;
36
+ //# sourceMappingURL=base-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-client.d.ts","sourceRoot":"","sources":["../../src/base/base-client.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,EAAE,EAEnB,KAAK,aAAa,EAClB,eAAe,EAChB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,QAAQ,EACR,eAAe,EACf,iBAAiB,EAClB,MAAM,4BAA4B,CAAC;AAEpC,eAAO,MAAM,SAAS,aAAuB,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,OAAO,SAAS,CAAC;AAE5C,MAAM,MAAM,aAAa,GAAG,CAC1B,WAAW,EAAE,YAAY,KACtB,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAE9B,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,eAAe,GAAG;IAClD,UAAU,CAAC,EAAE,aAAa,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAAC,CAAC,EAAE,CAAC,IAAI,eAAe,CACnD,UAAU,CACR,eAAe,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,EAC3D,kBAAkB,CACnB,EACD,CAAC,CACF,GAAG;IACF,KAAK,EAAE,eAAe,CACpB,UAAU,CACR,eAAe,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,EAC9D,kBAAkB,CACnB,EACD,CAAC,CACF,CAAC;CACH,CAAC;AAEF;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,OAAO,EACf,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,kBAAkB,sBAW/B;AAED,uBAAe,UAAU,CAAC,CAAC,SAAS,MAAM;IACxC,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,WAAW,CAAC;IAEpB,SAAS,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,UAAU,CAAC,EAAE,aAAa,CAAC;IACrC,SAAS,CAAC,WAAW,EAAE,YAAY,GAAG,SAAS,CAAC;IAEhD,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;gBAEzC,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,mBAAmB;IA6BjD,WAAW;cAIF,QAAQ;IASjB,aAAa;IAIpB,SAAS,CAAC,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAC3D,QAAQ,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,kBAAkB,CAAC,GAChD,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC;IA0B1B,SAAS,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC;cAKrD,YAAY;CAe7B;AAED,eAAe,UAAU,CAAC"}
@@ -0,0 +1,96 @@
1
+ import createClient from "openapi-fetch";
2
+ export const ANALYTICS = "analytics";
3
+ /**
4
+ * This decorator is used to check if the baseUrl or token of the client are set.
5
+ * If the baseUrl or token are not set, it throws an error
6
+ */
7
+ export function needsBackend(target, propertyKey, descriptor) {
8
+ const originalMethod = descriptor.value;
9
+ descriptor.value = async function (...args) {
10
+ this.checkBackend();
11
+ return originalMethod.apply(this, args);
12
+ };
13
+ return descriptor;
14
+ }
15
+ class BaseClient {
16
+ baseUrl;
17
+ initialized;
18
+ token;
19
+ getTokenFn;
20
+ serviceName;
21
+ client;
22
+ constructor({ baseUrl, getTokenFn }) {
23
+ this.initialized = false;
24
+ if (baseUrl) {
25
+ this.baseUrl = baseUrl;
26
+ this.initialized = true;
27
+ }
28
+ if (getTokenFn) {
29
+ this.getTokenFn = getTokenFn;
30
+ }
31
+ this.token = undefined;
32
+ this.client = createClient({ baseUrl: this.baseUrl });
33
+ const authMiddleware = {
34
+ onRequest: async ({ request }) => {
35
+ if (!this.token && this.getTokenFn) {
36
+ this.token = await this.getTokenFn(this.serviceName);
37
+ }
38
+ if (this.token) {
39
+ request.headers.set("Authorization", `Bearer ${this.token}`);
40
+ }
41
+ return request;
42
+ },
43
+ };
44
+ this.client.use(authMiddleware);
45
+ }
46
+ deleteToken() {
47
+ this.token = undefined;
48
+ }
49
+ async getToken() {
50
+ if (this.getTokenFn) {
51
+ const token = await this.getTokenFn(this.serviceName);
52
+ this.token = token;
53
+ }
54
+ return this.token;
55
+ }
56
+ isInitialized() {
57
+ return this.initialized;
58
+ }
59
+ formatResponse(response) {
60
+ let outputData = undefined;
61
+ let outputMetadata = undefined;
62
+ if (!response) {
63
+ return {};
64
+ }
65
+ if (response.data) {
66
+ const dataEntries = Object.entries(response.data);
67
+ // by docs the body should contain a "data"
68
+ // properties with the response values
69
+ const containsData = dataEntries.find((x) => x[0] === "data");
70
+ const containsMetadata = dataEntries.find((x) => x[0] === "metadata");
71
+ if (containsMetadata) {
72
+ outputMetadata = containsMetadata[1];
73
+ }
74
+ outputData = containsData ? containsData[1] : response.data;
75
+ }
76
+ return {
77
+ data: outputData,
78
+ metadata: outputMetadata,
79
+ error: response.error,
80
+ };
81
+ }
82
+ formatError(reason) {
83
+ return { error: reason };
84
+ }
85
+ /* checkBackend is a protected method used by needsBackend decorator */
86
+ async checkBackend() {
87
+ const className = this.constructor.name;
88
+ if (!this.baseUrl) {
89
+ throw new Error(`${className} baseUrl is not set. Please provide a valid baseUrl when initializing ${className} SDK methods.`);
90
+ }
91
+ if (!this.token && !this.getTokenFn) {
92
+ throw new Error(`${className} token is not set. Please provide a valid getTokenFn function when initializing ${className} SDK methods.`);
93
+ }
94
+ }
95
+ }
96
+ export default BaseClient;