@blux.ai/web-sdk 0.0.5 → 0.0.6-tommy0

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 (115) hide show
  1. package/README.md +4 -4
  2. package/demo/craco.config.js +2 -0
  3. package/demo/package.json +4 -2
  4. package/demo/public/index.html +1 -1
  5. package/demo/tailwind.config.js +2 -0
  6. package/dist/BluxClient.d.ts +14 -13
  7. package/dist/BluxClient.js +180 -324
  8. package/dist/BluxClient.js.map +1 -1
  9. package/dist/apis/createEvent.d.ts +4 -0
  10. package/dist/apis/createEvent.js +7 -0
  11. package/dist/apis/createEvent.js.map +1 -0
  12. package/dist/apis/getItemRecommendation.d.ts +4 -0
  13. package/dist/apis/getItemRecommendation.js +7 -0
  14. package/dist/apis/getItemRecommendation.js.map +1 -0
  15. package/dist/apis/initialize.d.ts +4 -0
  16. package/dist/apis/initialize.js +7 -0
  17. package/dist/apis/initialize.js.map +1 -0
  18. package/dist/apis/signIn.d.ts +4 -0
  19. package/dist/apis/signIn.js +7 -0
  20. package/dist/apis/signIn.js.map +1 -0
  21. package/dist/apis/signOut.d.ts +4 -0
  22. package/dist/apis/signOut.js +7 -0
  23. package/dist/apis/signOut.js.map +1 -0
  24. package/dist/apis/updateCustomUserProperties.d.ts +4 -0
  25. package/dist/apis/updateCustomUserProperties.js +7 -0
  26. package/dist/apis/updateCustomUserProperties.js.map +1 -0
  27. package/dist/apis/updateUserProperties.d.ts +4 -0
  28. package/dist/apis/updateUserProperties.js +7 -0
  29. package/dist/apis/updateUserProperties.js.map +1 -0
  30. package/dist/constants/URLS.d.ts +1 -7
  31. package/dist/constants/URLS.js +3 -15
  32. package/dist/constants/URLS.js.map +1 -1
  33. package/dist/events/AddCartaddEvent.d.ts +2 -2
  34. package/dist/events/AddCartaddEvent.js +9 -40
  35. package/dist/events/AddCartaddEvent.js.map +1 -1
  36. package/dist/events/AddCustomEvent.d.ts +2 -2
  37. package/dist/events/AddCustomEvent.js +11 -42
  38. package/dist/events/AddCustomEvent.js.map +1 -1
  39. package/dist/events/AddLikeEvent.d.ts +2 -2
  40. package/dist/events/AddLikeEvent.js +9 -40
  41. package/dist/events/AddLikeEvent.js.map +1 -1
  42. package/dist/events/AddPageViewEvent.d.ts +2 -2
  43. package/dist/events/AddPageViewEvent.js +9 -38
  44. package/dist/events/AddPageViewEvent.js.map +1 -1
  45. package/dist/events/AddProductDetailViewEvent.d.ts +2 -2
  46. package/dist/events/AddProductDetailViewEvent.js +11 -41
  47. package/dist/events/AddProductDetailViewEvent.js.map +1 -1
  48. package/dist/events/AddPurchaseEvent.d.ts +2 -2
  49. package/dist/events/AddPurchaseEvent.js +11 -39
  50. package/dist/events/AddPurchaseEvent.js.map +1 -1
  51. package/dist/events/AddRateEvent.d.ts +2 -2
  52. package/dist/events/AddRateEvent.js +9 -40
  53. package/dist/events/AddRateEvent.js.map +1 -1
  54. package/dist/events/AddRecommendationViewEvent.d.ts +2 -2
  55. package/dist/events/AddRecommendationViewEvent.js +8 -39
  56. package/dist/events/AddRecommendationViewEvent.js.map +1 -1
  57. package/dist/events/Event.d.ts +2 -2
  58. package/dist/events/Event.js +11 -25
  59. package/dist/events/Event.js.map +1 -1
  60. package/dist/events/VisitEvent.d.ts +5 -0
  61. package/dist/events/VisitEvent.js +11 -0
  62. package/dist/events/VisitEvent.js.map +1 -0
  63. package/dist/events/index.js +9 -28
  64. package/dist/events/index.js.map +1 -1
  65. package/dist/events/types.d.ts +6 -10
  66. package/dist/events/types.js +2 -6
  67. package/dist/events/types.js.map +1 -1
  68. package/dist/index.d.ts +3 -1
  69. package/dist/index.js +6 -23
  70. package/dist/index.js.map +1 -1
  71. package/dist/recommendations/ItemRecommendation.d.ts +5 -0
  72. package/dist/recommendations/ItemRecommendation.js +12 -0
  73. package/dist/recommendations/ItemRecommendation.js.map +1 -0
  74. package/dist/recommendations/Recommendation.d.ts +5 -0
  75. package/dist/recommendations/Recommendation.js +9 -0
  76. package/dist/recommendations/Recommendation.js.map +1 -0
  77. package/dist/recommendations/index.d.ts +1 -0
  78. package/dist/recommendations/index.js +2 -0
  79. package/dist/recommendations/index.js.map +1 -0
  80. package/dist/recommendations/types.d.ts +11 -0
  81. package/dist/recommendations/types.js +2 -0
  82. package/dist/recommendations/types.js.map +1 -0
  83. package/dist/utils/LocalStorage.js +14 -0
  84. package/dist/utils/LocalStorage.js.map +1 -0
  85. package/dist/{core → utils}/Logger.d.ts +1 -1
  86. package/dist/utils/Logger.js +49 -0
  87. package/dist/utils/Logger.js.map +1 -0
  88. package/dist/utils/getPath.d.ts +1 -0
  89. package/dist/utils/getPath.js +4 -0
  90. package/dist/utils/getPath.js.map +1 -0
  91. package/dist/utils/helper.js +2 -9
  92. package/dist/utils/helper.js.map +1 -1
  93. package/dist/utils/operators.d.ts +1 -1
  94. package/dist/utils/operators.js +5 -11
  95. package/dist/utils/operators.js.map +1 -1
  96. package/package.json +7 -6
  97. package/.prettierrc +0 -4
  98. package/.sentryclirc +0 -3
  99. package/demo/README.md +0 -46
  100. package/demo/src/App.test.tsx +0 -9
  101. package/demo/src/App.tsx +0 -158
  102. package/demo/src/index.css +0 -16
  103. package/demo/src/index.tsx +0 -19
  104. package/demo/src/react-app-env.d.ts +0 -1
  105. package/demo/src/reportWebVitals.ts +0 -15
  106. package/demo/src/setupTests.ts +0 -5
  107. package/demo/yarn.lock +0 -10120
  108. package/dist/core/LocalStorage.js +0 -21
  109. package/dist/core/LocalStorage.js.map +0 -1
  110. package/dist/core/Logger.js +0 -88
  111. package/dist/core/Logger.js.map +0 -1
  112. package/dist/utils/sentry.d.ts +0 -2
  113. package/dist/utils/sentry.js +0 -50
  114. package/dist/utils/sentry.js.map +0 -1
  115. /package/dist/{core → utils}/LocalStorage.d.ts +0 -0
package/README.md CHANGED
@@ -90,7 +90,7 @@ BluxClient.signOut();
90
90
  BluxClient.sendEvent(
91
91
  new AddProductDetailViewEvent({
92
92
  itemId: "ITEM_ID",
93
- })
93
+ }),
94
94
  );
95
95
  ```
96
96
 
@@ -104,7 +104,7 @@ BluxClient.sendEvent(
104
104
  BluxClient.sendEvent(
105
105
  new AddLikeEvent({
106
106
  itemId: "ITEM_ID",
107
- })
107
+ }),
108
108
  );
109
109
  ```
110
110
 
@@ -118,7 +118,7 @@ BluxClient.sendEvent(
118
118
  BluxClient.sendEvent(
119
119
  new AddCartaddEvent({
120
120
  itemId: "ITEM_ID",
121
- })
121
+ }),
122
122
  );
123
123
  ```
124
124
 
@@ -138,7 +138,7 @@ BluxClient.sendEvent(
138
138
  new AddPurchaseEvent({
139
139
  itemId: "ITEM_ID",
140
140
  price: 1000,
141
- })
141
+ }),
142
142
  );
143
143
  ```
144
144
 
@@ -1,3 +1,5 @@
1
+ /* eslint-disable no-undef */
2
+
1
3
  module.exports = {
2
4
  webpack: {
3
5
  configure: (config) => {
package/demo/package.json CHANGED
@@ -3,10 +3,9 @@
3
3
  "version": "0.1.0",
4
4
  "private": true,
5
5
  "dependencies": {
6
- "@blux.ai/web-sdk": "../",
6
+ "@blux.ai/web-sdk": "workspace:*",
7
7
  "@testing-library/jest-dom": "^5.14.1",
8
8
  "@testing-library/react": "^13.0.0",
9
- "@testing-library/user-event": "^13.2.1",
10
9
  "@types/jest": "^27.0.1",
11
10
  "@types/node": "^16.7.13",
12
11
  "@types/react": "^18.0.0",
@@ -44,5 +43,8 @@
44
43
  "devDependencies": {
45
44
  "@craco/craco": "^7.1.0",
46
45
  "tailwindcss": "^3.4.4"
46
+ },
47
+ "installConfig": {
48
+ "hoistingLimits": "workspaces"
47
49
  }
48
50
  }
@@ -1,4 +1,4 @@
1
- <!DOCTYPE html>
1
+ <!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8" />
@@ -1,3 +1,5 @@
1
+ /* eslint-disable no-undef */
2
+
1
3
  /** @type {import('tailwindcss').Config} */
2
4
  module.exports = {
3
5
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
@@ -1,8 +1,9 @@
1
- import "./utils/sentry";
2
1
  import { BehaviorSubject } from "rxjs";
3
- import { LogLevel } from "./core/Logger";
4
- import { EventRequest } from "./events/types";
5
- import { Event } from "./events/Event";
2
+ import type { LogLevel } from "./utils/Logger";
3
+ import type { EventRequest } from "./events/types";
4
+ import type { Event } from "./events/Event";
5
+ import type { ItemRecommendationResponse } from "@blux.ai/common";
6
+ import type { Recommendation } from "./recommendations/Recommendation";
6
7
  export type SdkInfo = {
7
8
  type: string;
8
9
  version: string;
@@ -10,23 +11,22 @@ export type SdkInfo = {
10
11
  type BluxUser = {
11
12
  id: string;
12
13
  bluxApiKey: string;
13
- organizationId: string;
14
+ applicationId: string;
14
15
  deviceId: string;
15
16
  userId?: string;
16
17
  };
17
- declare class BluxClient {
18
+ export declare class BluxClient {
18
19
  private readonly STAGE;
19
- private readonly identifierApi;
20
- private readonly collectorApi;
20
+ private readonly api;
21
21
  private readonly sdkInfo;
22
22
  readonly bluxUser$: BehaviorSubject<BluxUser | undefined>;
23
23
  readonly requestQueue$: BehaviorSubject<EventRequest[]>;
24
24
  constructor(STAGE?: "local" | "dev" | "stg" | "prod");
25
- private generateIdentifierHeader;
26
- init({ bluxClientId: organizationId, bluxApiKey, }: {
27
- bluxClientId: string;
25
+ private generateApiHeader;
26
+ init({ applicationId, bluxApiKey, }: {
27
+ applicationId: string;
28
28
  bluxApiKey: string;
29
- }): Promise<void>;
29
+ }): Promise<boolean>;
30
30
  setLogLevel(logLevel: LogLevel): void;
31
31
  private getBluxUserWithTimeout;
32
32
  signIn(userId: string): Promise<void>;
@@ -36,7 +36,8 @@ declare class BluxClient {
36
36
  email_address?: string;
37
37
  }): Promise<void>;
38
38
  setCustomUserProperties(customUserProperties: Record<string, string | boolean | number | null>): Promise<void>;
39
- sendEvent(event: Event | Event[]): Promise<void>;
39
+ sendEvent(event: Event | Event[]): void;
40
+ getItemRecommendation(recommendation: Recommendation): Promise<ItemRecommendationResponse>;
40
41
  }
41
42
  export declare const bluxClient: BluxClient;
42
43
  export {};
@@ -1,334 +1,190 @@
1
- "use strict";
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a3d74585-c9aa-5c56-8a6b-1bf7035d4bc4")}catch(e){}}();
3
-
4
- var __assign = (this && this.__assign) || function () {
5
- __assign = Object.assign || function(t) {
6
- for (var s, i = 1, n = arguments.length; i < n; i++) {
7
- s = arguments[i];
8
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
9
- t[p] = s[p];
10
- }
11
- return t;
1
+ import { asyncScheduler, BehaviorSubject, catchError, exhaustMap, filter, firstValueFrom, map, observeOn, throwError, timeout, withLatestFrom, } from "rxjs";
2
+ import { LocalStorage } from "./utils/LocalStorage";
3
+ import { Logger } from "./utils/Logger";
4
+ import axios from "axios";
5
+ import { filterNullable } from "./utils/operators";
6
+ import { API_URL_BY_STAGE } from "./constants/URLS";
7
+ import { DevicePlatform } from "@blux.ai/common";
8
+ import { initialize } from "./apis/initialize";
9
+ import { signIn } from "./apis/signIn";
10
+ import { signOut } from "./apis/signOut";
11
+ import { updateUserProperties } from "./apis/updateUserProperties";
12
+ import { updateCustomUserProperties } from "./apis/updateCustomUserProperties";
13
+ import { collectEvent } from "./apis/createEvent";
14
+ import { VisitEvent } from "./events/VisitEvent";
15
+ import { getItemRecommendation } from "./apis/getItemRecommendation";
16
+ export class BluxClient {
17
+ STAGE;
18
+ api;
19
+ sdkInfo = {
20
+ type: "browser",
21
+ version: "0.0.3",
12
22
  };
13
- return __assign.apply(this, arguments);
14
- };
15
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
17
- return new (P || (P = Promise))(function (resolve, reject) {
18
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
20
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21
- step((generator = generator.apply(thisArg, _arguments || [])).next());
22
- });
23
- };
24
- var __generator = (this && this.__generator) || function (thisArg, body) {
25
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
26
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
27
- function verb(n) { return function (v) { return step([n, v]); }; }
28
- function step(op) {
29
- if (f) throw new TypeError("Generator is already executing.");
30
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
31
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
32
- if (y = 0, t) op = [op[0] & 2, t.value];
33
- switch (op[0]) {
34
- case 0: case 1: t = op; break;
35
- case 4: _.label++; return { value: op[1], done: false };
36
- case 5: _.label++; y = op[1]; op = [0]; continue;
37
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
38
- default:
39
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
40
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
41
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
42
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
43
- if (t[2]) _.ops.pop();
44
- _.trys.pop(); continue;
45
- }
46
- op = body.call(thisArg, _);
47
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
48
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
49
- }
50
- };
51
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
52
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
53
- if (ar || !(i in from)) {
54
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
55
- ar[i] = from[i];
56
- }
57
- }
58
- return to.concat(ar || Array.prototype.slice.call(from));
59
- };
60
- var __importDefault = (this && this.__importDefault) || function (mod) {
61
- return (mod && mod.__esModule) ? mod : { "default": mod };
62
- };
63
- exports.__esModule = true;
64
- exports.bluxClient = void 0;
65
- require("./utils/sentry");
66
- var rxjs_1 = require("rxjs");
67
- var LocalStorage_1 = require("./core/LocalStorage");
68
- var Logger_1 = require("./core/Logger");
69
- var axios_1 = __importDefault(require("axios"));
70
- var operators_1 = require("./utils/operators");
71
- var URLS_1 = require("./constants/URLS");
72
- var sentry_1 = require("./utils/sentry");
73
- var BluxClient = /** @class */ (function () {
74
- function BluxClient(STAGE) {
75
- if (STAGE === void 0) { STAGE = "prod"; }
76
- var _this = this;
23
+ bluxUser$ = new BehaviorSubject(undefined);
24
+ requestQueue$ = new BehaviorSubject([]);
25
+ constructor(STAGE = "prod") {
77
26
  this.STAGE = STAGE;
78
- this.identifierApi = axios_1["default"].create({
79
- baseURL: URLS_1.IDENTIFIER_API_URL_BY_STAGE[this.STAGE]
80
- });
81
- this.collectorApi = axios_1["default"].create({
82
- baseURL: URLS_1.COLLECTOR_API_URL_BY_STAGE[this.STAGE],
83
- headers: {
84
- "Content-Type": "application/json;charset=UTF-8",
85
- Accept: "application/json"
86
- }
27
+ this.api = axios.create({
28
+ baseURL: API_URL_BY_STAGE[this.STAGE],
87
29
  });
88
- this.sdkInfo = {
89
- type: "browser",
90
- version: "0.0.3"
91
- };
92
- this.bluxUser$ = new rxjs_1.BehaviorSubject(undefined);
93
- this.requestQueue$ = new rxjs_1.BehaviorSubject([]);
94
30
  this.requestQueue$
95
- .pipe((0, rxjs_1.filter)(function (queue) { return queue.length > 0; }), (0, rxjs_1.concatMap)(function (requests) {
96
- return (0, rxjs_1.from)(requests.map(function (request, idx) { return ({ request: request, idx: idx }); })).pipe((0, rxjs_1.withLatestFrom)(_this.bluxUser$.pipe((0, operators_1.filterNullable)())), (0, rxjs_1.concatMap)(function (_a) {
97
- var _b = _a[0], request = _b.request, idx = _b.idx, bluxUser = _a[1];
98
- return __awaiter(_this, void 0, void 0, function () {
99
- var body, error_1;
100
- return __generator(this, function (_c) {
101
- switch (_c.label) {
102
- case 0:
103
- body = JSON.stringify(__assign(__assign({}, request), { user_id: bluxUser.userId, blux_id: bluxUser.id, device_id: bluxUser.deviceId, timetsamp: request.timestamp + 1e-6 * idx }));
104
- _c.label = 1;
105
- case 1:
106
- _c.trys.push([1, 3, , 4]);
107
- return [4 /*yield*/, this.collectorApi.post("/events", body, {
108
- headers: {
109
- "X-BLUX-SDK-INFO": "".concat(this.sdkInfo.type, "-").concat(this.sdkInfo.version),
110
- "X-BLUX-CLIENT-ID": bluxUser.organizationId,
111
- "X-BLUX-API-KEY": bluxUser.bluxApiKey,
112
- "X-BLUX-TIMESTAMP": Math.floor(Date.now() / 1000).toString()
113
- }
114
- })];
115
- case 2:
116
- _c.sent(); // todo : retry & send with batch
117
- return [3 /*break*/, 4];
118
- case 3:
119
- error_1 = _c.sent();
120
- Logger_1.Logger.error(error_1, { tags: { from: "request-events-api" } });
121
- return [3 /*break*/, 4];
122
- case 4: return [2 /*return*/, requests.map(function (r) { return r.id; })]; // todo: return successed requests only
123
- }
124
- });
125
- });
126
- }));
127
- }), (0, rxjs_1.map)(function (requestIdsSucceeded) {
128
- return _this.requestQueue$.value.filter(function (request) { return !requestIdsSucceeded.includes(request.id); });
129
- }))
31
+ .pipe(filter((queue) => queue.length > 0), withLatestFrom(this.bluxUser$.pipe(filterNullable())), exhaustMap(async ([requests, bluxUser]) => {
32
+ try {
33
+ await collectEvent(this.api, {
34
+ blux_user_id: bluxUser.id,
35
+ application_id: bluxUser.applicationId,
36
+ }, {
37
+ events: requests.map((request) => ({
38
+ ...request,
39
+ user_id: bluxUser.userId,
40
+ blux_id: bluxUser.id,
41
+ device_id: bluxUser.deviceId,
42
+ })),
43
+ }, this.generateApiHeader(bluxUser));
44
+ }
45
+ catch (error) {
46
+ // todo : retry
47
+ Logger.error(error, { tags: { from: "request-events-api" } });
48
+ }
49
+ return requests.map((r) => r.id); // todo: return successed requests only
50
+ }), map((requestIdsSucceeded) => this.requestQueue$.value.filter((request) => !requestIdsSucceeded.includes(request.id))), observeOn(asyncScheduler))
130
51
  .subscribe(this.requestQueue$);
131
52
  }
132
- BluxClient.prototype.generateIdentifierHeader = function (_a) {
133
- var bluxApiKey = _a.bluxApiKey;
53
+ generateApiHeader({ bluxApiKey }) {
134
54
  return {
135
- Authorization: bluxApiKey
55
+ Authorization: bluxApiKey,
136
56
  };
137
- };
138
- BluxClient.prototype.init = function (_a) {
139
- var organizationId = _a.bluxClientId, bluxApiKey = _a.bluxApiKey;
140
- return __awaiter(this, void 0, void 0, function () {
141
- var deviceId, _b, blux_user_id, device_id, error_2;
142
- return __generator(this, function (_c) {
143
- switch (_c.label) {
144
- case 0:
145
- sentry_1.Sentry.setTag("bluxClientId", organizationId);
146
- _c.label = 1;
147
- case 1:
148
- _c.trys.push([1, 3, , 4]);
149
- Logger_1.Logger.debug("Init with client id: " + organizationId);
150
- deviceId = LocalStorage_1.LocalStorage.getDeviceId();
151
- if (!deviceId) {
152
- Logger_1.Logger.debug("Saved Device ID is not exists, newly registered.");
153
- }
154
- return [4 /*yield*/, this.identifierApi.post("/organizations/".concat(organizationId, "/blux-users/initialize"), {
155
- device_id: deviceId !== null && deviceId !== void 0 ? deviceId : undefined,
156
- country_code: navigator.language.split("-")[1],
157
- device_model: navigator.userAgent,
158
- language_code: navigator.language.split("-")[0],
159
- platform: "browser",
160
- os_version: navigator.userAgent,
161
- sdk_version: this.sdkInfo.version,
162
- sdk_type: this.sdkInfo.type,
163
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
164
- }, {
165
- headers: this.generateIdentifierHeader({
166
- bluxApiKey: bluxApiKey
167
- })
168
- })];
169
- case 2:
170
- _b = (_c.sent()).data, blux_user_id = _b.blux_user_id, device_id = _b.device_id;
171
- console.log({ device_id: device_id });
172
- LocalStorage_1.LocalStorage.setDeviceId(device_id);
173
- this.bluxUser$.next({
174
- id: blux_user_id,
175
- bluxApiKey: bluxApiKey,
176
- organizationId: organizationId,
177
- deviceId: device_id
178
- });
179
- return [3 /*break*/, 4];
180
- case 3:
181
- error_2 = _c.sent();
182
- Logger_1.Logger.error(error_2, { tags: { from: "init" } });
183
- return [3 /*break*/, 4];
184
- case 4: return [2 /*return*/];
185
- }
186
- });
187
- });
188
- };
189
- BluxClient.prototype.setLogLevel = function (logLevel) {
190
- Logger_1.Logger.setLevel(logLevel);
191
- };
192
- BluxClient.prototype.getBluxUserWithTimeout = function () {
193
- return __awaiter(this, void 0, void 0, function () {
194
- var bluxUser;
195
- return __generator(this, function (_a) {
196
- switch (_a.label) {
197
- case 0: return [4 /*yield*/, (0, rxjs_1.firstValueFrom)(this.bluxUser$.pipe((0, operators_1.filterNullable)(), (0, rxjs_1.timeout)(5000), (0, rxjs_1.catchError)(function (error) {
198
- return (0, rxjs_1.throwError)(function () {
199
- return error.name === "TimeoutError"
200
- ? new Error("Client ID is not intialized. Please initialize BluxClient.")
201
- : error;
202
- });
203
- })))];
204
- case 1:
205
- bluxUser = _a.sent();
206
- return [2 /*return*/, bluxUser];
207
- }
208
- });
209
- });
210
- };
211
- BluxClient.prototype.signIn = function (userId) {
212
- return __awaiter(this, void 0, void 0, function () {
213
- var bluxUser, bluxIdInResponse, error_3;
214
- return __generator(this, function (_a) {
215
- switch (_a.label) {
216
- case 0:
217
- _a.trys.push([0, 3, , 4]);
218
- return [4 /*yield*/, this.getBluxUserWithTimeout()];
219
- case 1:
220
- bluxUser = _a.sent();
221
- return [4 /*yield*/, this.identifierApi.put("/organizations/".concat(bluxUser.organizationId, "/blux-users/").concat(bluxUser.id, "/sign-in"), { user_id: userId }, {
222
- headers: this.generateIdentifierHeader(bluxUser)
223
- })];
224
- case 2:
225
- bluxIdInResponse = (_a.sent()).data.blux_user_id;
226
- if (bluxIdInResponse !== bluxUser.id) {
227
- Logger_1.Logger.debug("Blux id is changed in signIn.");
228
- this.bluxUser$.next(__assign(__assign({}, bluxUser), { id: bluxIdInResponse }));
229
- }
230
- return [3 /*break*/, 4];
231
- case 3:
232
- error_3 = _a.sent();
233
- Logger_1.Logger.error(error_3, { tags: { from: "signIn" } });
234
- return [3 /*break*/, 4];
235
- case 4: return [2 /*return*/];
236
- }
237
- });
238
- });
239
- };
240
- BluxClient.prototype.signOut = function () {
241
- return __awaiter(this, void 0, void 0, function () {
242
- var bluxUser, bluxIdInResponse, error_4;
243
- return __generator(this, function (_a) {
244
- switch (_a.label) {
245
- case 0:
246
- _a.trys.push([0, 3, , 4]);
247
- return [4 /*yield*/, this.getBluxUserWithTimeout()];
248
- case 1:
249
- bluxUser = _a.sent();
250
- return [4 /*yield*/, this.identifierApi.put("/organizations/".concat(bluxUser.organizationId, "/blux-users/").concat(bluxUser.id, "/sign-out"), { device_id: bluxUser.deviceId }, {
251
- headers: this.generateIdentifierHeader(bluxUser)
252
- })];
253
- case 2:
254
- bluxIdInResponse = (_a.sent()).data.blux_user_id;
255
- Logger_1.Logger.debug("Blux id is changed in signOut.");
256
- this.bluxUser$.next(__assign(__assign({}, bluxUser), { id: bluxIdInResponse }));
257
- return [3 /*break*/, 4];
258
- case 3:
259
- error_4 = _a.sent();
260
- Logger_1.Logger.error(error_4, { tags: { from: "signOut" } });
261
- return [3 /*break*/, 4];
262
- case 4: return [2 /*return*/];
263
- }
264
- });
265
- });
266
- };
267
- BluxClient.prototype.setUserProperties = function (userProperties) {
268
- return __awaiter(this, void 0, void 0, function () {
269
- var bluxUser, error_5;
270
- return __generator(this, function (_a) {
271
- switch (_a.label) {
272
- case 0:
273
- _a.trys.push([0, 3, , 4]);
274
- return [4 /*yield*/, this.getBluxUserWithTimeout()];
275
- case 1:
276
- bluxUser = _a.sent();
277
- return [4 /*yield*/, this.identifierApi.put("/organizations/".concat(bluxUser.organizationId, "/blux-users/").concat(bluxUser.id, "/update-user-properties"), { properties: userProperties }, {
278
- headers: this.generateIdentifierHeader(bluxUser)
279
- })];
280
- case 2:
281
- _a.sent();
282
- return [3 /*break*/, 4];
283
- case 3:
284
- error_5 = _a.sent();
285
- Logger_1.Logger.error(error_5, { tags: { from: "setUserProperties" } });
286
- return [3 /*break*/, 4];
287
- case 4: return [2 /*return*/];
288
- }
289
- });
290
- });
291
- };
292
- BluxClient.prototype.setCustomUserProperties = function (customUserProperties) {
293
- return __awaiter(this, void 0, void 0, function () {
294
- var bluxUser, error_6;
295
- return __generator(this, function (_a) {
296
- switch (_a.label) {
297
- case 0:
298
- _a.trys.push([0, 3, , 4]);
299
- return [4 /*yield*/, this.getBluxUserWithTimeout()];
300
- case 1:
301
- bluxUser = _a.sent();
302
- return [4 /*yield*/, this.identifierApi.put("/organizations/".concat(bluxUser.organizationId, "/blux-users/").concat(bluxUser.id, "/update-custom-user-properties"), { properties: customUserProperties }, {
303
- headers: this.generateIdentifierHeader(bluxUser)
304
- })];
305
- case 2:
306
- _a.sent();
307
- return [3 /*break*/, 4];
308
- case 3:
309
- error_6 = _a.sent();
310
- Logger_1.Logger.error(error_6, { tags: { from: "setCustomUserProperties" } });
311
- return [3 /*break*/, 4];
312
- case 4: return [2 /*return*/];
313
- }
57
+ }
58
+ async init({ applicationId, bluxApiKey, }) {
59
+ this.sendEvent(new VisitEvent({}));
60
+ try {
61
+ Logger.debug(`Init with application id: ${applicationId}`);
62
+ const deviceId = LocalStorage.getDeviceId();
63
+ if (!deviceId) {
64
+ Logger.debug("Saved Device ID is not exists, newly registered.");
65
+ }
66
+ const { data: { blux_user_id, device_id }, } = await initialize(this.api, { application_id: applicationId }, {
67
+ isVisitHandlingInSdk: true,
68
+ device_id: deviceId ?? undefined,
69
+ country_code: navigator.language.split("-")[1],
70
+ device_model: navigator.userAgent,
71
+ language_code: navigator.language.split("-")[0],
72
+ platform: DevicePlatform.browser,
73
+ os_version: navigator.userAgent,
74
+ sdk_version: this.sdkInfo.version,
75
+ sdk_type: this.sdkInfo.type,
76
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
77
+ }, this.generateApiHeader({
78
+ bluxApiKey,
79
+ }));
80
+ LocalStorage.setDeviceId(device_id);
81
+ this.bluxUser$.next({
82
+ id: blux_user_id,
83
+ bluxApiKey,
84
+ applicationId,
85
+ deviceId: device_id,
314
86
  });
315
- });
316
- };
317
- BluxClient.prototype.sendEvent = function (event) {
318
- return __awaiter(this, void 0, void 0, function () {
319
- var requests;
320
- var _this = this;
321
- return __generator(this, function (_a) {
322
- requests = (Array.isArray(event) ? event : [event]).map(function (event) { return event.request; });
323
- this.requestQueue$.next(__spreadArray(__spreadArray([], this.requestQueue$.value, true), requests.filter(function (request) {
324
- return !_this.requestQueue$.value.map(function (r) { return r.id; }).includes(request.id);
325
- }), true));
326
- return [2 /*return*/];
87
+ return true;
88
+ }
89
+ catch (error) {
90
+ Logger.error(error, { tags: { from: "init" } });
91
+ return false;
92
+ }
93
+ }
94
+ setLogLevel(logLevel) {
95
+ Logger.setLevel(logLevel);
96
+ }
97
+ async getBluxUserWithTimeout() {
98
+ const bluxUser = await firstValueFrom(this.bluxUser$.pipe(filterNullable(), timeout(5000), catchError((error) => {
99
+ return throwError(() => error.name === "TimeoutError"
100
+ ? new Error("Application ID is not intialized. Please initialize BluxClient.")
101
+ : error);
102
+ })));
103
+ return bluxUser;
104
+ }
105
+ async signIn(userId) {
106
+ try {
107
+ const bluxUser = await this.getBluxUserWithTimeout();
108
+ const { data: { blux_user_id: bluxIdInResponse }, } = await signIn(this.api, { application_id: bluxUser.applicationId, blux_user_id: bluxUser.id }, { user_id: userId, device_id: bluxUser.deviceId }, this.generateApiHeader(bluxUser));
109
+ if (bluxIdInResponse !== bluxUser.id) {
110
+ Logger.debug("Blux id is changed in signIn.");
111
+ this.bluxUser$.next({
112
+ ...bluxUser,
113
+ id: bluxIdInResponse,
114
+ });
115
+ }
116
+ }
117
+ catch (error) {
118
+ Logger.error(error, { tags: { from: "signIn" } });
119
+ }
120
+ }
121
+ async signOut() {
122
+ try {
123
+ const bluxUser = await this.getBluxUserWithTimeout();
124
+ const { data: { blux_user_id: bluxIdInResponse }, } = await signOut(this.api, { application_id: bluxUser.applicationId, blux_user_id: bluxUser.id }, { device_id: bluxUser.deviceId }, this.generateApiHeader(bluxUser));
125
+ Logger.debug("Blux id is changed in signOut.");
126
+ this.bluxUser$.next({
127
+ ...bluxUser,
128
+ id: bluxIdInResponse,
327
129
  });
328
- });
329
- };
330
- return BluxClient;
331
- }());
332
- exports.bluxClient = new BluxClient("prod");
333
- //# sourceMappingURL=BluxClient.js.map
334
- //# debugId=a3d74585-c9aa-5c56-8a6b-1bf7035d4bc4
130
+ }
131
+ catch (error) {
132
+ Logger.error(error, { tags: { from: "signOut" } });
133
+ }
134
+ }
135
+ async setUserProperties(userProperties) {
136
+ try {
137
+ const bluxUser = await this.getBluxUserWithTimeout();
138
+ await updateUserProperties(this.api, { application_id: bluxUser.applicationId, blux_user_id: bluxUser.id }, { properties: userProperties }, this.generateApiHeader(bluxUser));
139
+ }
140
+ catch (error) {
141
+ Logger.error(error, { tags: { from: "setUserProperties" } });
142
+ }
143
+ }
144
+ async setCustomUserProperties(customUserProperties) {
145
+ try {
146
+ const bluxUser = await this.getBluxUserWithTimeout();
147
+ await updateCustomUserProperties(this.api, { application_id: bluxUser.applicationId, blux_user_id: bluxUser.id }, { properties: customUserProperties }, this.generateApiHeader(bluxUser));
148
+ }
149
+ catch (error) {
150
+ Logger.error(error, { tags: { from: "setCustomUserProperties" } });
151
+ }
152
+ }
153
+ sendEvent(event) {
154
+ const requests = (Array.isArray(event) ? event : [event]).map((event) => event.request);
155
+ this.requestQueue$.next([
156
+ ...this.requestQueue$.value,
157
+ ...requests.filter((request) => !this.requestQueue$.value.map((r) => r.id).includes(request.id)),
158
+ ]);
159
+ }
160
+ async getItemRecommendation(recommendation) {
161
+ try {
162
+ const bluxUser = await this.getBluxUserWithTimeout();
163
+ const recommendationRequest = recommendation.request;
164
+ const recommendationResponse = await getItemRecommendation(this.api, {
165
+ application_id: bluxUser.applicationId,
166
+ blux_user_id: bluxUser.id,
167
+ }, {
168
+ call_type: recommendationRequest.call_type,
169
+ limit: recommendationRequest.limit,
170
+ offset: recommendationRequest.offset,
171
+ item_ids: recommendationRequest.item_ids,
172
+ }, this.generateApiHeader(bluxUser));
173
+ return recommendationResponse.data;
174
+ }
175
+ catch (error) {
176
+ Logger.error(error, { tags: { from: "getItemRecommendation" } });
177
+ return {
178
+ items: [],
179
+ metadata: {},
180
+ status: {
181
+ is_success: false,
182
+ code: 400,
183
+ message: error.message,
184
+ },
185
+ };
186
+ }
187
+ }
188
+ }
189
+ export const bluxClient = new BluxClient("prod");
190
+ //# sourceMappingURL=BluxClient.js.map