@nuvei-connect/nc-websdk 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -3
- package/dist/cdn-index.js +890 -7
- package/dist/cdn-index.min.js +3 -0
- package/dist/core/index.d.ts +3 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +28 -9
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -7,15 +7,16 @@ The **Nuvei WebSDK** allows third-party applications to easily embed Micro Front
|
|
|
7
7
|
Install the SDK from npm:
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npm install nc-
|
|
10
|
+
npm install @nuvei-connect/nc-websdk
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
## 🚀 Usage
|
|
14
14
|
|
|
15
|
-
Import and mount the SDK
|
|
15
|
+
Import and mount the SDK. The container must be mounted in the DOM before calling
|
|
16
|
+
`NuveiSDK.mount()`:
|
|
16
17
|
|
|
17
18
|
```typescript
|
|
18
|
-
import
|
|
19
|
+
import NuveiSDK from "@nuvei-connect/nc-websdk";
|
|
19
20
|
|
|
20
21
|
const instance = await NuveiSDK.mount({
|
|
21
22
|
componentName: moduleName,
|
|
@@ -27,6 +28,90 @@ const instance = await NuveiSDK.mount({
|
|
|
27
28
|
});
|
|
28
29
|
```
|
|
29
30
|
|
|
31
|
+
The `mount()` call returns an SDK instance. Keep the instance and call `destroy()`
|
|
32
|
+
when the host component is unmounted or the integration is no longer needed.
|
|
33
|
+
|
|
34
|
+
### ⚛️ React example
|
|
35
|
+
|
|
36
|
+
Keep the SDK container rendered independently from the loading state. If a loader
|
|
37
|
+
conditionally replaces the container, `containerRef.current` will be `null` when
|
|
38
|
+
the SDK is initialized.
|
|
39
|
+
|
|
40
|
+
```tsx
|
|
41
|
+
"use client";
|
|
42
|
+
|
|
43
|
+
import { useEffect, useRef, useState } from "react";
|
|
44
|
+
import NuveiSDK from "@nuvei-connect/nc-websdk";
|
|
45
|
+
|
|
46
|
+
async function fetchClientSession() {
|
|
47
|
+
const response = await fetch("/api/sdk/session", { method: "POST" });
|
|
48
|
+
return response.json();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function refreshClientSession(payload: {
|
|
52
|
+
accessToken: string;
|
|
53
|
+
refreshToken: string;
|
|
54
|
+
}) {
|
|
55
|
+
const response = await fetch("/api/sdk/session/refresh", {
|
|
56
|
+
method: "POST",
|
|
57
|
+
headers: { "Content-Type": "application/json" },
|
|
58
|
+
body: JSON.stringify(payload),
|
|
59
|
+
});
|
|
60
|
+
return response.json();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function destroySession() {
|
|
64
|
+
const response = await fetch("/api/sdk/session", { method: "POST" });
|
|
65
|
+
return response.ok;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function MicroFrontend({ componentName }: { componentName: string }) {
|
|
69
|
+
const containerRef = useRef<HTMLDivElement>(null);
|
|
70
|
+
const instanceRef = useRef<any>(null);
|
|
71
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
72
|
+
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
let isMounted = true;
|
|
75
|
+
|
|
76
|
+
async function initialize() {
|
|
77
|
+
if (!containerRef.current) return;
|
|
78
|
+
|
|
79
|
+
const instance = await NuveiSDK.mount({
|
|
80
|
+
componentName,
|
|
81
|
+
container: containerRef.current,
|
|
82
|
+
fetchClientSession,
|
|
83
|
+
refreshClientSession,
|
|
84
|
+
destroySession,
|
|
85
|
+
config: { environment: "preprod" },
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (!isMounted) {
|
|
89
|
+
instance.destroy();
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
instanceRef.current = instance;
|
|
94
|
+
setIsLoading(false);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
void initialize();
|
|
98
|
+
|
|
99
|
+
return () => {
|
|
100
|
+
isMounted = false;
|
|
101
|
+
instanceRef.current?.destroy();
|
|
102
|
+
instanceRef.current = null;
|
|
103
|
+
};
|
|
104
|
+
}, [componentName]);
|
|
105
|
+
|
|
106
|
+
return (
|
|
107
|
+
<>
|
|
108
|
+
{isLoading && <div>Loading…</div>}
|
|
109
|
+
<div ref={containerRef} />
|
|
110
|
+
</>
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
30
115
|
### 🔐 Authentication
|
|
31
116
|
|
|
32
117
|
By default, the SDK **handles authentication automatically**. No authentication configuration is required from the consuming application.
|
package/dist/cdn-index.js
CHANGED
|
@@ -1,8 +1,891 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
(() => {
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __defProps = Object.defineProperties;
|
|
5
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
9
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
10
|
+
var __spreadValues = (a, b) => {
|
|
11
|
+
for (var prop in b || (b = {}))
|
|
12
|
+
if (__hasOwnProp.call(b, prop))
|
|
13
|
+
__defNormalProp(a, prop, b[prop]);
|
|
14
|
+
if (__getOwnPropSymbols)
|
|
15
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
16
|
+
if (__propIsEnum.call(b, prop))
|
|
17
|
+
__defNormalProp(a, prop, b[prop]);
|
|
18
|
+
}
|
|
19
|
+
return a;
|
|
20
|
+
};
|
|
21
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
22
|
+
var __async = (__this, __arguments, generator) => {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
var fulfilled = (value) => {
|
|
25
|
+
try {
|
|
26
|
+
step(generator.next(value));
|
|
27
|
+
} catch (e) {
|
|
28
|
+
reject(e);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var rejected = (value) => {
|
|
32
|
+
try {
|
|
33
|
+
step(generator.throw(value));
|
|
34
|
+
} catch (e) {
|
|
35
|
+
reject(e);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
39
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/common/enums/index.ts
|
|
44
|
+
var ModulesNameEnum = /* @__PURE__ */ ((ModulesNameEnum3) => {
|
|
45
|
+
ModulesNameEnum3["ONBOARDING_PARTNER"] = "ONBOARDING_PARTNER";
|
|
46
|
+
ModulesNameEnum3["ONBOARDING_MERCHANT"] = "ONBOARDING_MERCHANT";
|
|
47
|
+
ModulesNameEnum3["DOC_UTILITY"] = "DOC_UTILITY";
|
|
48
|
+
return ModulesNameEnum3;
|
|
49
|
+
})(ModulesNameEnum || {});
|
|
50
|
+
|
|
51
|
+
// src/utils/common.utils.ts
|
|
52
|
+
var buildQuery = (queryObj) => {
|
|
53
|
+
if (queryObj && typeof queryObj === "object") {
|
|
54
|
+
const keys = Object.keys(queryObj);
|
|
55
|
+
const totalLength = keys.length;
|
|
56
|
+
let query = keys.length ? "?" : "";
|
|
57
|
+
keys.forEach((key, ind) => {
|
|
58
|
+
const nextInd = ind + 1;
|
|
59
|
+
const presentObjVal = queryObj[key];
|
|
60
|
+
const nextObjVal = queryObj[keys[nextInd]];
|
|
61
|
+
if (nextInd < totalLength && isDataValid(presentObjVal)) {
|
|
62
|
+
const q = query + key + "=" + presentObjVal;
|
|
63
|
+
if (isDataValid(nextObjVal)) query = q + "&";
|
|
64
|
+
else query = q;
|
|
65
|
+
} else if (isDataValid(presentObjVal)) {
|
|
66
|
+
query = query + key + "=" + presentObjVal;
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
return query;
|
|
70
|
+
}
|
|
71
|
+
return "";
|
|
72
|
+
};
|
|
73
|
+
var isDataValid = (data) => {
|
|
74
|
+
if (data === void 0 || data === null || data === "") return false;
|
|
75
|
+
if (typeof data === "number" && Number.isNaN(data)) return false;
|
|
76
|
+
if (typeof data === "string" && data.trim() === "") return false;
|
|
77
|
+
if (typeof data === "boolean") return true;
|
|
78
|
+
return true;
|
|
79
|
+
};
|
|
80
|
+
var buildValidObject = (obj) => {
|
|
81
|
+
const isValid = (data) => {
|
|
82
|
+
return data !== void 0 && data !== null && !(Array.isArray(data) && data.length === 0) && !(typeof data === "object" && Object.keys(data).length === 0) && !(typeof data === "string" && data.trim() === "");
|
|
83
|
+
};
|
|
84
|
+
if (!obj || typeof obj !== "object") {
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
const newObject = {};
|
|
88
|
+
for (const key in obj) {
|
|
89
|
+
if (obj.hasOwnProperty(key)) {
|
|
90
|
+
const value = obj[key];
|
|
91
|
+
if (isValid(value)) {
|
|
92
|
+
if (Array.isArray(value)) {
|
|
93
|
+
const validElements = value.filter((elem) => isValid(elem)).map(buildValidObject).filter((elem) => isValid(elem));
|
|
94
|
+
if (validElements.length) {
|
|
95
|
+
newObject[key] = validElements;
|
|
96
|
+
}
|
|
97
|
+
} else if (typeof value === "object") {
|
|
98
|
+
const nestedValid = buildValidObject(value);
|
|
99
|
+
if (isValid(nestedValid)) {
|
|
100
|
+
newObject[key] = nestedValid;
|
|
101
|
+
}
|
|
102
|
+
} else {
|
|
103
|
+
newObject[key] = value;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return Object.keys(newObject).length ? newObject : void 0;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// src/services/default-auth-provider.ts
|
|
112
|
+
var SESSION_FAILED_RESPONSE = {
|
|
113
|
+
isSuccess: false,
|
|
114
|
+
accessToken: "",
|
|
115
|
+
accessTokenExpiry: "",
|
|
116
|
+
refreshToken: "",
|
|
117
|
+
refreshTokenExpiry: ""
|
|
118
|
+
};
|
|
119
|
+
var REFRESH_FAILED_RESPONSE = {
|
|
120
|
+
isSuccess: false,
|
|
121
|
+
accessToken: "",
|
|
122
|
+
accessTokenExpiry: ""
|
|
123
|
+
};
|
|
124
|
+
var DefaultAuthProvider = class {
|
|
125
|
+
constructor(authConfig, componentName) {
|
|
126
|
+
this.currentAccessToken = "";
|
|
127
|
+
this.fetchClientSession = () => __async(this, null, function* () {
|
|
128
|
+
const url = this.getAuthUrl("/auth/micro-frontend/tokens");
|
|
129
|
+
const payload = buildValidObject({
|
|
130
|
+
modules: [{ name: this.getAuthModuleName() }],
|
|
131
|
+
referenceId: this.authConfig.referenceId
|
|
132
|
+
});
|
|
133
|
+
try {
|
|
134
|
+
const response = yield fetch(url, {
|
|
135
|
+
method: "POST",
|
|
136
|
+
headers: this.getHeaders(),
|
|
137
|
+
body: JSON.stringify(payload)
|
|
138
|
+
});
|
|
139
|
+
const session = yield this.parseJsonResponse(
|
|
140
|
+
response,
|
|
141
|
+
url,
|
|
142
|
+
"Frontend AccessToken"
|
|
143
|
+
);
|
|
144
|
+
this.currentAccessToken = session.accessToken || "";
|
|
145
|
+
return __spreadProps(__spreadValues(__spreadValues({}, SESSION_FAILED_RESPONSE), session), {
|
|
146
|
+
isSuccess: true
|
|
147
|
+
});
|
|
148
|
+
} catch (error) {
|
|
149
|
+
throw this.createAuthError("Frontend AccessToken", url, error);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
this.refreshClientSession = (payload) => __async(this, null, function* () {
|
|
153
|
+
const url = this.getAuthUrl("/auth/micro-frontend/tokens/refresh");
|
|
154
|
+
try {
|
|
155
|
+
const response = yield fetch(url, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: this.getHeaders(),
|
|
158
|
+
body: JSON.stringify(buildValidObject(payload))
|
|
159
|
+
});
|
|
160
|
+
const session = yield this.parseJsonResponse(
|
|
161
|
+
response,
|
|
162
|
+
url,
|
|
163
|
+
"Frontend AccessToken Refresh"
|
|
164
|
+
);
|
|
165
|
+
this.currentAccessToken = session.accessToken || this.currentAccessToken;
|
|
166
|
+
return __spreadProps(__spreadValues(__spreadValues({}, REFRESH_FAILED_RESPONSE), session), {
|
|
167
|
+
isSuccess: true
|
|
168
|
+
});
|
|
169
|
+
} catch (error) {
|
|
170
|
+
throw this.createAuthError("Frontend AccessToken Refresh", url, error);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
this.destroySession = () => __async(this, null, function* () {
|
|
174
|
+
if (!this.currentAccessToken) {
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
const url = this.getAuthUrl("/auth/access-token/revoke");
|
|
178
|
+
try {
|
|
179
|
+
const response = yield fetch(url, {
|
|
180
|
+
method: "POST",
|
|
181
|
+
headers: this.getHeaders(),
|
|
182
|
+
body: JSON.stringify({ accessToken: this.currentAccessToken })
|
|
183
|
+
});
|
|
184
|
+
if (!response.ok) {
|
|
185
|
+
const responseText = yield response.text();
|
|
186
|
+
throw new Error(
|
|
187
|
+
`Session revoke failed(Web SDK): ${response.status} ${response.statusText}. URL: ${url}. Response: ${responseText.slice(0, 200)}`
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
this.currentAccessToken = "";
|
|
191
|
+
return true;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
console.error(this.createAuthError("Session revoke", url, error).message);
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
this.getAuthModuleName = () => {
|
|
198
|
+
switch (this.moduleName) {
|
|
199
|
+
case "ONBOARDING_PARTNER" /* ONBOARDING_PARTNER */:
|
|
200
|
+
case "ONBOARDING_MERCHANT" /* ONBOARDING_MERCHANT */:
|
|
201
|
+
return "ONBOARDING";
|
|
202
|
+
default:
|
|
203
|
+
return this.moduleName || "";
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
this.getHeaders = () => {
|
|
207
|
+
return {
|
|
208
|
+
Authorization: this.authConfig.authToken || "",
|
|
209
|
+
"Content-Type": "application/json"
|
|
210
|
+
};
|
|
211
|
+
};
|
|
212
|
+
this.getAuthUrl = (path) => {
|
|
213
|
+
var _a;
|
|
214
|
+
const authApiUrl = (_a = this.authConfig.authApiUrl) == null ? void 0 : _a.trim();
|
|
215
|
+
if (!authApiUrl) {
|
|
216
|
+
throw new Error("authConfig.authApiUrl is required(Web SDK)");
|
|
217
|
+
}
|
|
218
|
+
return `${authApiUrl.replace(/\/$/, "")}${path}`;
|
|
219
|
+
};
|
|
220
|
+
this.parseJsonResponse = (response, url, label) => __async(null, null, function* () {
|
|
221
|
+
const responseText = yield response.text();
|
|
222
|
+
if (!response.ok) {
|
|
223
|
+
throw new Error(
|
|
224
|
+
`${label} Error Response(Web SDK): ${response.status} ${response.statusText}. URL: ${url}. Response: ${responseText.slice(0, 200)}`
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
const contentType = response.headers.get("content-type") || "";
|
|
228
|
+
if (!contentType.includes("application/json")) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`${label} expected JSON response(Web SDK). URL: ${url}. Content-Type: ${contentType || "unknown"}. Response: ${responseText.slice(0, 200)}`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
return JSON.parse(responseText);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
throw new Error(
|
|
237
|
+
`${label} JSON parse failed(Web SDK). URL: ${url}. Response: ${responseText.slice(0, 200)}`
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
this.createAuthError = (label, url, error) => {
|
|
242
|
+
if (error instanceof Error && error.message.includes("(Web SDK)")) {
|
|
243
|
+
return error;
|
|
244
|
+
}
|
|
245
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
246
|
+
const browserHint = message.includes("Failed to fetch") ? " This usually means the browser blocked the request because of CORS, the URL is unreachable, or the request was blocked before a response was returned." : "";
|
|
247
|
+
return new Error(`${label} Request Failed(Web SDK). URL: ${url}.${browserHint}`);
|
|
248
|
+
};
|
|
249
|
+
this.authConfig = authConfig;
|
|
250
|
+
this.moduleName = componentName;
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
// src/utils/object.utils.ts
|
|
255
|
+
function deepMerge(obj1, obj2) {
|
|
256
|
+
const result = __spreadValues({}, obj1);
|
|
257
|
+
for (const key of Object.keys(obj2)) {
|
|
258
|
+
if (obj1[key] && typeof obj1[key] === "object" && typeof obj2[key] === "object" && !Array.isArray(obj1[key]) && !Array.isArray(obj2[key])) {
|
|
259
|
+
result[key] = deepMerge(obj1[key], obj2[key]);
|
|
260
|
+
} else {
|
|
261
|
+
result[key] = obj2[key];
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return result;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/config/default-config.ts
|
|
268
|
+
var DEFAULT_CONFIG = {
|
|
269
|
+
iframeId: "nc-web-sdk-iframe",
|
|
270
|
+
containerId: "websdk-container",
|
|
271
|
+
iframeStyle: {
|
|
272
|
+
width: "100%",
|
|
273
|
+
height: "100vh",
|
|
274
|
+
border: "none",
|
|
275
|
+
display: "block"
|
|
276
|
+
},
|
|
277
|
+
sessionValidation: (token, tokenExpiry) => {
|
|
278
|
+
if (!token || !tokenExpiry) {
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
const expiryDate = new Date(tokenExpiry);
|
|
282
|
+
const currentDate = /* @__PURE__ */ new Date();
|
|
283
|
+
return expiryDate > currentDate;
|
|
284
|
+
},
|
|
285
|
+
sessionCheckInterval: 10 * 60 * 1e3,
|
|
286
|
+
// 5 minutes
|
|
287
|
+
environment: "uat" /* UAT */
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
// src/utils/date.utils.ts
|
|
291
|
+
var isDateExpired = (tokenExpiry) => {
|
|
292
|
+
if (!tokenExpiry) return true;
|
|
293
|
+
let expiryDate;
|
|
294
|
+
if (tokenExpiry instanceof Date) {
|
|
295
|
+
expiryDate = tokenExpiry;
|
|
296
|
+
} else if (typeof tokenExpiry === "number") {
|
|
297
|
+
expiryDate = new Date(tokenExpiry);
|
|
298
|
+
} else if (typeof tokenExpiry === "string") {
|
|
299
|
+
const normalized = tokenExpiry.trim().replace(" ", "T");
|
|
300
|
+
expiryDate = new Date(normalized);
|
|
301
|
+
} else {
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
if (isNaN(expiryDate.getTime())) return true;
|
|
305
|
+
return Date.now() > expiryDate.getTime();
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// src/utils/iframe-url.utils.ts
|
|
309
|
+
var ENVIRONMENT_BASE_URLS = {
|
|
310
|
+
local: "http://localhost:4000",
|
|
311
|
+
dev: "https://dev3-non-pci.eastus.cloudapp.azure.com",
|
|
312
|
+
preprod: "https://ignite-preprod.nuvei.com",
|
|
313
|
+
prod: "https://ignite.nuvei.com"
|
|
314
|
+
};
|
|
315
|
+
var DOCUMENT_UTILITY_BASE_URLS = {
|
|
316
|
+
local: "http://localhost:5000",
|
|
317
|
+
dev: "https://dev3-non-pci.eastus.cloudapp.azure.com",
|
|
318
|
+
preprod: "https://ignite-preprod.nuvei.com",
|
|
319
|
+
prod: "https://ignite.nuvei.com"
|
|
320
|
+
};
|
|
321
|
+
var MODULE_PATHS = {
|
|
322
|
+
["ONBOARDING_PARTNER" /* ONBOARDING_PARTNER */]: "/_onboarding/partner/application",
|
|
323
|
+
["ONBOARDING_MERCHANT" /* ONBOARDING_MERCHANT */]: "/_onboarding/merchant/application",
|
|
324
|
+
["DOC_UTILITY" /* DOC_UTILITY */]: "/_document-upload"
|
|
325
|
+
};
|
|
326
|
+
var DOCUMENT_REQUEST_ID_PARAM = "documentRequestId";
|
|
327
|
+
var getEnvironmentBaseUrl = (environment = "prod") => {
|
|
328
|
+
var _a;
|
|
329
|
+
return (_a = ENVIRONMENT_BASE_URLS[environment]) != null ? _a : ENVIRONMENT_BASE_URLS.prod;
|
|
330
|
+
};
|
|
331
|
+
var getDocumentUtilityBaseUrl = (environment = "prod") => {
|
|
332
|
+
var _a;
|
|
333
|
+
return (_a = DOCUMENT_UTILITY_BASE_URLS[environment]) != null ? _a : DOCUMENT_UTILITY_BASE_URLS.prod;
|
|
334
|
+
};
|
|
335
|
+
var getModulePath = (componentName) => {
|
|
336
|
+
var _a;
|
|
337
|
+
return (_a = MODULE_PATHS[componentName]) != null ? _a : "";
|
|
338
|
+
};
|
|
339
|
+
var getDocumentRequestIdFromUrl = () => {
|
|
340
|
+
if (typeof window === "undefined") {
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
const params = new URLSearchParams(window.location.search);
|
|
344
|
+
return params.get(DOCUMENT_REQUEST_ID_PARAM);
|
|
345
|
+
};
|
|
346
|
+
var getBaseUrl = (componentName, environment, config) => {
|
|
347
|
+
if (config.iframeBaseUrl) {
|
|
348
|
+
return config.iframeBaseUrl;
|
|
349
|
+
}
|
|
350
|
+
if (componentName === "DOC_UTILITY" /* DOC_UTILITY */) {
|
|
351
|
+
return getDocumentUtilityBaseUrl(environment);
|
|
352
|
+
}
|
|
353
|
+
return getEnvironmentBaseUrl(environment);
|
|
354
|
+
};
|
|
355
|
+
var resolveIframeUrl = (componentName, config) => {
|
|
356
|
+
var _a, _b;
|
|
357
|
+
const environment = (_a = config.environment) != null ? _a : "prod";
|
|
358
|
+
const baseUrl = getBaseUrl(
|
|
359
|
+
componentName,
|
|
360
|
+
environment,
|
|
361
|
+
config
|
|
362
|
+
);
|
|
363
|
+
const path = getModulePath(componentName);
|
|
364
|
+
let queryParams = {};
|
|
365
|
+
if (componentName === "DOC_UTILITY" /* DOC_UTILITY */) {
|
|
366
|
+
const documentRequestId = (_b = config.documentRequestId) != null ? _b : getDocumentRequestIdFromUrl();
|
|
367
|
+
queryParams = {
|
|
368
|
+
[DOCUMENT_REQUEST_ID_PARAM]: documentRequestId
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
const query = buildQuery(queryParams);
|
|
372
|
+
return `${baseUrl}${path}${query}`;
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
// src/core/index.ts
|
|
376
|
+
var _NuveiSDK = class _NuveiSDK {
|
|
377
|
+
/**
|
|
378
|
+
* Initializes the Nuvei SDK instance
|
|
379
|
+
* @param {INuveiInitParams} params - Initialization parameters
|
|
380
|
+
* @param {() => Promise<IClientSession>} params.fetchClientSession - Function to fetch the client session
|
|
381
|
+
* @param {() => Promise<IClientRefreshSession>} params.refreshClientSession - Function to refresh the client session
|
|
382
|
+
* @param {() => Promise<boolean>} params.destroySession - Function to destroy the client session
|
|
383
|
+
* @param {INuveiSdkConfig} [params.config] - Optional configuration overrides
|
|
384
|
+
*/
|
|
385
|
+
constructor(params) {
|
|
386
|
+
this.sdkConfig = __spreadValues({}, DEFAULT_CONFIG);
|
|
387
|
+
// iframe
|
|
388
|
+
this.currentIframe = null;
|
|
389
|
+
this.iframeUrl = "";
|
|
390
|
+
this.isIframeReady = false;
|
|
391
|
+
this.messageQueue = [];
|
|
392
|
+
// session
|
|
393
|
+
this.cachedSession = null;
|
|
394
|
+
this.sessionCheckInterval = null;
|
|
395
|
+
this.expiryTimeout = null;
|
|
396
|
+
this.retryAttempts = 0;
|
|
397
|
+
this.MAX_RETRIES = 3;
|
|
398
|
+
this.REFRESH_BUFFER_MS = 60 * 1e3;
|
|
399
|
+
this.isListeningToIframeEvents = false;
|
|
400
|
+
this.isDestroyed = false;
|
|
401
|
+
/**
|
|
402
|
+
* Initializes the configured component.
|
|
403
|
+
*
|
|
404
|
+
* This is a convenience wrapper for integrations that only mount one
|
|
405
|
+
* microfrontend and do not need to call loadComponent manually.
|
|
406
|
+
*/
|
|
407
|
+
this.initialize = () => __async(this, null, function* () {
|
|
408
|
+
var _a, _b;
|
|
409
|
+
this.isDestroyed = false;
|
|
410
|
+
if (!this.componentName) {
|
|
411
|
+
throw new Error("componentName is required to initialize the SDK(Web SDK)");
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
const iframe = yield this.loadComponent(this.componentName);
|
|
415
|
+
if (this.isDestroyed) return iframe;
|
|
416
|
+
yield (_a = this.onReady) == null ? void 0 : _a.call(this, this);
|
|
417
|
+
return iframe;
|
|
418
|
+
} catch (error) {
|
|
419
|
+
(_b = this.onError) == null ? void 0 : _b.call(this, error);
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
/**
|
|
424
|
+
* Establishes a connection to a specified component by creating and loading an iframe.
|
|
425
|
+
*
|
|
426
|
+
* This asynchronous function initializes the WebSDK with a valid session, validates
|
|
427
|
+
* the session token, determines the appropriate iframe URL based on the given
|
|
428
|
+
* component name, and creates the iframe with the specified source URL.
|
|
429
|
+
*
|
|
430
|
+
* @param {string} componentName - The name of the component to connect to.
|
|
431
|
+
* Valid values are defined in the ComponentNameEnum.
|
|
432
|
+
*
|
|
433
|
+
* @returns {Promise<HTMLIFrameElement | void>} A promise that resolves to the created
|
|
434
|
+
* iframe element, or void if an error occurs.
|
|
435
|
+
*
|
|
436
|
+
* @throws {Error} Throws an error if the session token is invalid or if the
|
|
437
|
+
* specified component name is unknown.
|
|
438
|
+
*/
|
|
439
|
+
this.loadComponent = (componentName) => __async(this, null, function* () {
|
|
440
|
+
console.log("Component Requested to Load(Web SDK): ", componentName);
|
|
441
|
+
try {
|
|
442
|
+
const accessTokenData = yield this.getClientSession();
|
|
443
|
+
if (!this.sdkConfig.sessionValidation(
|
|
444
|
+
accessTokenData == null ? void 0 : accessTokenData.accessToken,
|
|
445
|
+
accessTokenData == null ? void 0 : accessTokenData.accessTokenExpiry
|
|
446
|
+
)) {
|
|
447
|
+
throw new Error("Token Validation FailedLoad(Web SDK)");
|
|
448
|
+
}
|
|
449
|
+
this.iframeUrl = resolveIframeUrl(componentName, this.sdkConfig);
|
|
450
|
+
console.log("\nIframe URL(Web SDK): ", this.iframeUrl, "\n");
|
|
451
|
+
const iframe = yield this.createIframeWithSource(this.iframeUrl, componentName);
|
|
452
|
+
this.currentIframe = iframe;
|
|
453
|
+
this.updateIframeToken(accessTokenData.accessToken);
|
|
454
|
+
return iframe;
|
|
455
|
+
} catch (error) {
|
|
456
|
+
this.destroyIframe();
|
|
457
|
+
throw error;
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
/**
|
|
461
|
+
* Destroys the current iframe if it exists, removing it from the DOM.
|
|
462
|
+
* Also clears the session check interval associated with the iframe.
|
|
463
|
+
*/
|
|
464
|
+
this.destroyIframe = () => {
|
|
465
|
+
if (this.currentIframe) {
|
|
466
|
+
this.currentIframe.remove();
|
|
467
|
+
this.currentIframe = null;
|
|
468
|
+
}
|
|
469
|
+
this.stopSessionExpiryCheck();
|
|
470
|
+
};
|
|
471
|
+
/**
|
|
472
|
+
* Fully destroys the SDK instance's mounted iframe and browser listeners.
|
|
473
|
+
*/
|
|
474
|
+
this.destroy = () => {
|
|
475
|
+
this.isDestroyed = true;
|
|
476
|
+
this.destroyIframe();
|
|
477
|
+
if (this.mountKey) {
|
|
478
|
+
_NuveiSDK.mountPromises.delete(this.mountKey);
|
|
479
|
+
this.mountKey = void 0;
|
|
480
|
+
}
|
|
481
|
+
this.messageQueue = [];
|
|
482
|
+
this.isIframeReady = false;
|
|
483
|
+
window.removeEventListener("message", this.handleIframeMessage);
|
|
484
|
+
this.isListeningToIframeEvents = false;
|
|
485
|
+
};
|
|
486
|
+
/**
|
|
487
|
+
* Logout of the WebSDK.
|
|
488
|
+
*
|
|
489
|
+
* Logs out the current session, revoking the access token. If the logout is
|
|
490
|
+
* successful, the SDK will destroy the iframe.
|
|
491
|
+
*
|
|
492
|
+
* @throws {Error} Throws an error if something goes wrong during logout.
|
|
493
|
+
*/
|
|
494
|
+
this.logout = () => __async(this, null, function* () {
|
|
495
|
+
const logoutRes = yield this.authProvider.destroySession();
|
|
496
|
+
if (logoutRes) {
|
|
497
|
+
this.stopSessionExpiryCheck();
|
|
498
|
+
this.destroyIframe();
|
|
499
|
+
} else {
|
|
500
|
+
console.error("Logout failed(Web SDK)");
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
/**
|
|
504
|
+
* Sends a message to the iframe to navigate to the given path.
|
|
505
|
+
* @param {string} path - The path to navigate to.
|
|
506
|
+
*/
|
|
507
|
+
this.updateIframeNavigation = (path) => {
|
|
508
|
+
this.enqueueMessage("NAVIGATE", path);
|
|
509
|
+
};
|
|
510
|
+
/**
|
|
511
|
+
* Sends custom data to the iframe.
|
|
512
|
+
* @param {any} data - The custom data to be sent to the iframe.
|
|
513
|
+
* @example sendCustomDataToIframe({ name: 'John Doe', age: 30 });
|
|
514
|
+
*/
|
|
515
|
+
this.sendCustomDataToIframe = (data) => {
|
|
516
|
+
this.enqueueMessage("CUSTOM_DATA", data);
|
|
517
|
+
};
|
|
518
|
+
// =============================|| PRIVATE METHODS ||============================== //
|
|
519
|
+
/**
|
|
520
|
+
* Retrieves and validates the current client session.
|
|
521
|
+
*
|
|
522
|
+
* This asynchronous function fetches a new client session using
|
|
523
|
+
* `fetchClientSession`, validates the session's access token using
|
|
524
|
+
* `sessionValidation`, and updates the current session ID and
|
|
525
|
+
* token expiry time. If the session token is invalid, an error is thrown.
|
|
526
|
+
*
|
|
527
|
+
* @returns {Promise<string>} The current session ID if validation is successful.
|
|
528
|
+
* @throws {Error} If session validation fails or any error occurs during
|
|
529
|
+
* the fetching or validation process.
|
|
530
|
+
*/
|
|
531
|
+
this.getClientSession = () => __async(this, null, function* () {
|
|
532
|
+
var _a, _b, _c, _d;
|
|
533
|
+
try {
|
|
534
|
+
if (this.cachedSession && ((_c = this.sdkConfig) == null ? void 0 : _c.sessionValidation(
|
|
535
|
+
(_a = this.cachedSession) == null ? void 0 : _a.accessToken,
|
|
536
|
+
(_b = this.cachedSession) == null ? void 0 : _b.accessTokenExpiry
|
|
537
|
+
))) {
|
|
538
|
+
return this.cachedSession;
|
|
539
|
+
} else {
|
|
540
|
+
const session = yield this.authProvider.fetchClientSession();
|
|
541
|
+
if (!session.isSuccess) {
|
|
542
|
+
throw new Error("Client Session Fetch Failed(Web SDK)");
|
|
543
|
+
}
|
|
544
|
+
if (!((_d = this.sdkConfig) == null ? void 0 : _d.sessionValidation(session.accessToken, session.accessTokenExpiry))) {
|
|
545
|
+
throw new Error("Client Session Validation Failed(Web SDK)");
|
|
546
|
+
}
|
|
547
|
+
this.cachedSession = session;
|
|
548
|
+
this.retryAttempts = 0;
|
|
549
|
+
return session;
|
|
550
|
+
}
|
|
551
|
+
} catch (error) {
|
|
552
|
+
throw error;
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
/**
|
|
556
|
+
* Refreshes the current client session.
|
|
557
|
+
*
|
|
558
|
+
* @returns {Promise<IClientRefreshSession>} The current session ID if validation is successful.
|
|
559
|
+
* @throws {Error} If session validation fails or any error occurs during
|
|
560
|
+
* the fetching or validation process.
|
|
561
|
+
*/
|
|
562
|
+
this.refreshedClientSession = () => __async(this, null, function* () {
|
|
563
|
+
var _a, _b;
|
|
564
|
+
if (!((_a = this.cachedSession) == null ? void 0 : _a.refreshToken) || !this.cachedSession.accessToken) {
|
|
565
|
+
console.error(
|
|
566
|
+
"Invalid or missing refreshToken or accessToken in cashed session. Destroying iframe(Web SDK)."
|
|
567
|
+
);
|
|
568
|
+
this.destroyIframe();
|
|
569
|
+
throw new Error("No session found(Web SDK)");
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
const response = yield this.authProvider.refreshClientSession({
|
|
573
|
+
accessToken: this.cachedSession.accessToken,
|
|
574
|
+
refreshToken: this.cachedSession.refreshToken
|
|
575
|
+
});
|
|
576
|
+
if (!response.isSuccess) {
|
|
577
|
+
console.log("Invalid refresh session token(Called From Web SDK)");
|
|
578
|
+
throw new Error("Refresh Client Session Failed");
|
|
579
|
+
}
|
|
580
|
+
if (!((_b = this.sdkConfig) == null ? void 0 : _b.sessionValidation(response.accessToken, response.accessTokenExpiry))) {
|
|
581
|
+
console.log("Invalid refresh session token(Called From Web SDK)");
|
|
582
|
+
throw new Error("Refresh Client Session Validation Failed");
|
|
583
|
+
}
|
|
584
|
+
const newSession = __spreadValues({}, this.cachedSession);
|
|
585
|
+
newSession.accessToken = response.accessToken;
|
|
586
|
+
newSession.accessTokenExpiry = response.accessTokenExpiry;
|
|
587
|
+
this.cachedSession = newSession;
|
|
588
|
+
this.retryAttempts = 0;
|
|
589
|
+
return response;
|
|
590
|
+
} catch (error) {
|
|
591
|
+
console.error("Session Refresh Failed(Web SDK):", error);
|
|
592
|
+
throw error;
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
/**
|
|
596
|
+
* Creates an iframe with the given URL and appends it to the container with the given ID.
|
|
597
|
+
* If an iframe with the same ID already exists, it is reused.
|
|
598
|
+
*
|
|
599
|
+
* @param {string} url The URL to load in the iframe
|
|
600
|
+
* @returns {Promise<HTMLIFrameElement>} A promise that resolves to the created iframe element
|
|
601
|
+
* @throws {Error} If the container element is not found or the iframe fails to load
|
|
602
|
+
*/
|
|
603
|
+
this.createIframeWithSource = (url, componentName) => {
|
|
604
|
+
return new Promise((resolve, reject) => {
|
|
605
|
+
const container = this.getContainerElement();
|
|
606
|
+
if (!container) {
|
|
607
|
+
return reject(new Error("SDK container not found(Web SDK)"));
|
|
608
|
+
}
|
|
609
|
+
const iframeId = this.getIframeId(componentName);
|
|
610
|
+
let iframe = document.getElementById(iframeId);
|
|
611
|
+
if (iframe) {
|
|
612
|
+
console.log(`Iframe with Id: ${iframeId} already exists, reusing it(Web SDK)`);
|
|
613
|
+
resolve(iframe);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
iframe = document.createElement("iframe");
|
|
617
|
+
iframe.src = url;
|
|
618
|
+
iframe.id = iframeId;
|
|
619
|
+
const iframeStyle = __spreadValues({}, this.sdkConfig.iframeStyle);
|
|
620
|
+
if (iframeStyle) {
|
|
621
|
+
Object.assign(iframe.style, iframeStyle);
|
|
622
|
+
}
|
|
623
|
+
iframe.setAttribute("allow", "clipboard-write *");
|
|
624
|
+
iframe.onload = () => {
|
|
625
|
+
console.log("Iframe loaded successfully(Web SDK)");
|
|
626
|
+
this.startSessionExpiryCheck();
|
|
627
|
+
resolve(iframe);
|
|
628
|
+
};
|
|
629
|
+
iframe.onerror = () => {
|
|
630
|
+
reject(new Error("Iframe failed to load(Web SDK)"));
|
|
631
|
+
};
|
|
632
|
+
container.appendChild(iframe);
|
|
633
|
+
});
|
|
634
|
+
};
|
|
635
|
+
this.getContainerElement = () => {
|
|
636
|
+
if (this.container instanceof HTMLElement) {
|
|
637
|
+
return this.container;
|
|
638
|
+
}
|
|
639
|
+
if (typeof this.container === "string") {
|
|
640
|
+
return document.querySelector(this.container) || document.getElementById(this.container);
|
|
641
|
+
}
|
|
642
|
+
return document.getElementById(this.sdkConfig.containerId);
|
|
643
|
+
};
|
|
644
|
+
this.getIframeId = (componentName) => {
|
|
645
|
+
const componentKey = String(componentName).toLowerCase().replace(/_/g, "-");
|
|
646
|
+
return `${this.sdkConfig.iframeId}-${componentKey}`;
|
|
647
|
+
};
|
|
648
|
+
/**
|
|
649
|
+
* Schedules a session expiry check in the future based on the provided
|
|
650
|
+
* {@link tokenExpiryTime}. If the token has already expired, the check
|
|
651
|
+
* is retried up to {@link MAX_RETRIES} times. If all retries fail, the
|
|
652
|
+
* session check is stopped and the iframe is destroyed.
|
|
653
|
+
*
|
|
654
|
+
* @throws {Error} If the session check fails with an error, the iframe is
|
|
655
|
+
* destroyed as a fallback.
|
|
656
|
+
*/
|
|
657
|
+
this.startSessionExpiryCheck = () => __async(this, null, function* () {
|
|
658
|
+
var _a, _b;
|
|
659
|
+
const isRefreshExpired = isDateExpired((_a = this.cachedSession) == null ? void 0 : _a.refreshTokenExpiry);
|
|
660
|
+
if (isRefreshExpired) {
|
|
661
|
+
console.error("Refresh token is expired. Stopping session expiry check(Web SDK).");
|
|
662
|
+
this.destroyIframe();
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
const now = /* @__PURE__ */ new Date();
|
|
666
|
+
const expiryRaw = (_b = this.cachedSession) == null ? void 0 : _b.accessTokenExpiry;
|
|
667
|
+
const expiryTime = expiryRaw ? new Date(expiryRaw) : null;
|
|
668
|
+
if (!expiryTime || isNaN(expiryTime.getTime())) {
|
|
669
|
+
console.error(
|
|
670
|
+
"Invalid or missing accessTokenExpiry in session. Stopping session expiry check(Web SDK)."
|
|
671
|
+
);
|
|
672
|
+
this.destroyIframe();
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const delay = expiryTime.getTime() - now.getTime() - this.REFRESH_BUFFER_MS;
|
|
676
|
+
const performRefresh = () => __async(this, null, function* () {
|
|
677
|
+
try {
|
|
678
|
+
if (this.retryAttempts >= this.MAX_RETRIES) {
|
|
679
|
+
console.warn(
|
|
680
|
+
`Max retry attempts (${this.MAX_RETRIES}) reached. Stopping session check(Web SDK).`
|
|
681
|
+
);
|
|
682
|
+
this.stopSessionExpiryCheck();
|
|
683
|
+
this.destroyIframe();
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
const refreshSession = yield this.refreshedClientSession();
|
|
687
|
+
this.updateIframeToken(refreshSession.accessToken);
|
|
688
|
+
this.retryAttempts = 0;
|
|
689
|
+
this.startSessionExpiryCheck();
|
|
690
|
+
} catch (err) {
|
|
691
|
+
console.error("Failed to perform session refresh(Web SDK):", err);
|
|
692
|
+
this.retryAttempts++;
|
|
693
|
+
this.stopSessionExpiryCheck();
|
|
694
|
+
this.expiryTimeout = setTimeout(performRefresh, 5e3);
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
this.stopSessionExpiryCheck();
|
|
698
|
+
if (delay <= 0) {
|
|
699
|
+
performRefresh();
|
|
700
|
+
} else {
|
|
701
|
+
this.expiryTimeout = setTimeout(performRefresh, delay);
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
/**
|
|
705
|
+
* Stops the session expiry check scheduled by {@link startSessionExpiryCheck}.
|
|
706
|
+
* This is useful when the iframe is destroyed or the session is manually
|
|
707
|
+
* invalidated.
|
|
708
|
+
*/
|
|
709
|
+
this.stopSessionExpiryCheck = () => {
|
|
710
|
+
if (this.expiryTimeout) {
|
|
711
|
+
clearTimeout(this.expiryTimeout);
|
|
712
|
+
this.expiryTimeout = null;
|
|
713
|
+
}
|
|
714
|
+
if (this.sessionCheckInterval) {
|
|
715
|
+
clearInterval(this.sessionCheckInterval);
|
|
716
|
+
this.sessionCheckInterval = null;
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
/**
|
|
720
|
+
* Sends a message to the microfrontend running in the iframe to update the session token.
|
|
721
|
+
* @param {string} data - The new session token to be used by the microfrontend.
|
|
722
|
+
*/
|
|
723
|
+
this.updateIframeToken = (data) => {
|
|
724
|
+
this.enqueueMessage("UPDATE_TOKEN", data);
|
|
725
|
+
};
|
|
726
|
+
/**
|
|
727
|
+
* Enqueues a message to be sent to the microfrontend running in the iframe.
|
|
728
|
+
* @param {PostMessageActionType} action - The action to be performed by the microfrontend.
|
|
729
|
+
* @param {any} data - The data to be sent to the microfrontend.
|
|
730
|
+
* @example enqueueMessage('UPDATE_TOKEN', 'my-access-token');
|
|
731
|
+
*/
|
|
732
|
+
this.enqueueMessage = (action, data) => {
|
|
733
|
+
const payload = {
|
|
734
|
+
action,
|
|
735
|
+
source: "NUVEI_WEB_SDK",
|
|
736
|
+
data
|
|
737
|
+
};
|
|
738
|
+
if (!this.isIframeReady) {
|
|
739
|
+
console.log("Iframe not ready, queueing message(Web SDK):", payload);
|
|
740
|
+
this.messageQueue.push(payload);
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
this.postMessageToIframe(payload);
|
|
744
|
+
};
|
|
745
|
+
/**
|
|
746
|
+
* Flushes the message queue to send all queued messages to the microfrontend.
|
|
747
|
+
* This is called when the iframe is ready to receive messages.
|
|
748
|
+
* @example flushMessageQueue();
|
|
749
|
+
*/
|
|
750
|
+
this.flushMessageQueue = () => {
|
|
751
|
+
console.log("Flushing message queue(Web SDK):", this.messageQueue);
|
|
752
|
+
while (this.messageQueue.length > 0) {
|
|
753
|
+
const msg = this.messageQueue.shift();
|
|
754
|
+
if (msg) this.postMessageToIframe(msg);
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
/**
|
|
758
|
+
* Listens to messages from the microfrontend running in the iframe.
|
|
759
|
+
* @example listenToIframeEvents();
|
|
760
|
+
*/
|
|
761
|
+
this.listenToIframeEvents = () => {
|
|
762
|
+
if (this.isListeningToIframeEvents) return;
|
|
763
|
+
window.addEventListener("message", this.handleIframeMessage);
|
|
764
|
+
this.isListeningToIframeEvents = true;
|
|
765
|
+
};
|
|
766
|
+
this.handleIframeMessage = (event) => {
|
|
767
|
+
if (!this.iframeUrl) return;
|
|
768
|
+
const expectedOrigin = new URL(this.iframeUrl).origin;
|
|
769
|
+
if (event.origin !== expectedOrigin) return;
|
|
770
|
+
const data = event.data;
|
|
771
|
+
if ((data == null ? void 0 : data.source) !== "NUVEI_IFRAME") return;
|
|
772
|
+
if (this.isDestroyed) return;
|
|
773
|
+
console.log("Received from iframe:(Web SDK)", data);
|
|
774
|
+
if (this.onMessage) {
|
|
775
|
+
this.onMessage(data);
|
|
776
|
+
}
|
|
777
|
+
switch (data.action) {
|
|
778
|
+
case "IFRAME_READY" /* IFRAME_READY */:
|
|
779
|
+
this.handleIframeReady();
|
|
780
|
+
break;
|
|
781
|
+
default:
|
|
782
|
+
break;
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
/**
|
|
786
|
+
* Handles the iframe ready event.
|
|
787
|
+
* @example handleIframeReady();
|
|
788
|
+
*/
|
|
789
|
+
this.handleIframeReady = () => {
|
|
790
|
+
console.log("Iframe is READY(Web SDK)");
|
|
791
|
+
this.isIframeReady = true;
|
|
792
|
+
this.flushMessageQueue();
|
|
793
|
+
};
|
|
794
|
+
/**
|
|
795
|
+
* Sends a post message to the microfrontend running in the iframe.
|
|
796
|
+
* This will fail silently if the iframe does not exist or does not have a contentWindow.
|
|
797
|
+
* @param {ISdkPostMessagePayload} payload - The payload to be sent as a post message.
|
|
798
|
+
* @example postMessageToIframe({ action: 'NAVIGATE', source: 'NUVEI_WEB_SDK', data: '/dashboard' });
|
|
799
|
+
*/
|
|
800
|
+
this.postMessageToIframe = (payload) => {
|
|
801
|
+
var _a;
|
|
802
|
+
if (!((_a = this == null ? void 0 : this.currentIframe) == null ? void 0 : _a.contentWindow)) {
|
|
803
|
+
console.warn("Iframe not available(Web SDK)");
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const origin = new URL(this.iframeUrl).origin;
|
|
807
|
+
console.log("Sending message to microfrontend(Web SDK):", payload);
|
|
808
|
+
this.currentIframe.contentWindow.postMessage(payload, origin);
|
|
809
|
+
};
|
|
810
|
+
const {
|
|
811
|
+
fetchClientSession,
|
|
812
|
+
refreshClientSession,
|
|
813
|
+
destroySession,
|
|
814
|
+
componentName,
|
|
815
|
+
container,
|
|
816
|
+
authConfig,
|
|
817
|
+
config,
|
|
818
|
+
onReady,
|
|
819
|
+
onError,
|
|
820
|
+
onMessage
|
|
821
|
+
} = params;
|
|
822
|
+
if (authConfig) {
|
|
823
|
+
const defaultAuthProvider = new DefaultAuthProvider(authConfig, componentName);
|
|
824
|
+
this.authProvider = {
|
|
825
|
+
fetchClientSession: fetchClientSession != null ? fetchClientSession : defaultAuthProvider.fetchClientSession,
|
|
826
|
+
refreshClientSession: refreshClientSession != null ? refreshClientSession : defaultAuthProvider.refreshClientSession,
|
|
827
|
+
destroySession: destroySession != null ? destroySession : defaultAuthProvider.destroySession
|
|
828
|
+
};
|
|
829
|
+
} else if (fetchClientSession && refreshClientSession && destroySession) {
|
|
830
|
+
this.authProvider = {
|
|
831
|
+
fetchClientSession,
|
|
832
|
+
refreshClientSession,
|
|
833
|
+
destroySession
|
|
834
|
+
};
|
|
835
|
+
} else {
|
|
836
|
+
throw new Error(
|
|
837
|
+
"authConfig is required when auth callbacks are not fully provided(Web SDK)"
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
this.componentName = componentName;
|
|
841
|
+
this.container = container;
|
|
842
|
+
if (config) {
|
|
843
|
+
this.sdkConfig = deepMerge(DEFAULT_CONFIG, config);
|
|
844
|
+
}
|
|
845
|
+
if (onReady) {
|
|
846
|
+
this.onReady = onReady;
|
|
847
|
+
}
|
|
848
|
+
if (onError) {
|
|
849
|
+
this.onError = onError;
|
|
850
|
+
}
|
|
851
|
+
if (onMessage) {
|
|
852
|
+
this.onMessage = onMessage;
|
|
853
|
+
}
|
|
854
|
+
this.listenToIframeEvents();
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
_NuveiSDK.mountPromises = /* @__PURE__ */ new Map();
|
|
858
|
+
_NuveiSDK.getMountKey = (params) => {
|
|
859
|
+
var _a;
|
|
860
|
+
const componentKey = String((_a = params.componentName) != null ? _a : "");
|
|
861
|
+
return componentKey;
|
|
862
|
+
};
|
|
863
|
+
// =============================|| PUBLIC METHODS ||============================== //
|
|
864
|
+
/**
|
|
865
|
+
* Creates and initializes an SDK instance in one call.
|
|
866
|
+
*/
|
|
867
|
+
_NuveiSDK.mount = (params) => __async(null, null, function* () {
|
|
868
|
+
const mountKey = _NuveiSDK.getMountKey(params);
|
|
869
|
+
const existingMount = _NuveiSDK.mountPromises.get(mountKey);
|
|
870
|
+
if (existingMount) return existingMount;
|
|
871
|
+
const instance = new _NuveiSDK(params);
|
|
872
|
+
instance.mountKey = mountKey;
|
|
873
|
+
const mountPromise = instance.initialize().then(() => instance).catch((error) => {
|
|
874
|
+
_NuveiSDK.mountPromises.delete(mountKey);
|
|
875
|
+
throw error;
|
|
876
|
+
});
|
|
877
|
+
_NuveiSDK.mountPromises.set(mountKey, mountPromise);
|
|
878
|
+
return mountPromise;
|
|
879
|
+
});
|
|
880
|
+
/**
|
|
881
|
+
* Alias for mount, useful for integrations that prefer create-style naming.
|
|
882
|
+
*/
|
|
883
|
+
_NuveiSDK.create = _NuveiSDK.mount;
|
|
884
|
+
var NuveiSDK = _NuveiSDK;
|
|
885
|
+
|
|
886
|
+
// src/cdn-index.ts
|
|
887
|
+
var cdnGlobal = window;
|
|
888
|
+
cdnGlobal.NCWebSDK = NuveiSDK;
|
|
889
|
+
cdnGlobal.NuveiSDK = NuveiSDK;
|
|
890
|
+
cdnGlobal.ModulesNameEnum = ModulesNameEnum;
|
|
891
|
+
})();
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";(()=>{var P=Object.defineProperty,O=Object.defineProperties;var U=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var K=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var C=(r,e,s)=>e in r?P(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s,f=(r,e)=>{for(var s in e||(e={}))K.call(e,s)&&C(r,s,e[s]);if(w)for(var s of w(e))L.call(e,s)&&C(r,s,e[s]);return r},S=(r,e)=>O(r,U(e));var u=(r,e,s)=>new Promise((t,n)=>{var i=c=>{try{o(s.next(c))}catch(l){n(l)}},a=c=>{try{o(s.throw(c))}catch(l){n(l)}},o=c=>c.done?t(c.value):Promise.resolve(c.value).then(i,a);o((s=s.apply(r,e)).next())});var m=(t=>(t.ONBOARDING_PARTNER="ONBOARDING_PARTNER",t.ONBOARDING_MERCHANT="ONBOARDING_MERCHANT",t.DOC_UTILITY="DOC_UTILITY",t))(m||{});var D=r=>{if(r&&typeof r=="object"){let e=Object.keys(r),s=e.length,t=e.length?"?":"";return e.forEach((n,i)=>{let a=i+1,o=r[n],c=r[e[a]];if(a<s&&g(o)){let l=t+n+"="+o;g(c)?t=l+"&":t=l}else g(o)&&(t=t+n+"="+o)}),t}return""},g=r=>!(r==null||r===""||typeof r=="number"&&Number.isNaN(r)||typeof r=="string"&&r.trim()===""),p=r=>{let e=t=>t!=null&&!(Array.isArray(t)&&t.length===0)&&!(typeof t=="object"&&Object.keys(t).length===0)&&!(typeof t=="string"&&t.trim()==="");if(!r||typeof r!="object")return;let s={};for(let t in r)if(r.hasOwnProperty(t)){let n=r[t];if(e(n))if(Array.isArray(n)){let i=n.filter(a=>e(a)).map(p).filter(a=>e(a));i.length&&(s[t]=i)}else if(typeof n=="object"){let i=p(n);e(i)&&(s[t]=i)}else s[t]=n}return Object.keys(s).length?s:void 0};var F={isSuccess:!1,accessToken:"",accessTokenExpiry:"",refreshToken:"",refreshTokenExpiry:""},_={isSuccess:!1,accessToken:"",accessTokenExpiry:""},y=class{constructor(e,s){this.currentAccessToken="";this.fetchClientSession=()=>u(this,null,function*(){let e=this.getAuthUrl("/auth/micro-frontend/tokens"),s=p({modules:[{name:this.getAuthModuleName()}],referenceId:this.authConfig.referenceId});try{let t=yield fetch(e,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(s)}),n=yield this.parseJsonResponse(t,e,"Frontend AccessToken");return this.currentAccessToken=n.accessToken||"",S(f(f({},F),n),{isSuccess:!0})}catch(t){throw this.createAuthError("Frontend AccessToken",e,t)}});this.refreshClientSession=e=>u(this,null,function*(){let s=this.getAuthUrl("/auth/micro-frontend/tokens/refresh");try{let t=yield fetch(s,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(p(e))}),n=yield this.parseJsonResponse(t,s,"Frontend AccessToken Refresh");return this.currentAccessToken=n.accessToken||this.currentAccessToken,S(f(f({},_),n),{isSuccess:!0})}catch(t){throw this.createAuthError("Frontend AccessToken Refresh",s,t)}});this.destroySession=()=>u(this,null,function*(){if(!this.currentAccessToken)return!0;let e=this.getAuthUrl("/auth/access-token/revoke");try{let s=yield fetch(e,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({accessToken:this.currentAccessToken})});if(!s.ok){let t=yield s.text();throw new Error(`Session revoke failed(Web SDK): ${s.status} ${s.statusText}. URL: ${e}. Response: ${t.slice(0,200)}`)}return this.currentAccessToken="",!0}catch(s){return console.error(this.createAuthError("Session revoke",e,s).message),!1}});this.getAuthModuleName=()=>{switch(this.moduleName){case"ONBOARDING_PARTNER":case"ONBOARDING_MERCHANT":return"ONBOARDING";default:return this.moduleName||""}};this.getHeaders=()=>({Authorization:this.authConfig.authToken||"","Content-Type":"application/json"});this.getAuthUrl=e=>{var t;let s=(t=this.authConfig.authApiUrl)==null?void 0:t.trim();if(!s)throw new Error("authConfig.authApiUrl is required(Web SDK)");return`${s.replace(/\/$/,"")}${e}`};this.parseJsonResponse=(e,s,t)=>u(null,null,function*(){let n=yield e.text();if(!e.ok)throw new Error(`${t} Error Response(Web SDK): ${e.status} ${e.statusText}. URL: ${s}. Response: ${n.slice(0,200)}`);let i=e.headers.get("content-type")||"";if(!i.includes("application/json"))throw new Error(`${t} expected JSON response(Web SDK). URL: ${s}. Content-Type: ${i||"unknown"}. Response: ${n.slice(0,200)}`);try{return JSON.parse(n)}catch(a){throw new Error(`${t} JSON parse failed(Web SDK). URL: ${s}. Response: ${n.slice(0,200)}`)}});this.createAuthError=(e,s,t)=>{if(t instanceof Error&&t.message.includes("(Web SDK)"))return t;let i=(t instanceof Error?t.message:String(t)).includes("Failed to fetch")?" This usually means the browser blocked the request because of CORS, the URL is unreachable, or the request was blocked before a response was returned.":"";return new Error(`${e} Request Failed(Web SDK). URL: ${s}.${i}`)};this.authConfig=e,this.moduleName=s}};function T(r,e){let s=f({},r);for(let t of Object.keys(e))r[t]&&typeof r[t]=="object"&&typeof e[t]=="object"&&!Array.isArray(r[t])&&!Array.isArray(e[t])?s[t]=T(r[t],e[t]):s[t]=e[t];return s}var E={iframeId:"nc-web-sdk-iframe",containerId:"websdk-container",iframeStyle:{width:"100%",height:"100vh",border:"none",display:"block"},sessionValidation:(r,e)=>!r||!e?!1:new Date(e)>new Date,sessionCheckInterval:10*60*1e3,environment:"uat"};var N=r=>{if(!r)return!0;let e;if(r instanceof Date)e=r;else if(typeof r=="number")e=new Date(r);else if(typeof r=="string"){let s=r.trim().replace(" ","T");e=new Date(s)}else return!0;return isNaN(e.getTime())?!0:Date.now()>e.getTime()};var v={local:"http://localhost:4000",dev:"https://dev3-non-pci.eastus.cloudapp.azure.com",preprod:"https://ignite-preprod.nuvei.com",prod:"https://ignite.nuvei.com"},b={local:"http://localhost:5000",dev:"https://dev3-non-pci.eastus.cloudapp.azure.com",preprod:"https://ignite-preprod.nuvei.com",prod:"https://ignite.nuvei.com"},W={ONBOARDING_PARTNER:"/_onboarding/partner/application",ONBOARDING_MERCHANT:"/_onboarding/merchant/application",DOC_UTILITY:"/_document-upload"},M="documentRequestId",$=(r="prod")=>{var e;return(e=v[r])!=null?e:v.prod},B=(r="prod")=>{var e;return(e=b[r])!=null?e:b.prod},V=r=>{var e;return(e=W[r])!=null?e:""},H=()=>typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(M),q=(r,e,s)=>s.iframeBaseUrl?s.iframeBaseUrl:r==="DOC_UTILITY"?B(e):$(e),x=(r,e)=>{var o,c;let s=(o=e.environment)!=null?o:"prod",t=q(r,s,e),n=V(r),i={};if(r==="DOC_UTILITY"){let l=(c=e.documentRequestId)!=null?c:H();i={[M]:l}}let a=D(i);return`${t}${n}${a}`};var h=class h{constructor(e){this.sdkConfig=f({},E);this.currentIframe=null;this.iframeUrl="";this.isIframeReady=!1;this.messageQueue=[];this.cachedSession=null;this.sessionCheckInterval=null;this.expiryTimeout=null;this.retryAttempts=0;this.MAX_RETRIES=3;this.REFRESH_BUFFER_MS=60*1e3;this.isListeningToIframeEvents=!1;this.isDestroyed=!1;this.initialize=()=>u(this,null,function*(){var e,s;if(this.isDestroyed=!1,!this.componentName)throw new Error("componentName is required to initialize the SDK(Web SDK)");try{let t=yield this.loadComponent(this.componentName);return this.isDestroyed||(yield(e=this.onReady)==null?void 0:e.call(this,this)),t}catch(t){throw(s=this.onError)==null||s.call(this,t),t}});this.loadComponent=e=>u(this,null,function*(){console.log("Component Requested to Load(Web SDK): ",e);try{let s=yield this.getClientSession();if(!this.sdkConfig.sessionValidation(s==null?void 0:s.accessToken,s==null?void 0:s.accessTokenExpiry))throw new Error("Token Validation FailedLoad(Web SDK)");this.iframeUrl=x(e,this.sdkConfig),console.log(`
|
|
2
|
+
Iframe URL(Web SDK): `,this.iframeUrl,`
|
|
3
|
+
`);let t=yield this.createIframeWithSource(this.iframeUrl,e);return this.currentIframe=t,this.updateIframeToken(s.accessToken),t}catch(s){throw this.destroyIframe(),s}});this.destroyIframe=()=>{this.currentIframe&&(this.currentIframe.remove(),this.currentIframe=null),this.stopSessionExpiryCheck()};this.destroy=()=>{this.isDestroyed=!0,this.destroyIframe(),this.mountKey&&(h.mountPromises.delete(this.mountKey),this.mountKey=void 0),this.messageQueue=[],this.isIframeReady=!1,window.removeEventListener("message",this.handleIframeMessage),this.isListeningToIframeEvents=!1};this.logout=()=>u(this,null,function*(){(yield this.authProvider.destroySession())?(this.stopSessionExpiryCheck(),this.destroyIframe()):console.error("Logout failed(Web SDK)")});this.updateIframeNavigation=e=>{this.enqueueMessage("NAVIGATE",e)};this.sendCustomDataToIframe=e=>{this.enqueueMessage("CUSTOM_DATA",e)};this.getClientSession=()=>u(this,null,function*(){var e,s,t,n;try{if(this.cachedSession&&((t=this.sdkConfig)!=null&&t.sessionValidation((e=this.cachedSession)==null?void 0:e.accessToken,(s=this.cachedSession)==null?void 0:s.accessTokenExpiry)))return this.cachedSession;{let i=yield this.authProvider.fetchClientSession();if(!i.isSuccess)throw new Error("Client Session Fetch Failed(Web SDK)");if(!((n=this.sdkConfig)!=null&&n.sessionValidation(i.accessToken,i.accessTokenExpiry)))throw new Error("Client Session Validation Failed(Web SDK)");return this.cachedSession=i,this.retryAttempts=0,i}}catch(i){throw i}});this.refreshedClientSession=()=>u(this,null,function*(){var e,s;if(!((e=this.cachedSession)!=null&&e.refreshToken)||!this.cachedSession.accessToken)throw console.error("Invalid or missing refreshToken or accessToken in cashed session. Destroying iframe(Web SDK)."),this.destroyIframe(),new Error("No session found(Web SDK)");try{let t=yield this.authProvider.refreshClientSession({accessToken:this.cachedSession.accessToken,refreshToken:this.cachedSession.refreshToken});if(!t.isSuccess)throw console.log("Invalid refresh session token(Called From Web SDK)"),new Error("Refresh Client Session Failed");if(!((s=this.sdkConfig)!=null&&s.sessionValidation(t.accessToken,t.accessTokenExpiry)))throw console.log("Invalid refresh session token(Called From Web SDK)"),new Error("Refresh Client Session Validation Failed");let n=f({},this.cachedSession);return n.accessToken=t.accessToken,n.accessTokenExpiry=t.accessTokenExpiry,this.cachedSession=n,this.retryAttempts=0,t}catch(t){throw console.error("Session Refresh Failed(Web SDK):",t),t}});this.createIframeWithSource=(e,s)=>new Promise((t,n)=>{let i=this.getContainerElement();if(!i)return n(new Error("SDK container not found(Web SDK)"));let a=this.getIframeId(s),o=document.getElementById(a);if(o){console.log(`Iframe with Id: ${a} already exists, reusing it(Web SDK)`),t(o);return}o=document.createElement("iframe"),o.src=e,o.id=a;let c=f({},this.sdkConfig.iframeStyle);c&&Object.assign(o.style,c),o.setAttribute("allow","clipboard-write *"),o.onload=()=>{console.log("Iframe loaded successfully(Web SDK)"),this.startSessionExpiryCheck(),t(o)},o.onerror=()=>{n(new Error("Iframe failed to load(Web SDK)"))},i.appendChild(o)});this.getContainerElement=()=>this.container instanceof HTMLElement?this.container:typeof this.container=="string"?document.querySelector(this.container)||document.getElementById(this.container):document.getElementById(this.sdkConfig.containerId);this.getIframeId=e=>{let s=String(e).toLowerCase().replace(/_/g,"-");return`${this.sdkConfig.iframeId}-${s}`};this.startSessionExpiryCheck=()=>u(this,null,function*(){var o,c;if(N((o=this.cachedSession)==null?void 0:o.refreshTokenExpiry)){console.error("Refresh token is expired. Stopping session expiry check(Web SDK)."),this.destroyIframe();return}let s=new Date,t=(c=this.cachedSession)==null?void 0:c.accessTokenExpiry,n=t?new Date(t):null;if(!n||isNaN(n.getTime())){console.error("Invalid or missing accessTokenExpiry in session. Stopping session expiry check(Web SDK)."),this.destroyIframe();return}let i=n.getTime()-s.getTime()-this.REFRESH_BUFFER_MS,a=()=>u(this,null,function*(){try{if(this.retryAttempts>=this.MAX_RETRIES){console.warn(`Max retry attempts (${this.MAX_RETRIES}) reached. Stopping session check(Web SDK).`),this.stopSessionExpiryCheck(),this.destroyIframe();return}let l=yield this.refreshedClientSession();this.updateIframeToken(l.accessToken),this.retryAttempts=0,this.startSessionExpiryCheck()}catch(l){console.error("Failed to perform session refresh(Web SDK):",l),this.retryAttempts++,this.stopSessionExpiryCheck(),this.expiryTimeout=setTimeout(a,5e3)}});this.stopSessionExpiryCheck(),i<=0?a():this.expiryTimeout=setTimeout(a,i)});this.stopSessionExpiryCheck=()=>{this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=null),this.sessionCheckInterval&&(clearInterval(this.sessionCheckInterval),this.sessionCheckInterval=null)};this.updateIframeToken=e=>{this.enqueueMessage("UPDATE_TOKEN",e)};this.enqueueMessage=(e,s)=>{let t={action:e,source:"NUVEI_WEB_SDK",data:s};if(!this.isIframeReady){console.log("Iframe not ready, queueing message(Web SDK):",t),this.messageQueue.push(t);return}this.postMessageToIframe(t)};this.flushMessageQueue=()=>{for(console.log("Flushing message queue(Web SDK):",this.messageQueue);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.postMessageToIframe(e)}};this.listenToIframeEvents=()=>{this.isListeningToIframeEvents||(window.addEventListener("message",this.handleIframeMessage),this.isListeningToIframeEvents=!0)};this.handleIframeMessage=e=>{if(!this.iframeUrl)return;let s=new URL(this.iframeUrl).origin;if(e.origin!==s)return;let t=e.data;if((t==null?void 0:t.source)==="NUVEI_IFRAME"&&!this.isDestroyed)switch(console.log("Received from iframe:(Web SDK)",t),this.onMessage&&this.onMessage(t),t.action){case"IFRAME_READY":this.handleIframeReady();break;default:break}};this.handleIframeReady=()=>{console.log("Iframe is READY(Web SDK)"),this.isIframeReady=!0,this.flushMessageQueue()};this.postMessageToIframe=e=>{var t;if(!((t=this==null?void 0:this.currentIframe)!=null&&t.contentWindow)){console.warn("Iframe not available(Web SDK)");return}let s=new URL(this.iframeUrl).origin;console.log("Sending message to microfrontend(Web SDK):",e),this.currentIframe.contentWindow.postMessage(e,s)};let{fetchClientSession:s,refreshClientSession:t,destroySession:n,componentName:i,container:a,authConfig:o,config:c,onReady:l,onError:k,onMessage:R}=e;if(o){let I=new y(o,i);this.authProvider={fetchClientSession:s!=null?s:I.fetchClientSession,refreshClientSession:t!=null?t:I.refreshClientSession,destroySession:n!=null?n:I.destroySession}}else if(s&&t&&n)this.authProvider={fetchClientSession:s,refreshClientSession:t,destroySession:n};else throw new Error("authConfig is required when auth callbacks are not fully provided(Web SDK)");this.componentName=i,this.container=a,c&&(this.sdkConfig=T(E,c)),l&&(this.onReady=l),k&&(this.onError=k),R&&(this.onMessage=R),this.listenToIframeEvents()}};h.mountPromises=new Map,h.getMountKey=e=>{var t;return String((t=e.componentName)!=null?t:"")},h.mount=e=>u(null,null,function*(){let s=h.getMountKey(e),t=h.mountPromises.get(s);if(t)return t;let n=new h(e);n.mountKey=s;let i=n.initialize().then(()=>n).catch(a=>{throw h.mountPromises.delete(s),a});return h.mountPromises.set(s,i),i}),h.create=h.mount;var d=h;var A=window;A.NCWebSDK=d;A.NuveiSDK=d;A.ModulesNameEnum=m;})();
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { ModulesNameEnum } from '../common/enums';
|
|
2
2
|
import { HTMLIFrameElement, INuveiInitParams } from '../interfaces';
|
|
3
3
|
export default class NuveiSDK {
|
|
4
|
+
private static readonly mountPromises;
|
|
5
|
+
private static getMountKey;
|
|
4
6
|
private sdkConfig;
|
|
5
7
|
private currentIframe;
|
|
6
8
|
private iframeUrl;
|
|
@@ -17,6 +19,7 @@ export default class NuveiSDK {
|
|
|
17
19
|
private container?;
|
|
18
20
|
private isListeningToIframeEvents;
|
|
19
21
|
private isDestroyed;
|
|
22
|
+
private mountKey?;
|
|
20
23
|
/**
|
|
21
24
|
* Initializes the Nuvei SDK instance
|
|
22
25
|
* @param {INuveiInitParams} params - Initialization parameters
|
package/dist/core/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,EAGhB,MAAM,eAAe,CAAC;AAQvB,OAAO,EACL,iBAAiB,EAKjB,gBAAgB,EAEjB,MAAM,eAAe,CAAC;AAIvB,MAAM,CAAC,OAAO,OAAO,QAAQ;IAC3B,OAAO,CAAC,SAAS,CAA0C;IAE3D,OAAO,CAAC,aAAa,CAAkC;IACvD,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,aAAa,CAAkB;IACvC,OAAO,CAAC,YAAY,CAAgC;IAEpD,OAAO,CAAC,aAAa,CAA+B;IACpD,OAAO,CAAC,oBAAoB,CAA+C;IAC3E,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAK;IACjC,OAAO,CAAC,iBAAiB,CAAa;IACtC,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,aAAa,CAAC,CAAkB;IACxC,OAAO,CAAC,SAAS,CAAC,CAAuB;IACzC,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,WAAW,CAAS;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,EAGhB,MAAM,eAAe,CAAC;AAQvB,OAAO,EACL,iBAAiB,EAKjB,gBAAgB,EAEjB,MAAM,eAAe,CAAC;AAIvB,MAAM,CAAC,OAAO,OAAO,QAAQ;IAC3B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAwC;IAC7E,OAAO,CAAC,MAAM,CAAC,WAAW,CAMxB;IAEF,OAAO,CAAC,SAAS,CAA0C;IAE3D,OAAO,CAAC,aAAa,CAAkC;IACvD,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,aAAa,CAAkB;IACvC,OAAO,CAAC,YAAY,CAAgC;IAEpD,OAAO,CAAC,aAAa,CAA+B;IACpD,OAAO,CAAC,oBAAoB,CAA+C;IAC3E,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAK;IACjC,OAAO,CAAC,iBAAiB,CAAa;IACtC,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,aAAa,CAAC,CAAkB;IACxC,OAAO,CAAC,SAAS,CAAC,CAAuB;IACzC,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,QAAQ,CAAC,CAAS;IAE1B;;;;;;;OAOG;gBACS,MAAM,EAAE,gBAAgB;IAwDpC,OAAO,CAAC,OAAO,CAAC,CAAqD;IACrE,OAAO,CAAC,OAAO,CAAC,CAA2B;IAC3C,OAAO,CAAC,SAAS,CAAC,CAAyB;IAI3C;;OAEG;IACH,gBAAuB,KAAK,GAAU,QAAQ,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAAC,CAiBhF;IAEF;;OAEG;IACH,gBAAuB,MAAM,WAtBiB,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAAC,CAsBnC;IAE/C;;;;;OAKG;IACI,UAAU,QAAa,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAgB7D;IAEF;;;;;;;;;;;;;;;OAeG;IACI,aAAa,GAClB,eAAe,eAAe,KAC7B,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CA2BlC;IAEF;;;OAGG;IACI,aAAa,aAOlB;IAEF;;OAEG;IACI,OAAO,aAWZ;IAEF;;;;;;;OAOG;IACI,MAAM,sBASX;IAEF;;;OAGG;IACI,sBAAsB,GAAI,MAAM,MAAM,UAE3C;IAEF;;;;OAIG;IACI,sBAAsB,GAAI,MAAM,GAAG,UAExC;IAIF;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,gBAAgB,CA4BtB;IAEF;;;;;;OAMG;IACH,OAAO,CAAC,sBAAsB,CAoC5B;IAEF;;;;;;;OAOG;IACH,OAAO,CAAC,sBAAsB,CAgD5B;IAEF,OAAO,CAAC,mBAAmB,CAUzB;IAEF,OAAO,CAAC,WAAW,CAGjB;IAEF;;;;;;;;OAQG;IACH,OAAO,CAAC,uBAAuB,CA2D7B;IAEF;;;;OAIG;IACH,OAAO,CAAC,sBAAsB,CAW5B;IAEF;;;OAGG;IACH,OAAO,CAAC,iBAAiB,CAEvB;IAEF;;;;;OAKG;IACH,OAAO,CAAC,cAAc,CAcpB;IAEF;;;;OAIG;IACH,OAAO,CAAC,iBAAiB,CAOvB;IAEF;;;OAGG;IACH,OAAO,CAAC,oBAAoB,CAK1B;IAEF,OAAO,CAAC,mBAAmB,CAwBzB;IAEF;;;OAGG;IACH,OAAO,CAAC,iBAAiB,CAIvB;IAEF;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB,CASzB;CACH"}
|
package/dist/core/index.js
CHANGED
|
@@ -183,6 +183,10 @@ var NuveiSDK = /** @class */ (function () {
|
|
|
183
183
|
this.destroy = function () {
|
|
184
184
|
_this.isDestroyed = true;
|
|
185
185
|
_this.destroyIframe();
|
|
186
|
+
if (_this.mountKey) {
|
|
187
|
+
_a.mountPromises.delete(_this.mountKey);
|
|
188
|
+
_this.mountKey = undefined;
|
|
189
|
+
}
|
|
186
190
|
_this.messageQueue = [];
|
|
187
191
|
_this.isIframeReady = false;
|
|
188
192
|
window.removeEventListener('message', _this.handleIframeMessage);
|
|
@@ -603,21 +607,36 @@ var NuveiSDK = /** @class */ (function () {
|
|
|
603
607
|
}
|
|
604
608
|
var _a;
|
|
605
609
|
_a = NuveiSDK;
|
|
610
|
+
NuveiSDK.mountPromises = new Map();
|
|
611
|
+
NuveiSDK.getMountKey = function (params) {
|
|
612
|
+
var _b;
|
|
613
|
+
var componentKey = String((_b = params.componentName) !== null && _b !== void 0 ? _b : '');
|
|
614
|
+
// The SDK uses one deterministic iframe ID per component. Deduplicate by
|
|
615
|
+
// component so a host remount with a new container object cannot start a
|
|
616
|
+
// second SDK instance for the same microfrontend.
|
|
617
|
+
return componentKey;
|
|
618
|
+
};
|
|
606
619
|
// =============================|| PUBLIC METHODS ||============================== //
|
|
607
620
|
/**
|
|
608
621
|
* Creates and initializes an SDK instance in one call.
|
|
609
622
|
*/
|
|
610
623
|
NuveiSDK.mount = function (params) { return __awaiter(void 0, void 0, void 0, function () {
|
|
611
|
-
var instance;
|
|
624
|
+
var mountKey, existingMount, instance, mountPromise;
|
|
612
625
|
return __generator(_a, function (_b) {
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
626
|
+
mountKey = _a.getMountKey(params);
|
|
627
|
+
existingMount = _a.mountPromises.get(mountKey);
|
|
628
|
+
if (existingMount)
|
|
629
|
+
return [2 /*return*/, existingMount];
|
|
630
|
+
instance = new _a(params);
|
|
631
|
+
instance.mountKey = mountKey;
|
|
632
|
+
mountPromise = instance.initialize()
|
|
633
|
+
.then(function () { return instance; })
|
|
634
|
+
.catch(function (error) {
|
|
635
|
+
_a.mountPromises.delete(mountKey);
|
|
636
|
+
throw error;
|
|
637
|
+
});
|
|
638
|
+
_a.mountPromises.set(mountKey, mountPromise);
|
|
639
|
+
return [2 /*return*/, mountPromise];
|
|
621
640
|
});
|
|
622
641
|
}); };
|
|
623
642
|
/**
|
package/package.json
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nuvei-connect/nc-websdk",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"build": "tsc && tsc-alias",
|
|
8
|
+
"build": "tsc && tsc-alias && esbuild src/cdn-index.ts --bundle --platform=browser --format=iife --target=es2015 --outfile=dist/cdn-index.js && esbuild src/cdn-index.ts --bundle --platform=browser --format=iife --target=es2015 --minify --outfile=dist/cdn-index.min.js",
|
|
9
9
|
"prepare": "npm run build",
|
|
10
10
|
"dev": "ts-node -r tsconfig-paths/register src/index.ts",
|
|
11
11
|
"start": "node -r tsconfig-paths/register dist/index.js",
|
|
12
12
|
"test": "jest",
|
|
13
13
|
"lint": "eslint src --ext .ts",
|
|
14
|
-
"docs": "typedoc --out docs src"
|
|
14
|
+
"docs": "typedoc --out docs src",
|
|
15
|
+
"serve:cdn": "npx http-server dist -p 3009 -c-1"
|
|
15
16
|
},
|
|
16
17
|
"files": [
|
|
17
18
|
"dist/**/*"
|