@accelbyte/sdk 3.0.8 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,821 +1,873 @@
1
- import { Buffer as Buffer$1 } from 'buffer';
2
- import axios from 'axios';
3
- import qs from 'query-string';
4
- import * as uuid from 'uuid';
5
- import { z } from 'zod';
1
+ // src/polyfills/browser.ts
2
+ import { Buffer as Buffer2 } from "buffer";
3
+ window.Buffer = Buffer2;
6
4
 
7
- /*
8
- * Copyright (c) 2018-2024 AccelByte Inc. All Rights Reserved
9
- * This is licensed software from AccelByte Inc, for limitations
10
- * and restrictions contact your company contract manager.
11
- */
12
- window.Buffer = Buffer$1;
5
+ // src/utils/ApiUtils.ts
6
+ import axios from "axios";
7
+ var ApiUtils = class {
8
+ };
9
+ ApiUtils.mergeAxiosConfigs = (config, overrides) => {
10
+ return {
11
+ ...config,
12
+ ...overrides,
13
+ headers: {
14
+ ...config?.headers,
15
+ ...overrides?.headers
16
+ }
17
+ };
18
+ };
19
+ ApiUtils.is4xxError = (error) => {
20
+ if (axios.isAxiosError(error) && error.response) {
21
+ return error.response.status >= 400 && error.response.status <= 499;
22
+ }
23
+ return false;
24
+ };
13
25
 
14
- var _a;
15
- class SdkDevice {
16
- }
17
- _a = SdkDevice;
18
- SdkDevice.ID_KEY = 'deviceId';
19
- SdkDevice.TYPE = {
20
- MOBILE: 'mobile',
21
- DESKTOP: 'desktop'
22
- };
23
- SdkDevice.getType = () => {
24
- return isMobile() ? SdkDevice.TYPE.MOBILE : SdkDevice.TYPE.DESKTOP;
25
- };
26
- SdkDevice.generateUUID = () => {
27
- const deviceIdInUUID = uuid.v4().split('-').join('');
28
- localStorage.setItem(SdkDevice.ID_KEY, deviceIdInUUID);
29
- return deviceIdInUUID;
30
- };
31
- SdkDevice.getDeviceId = () => {
32
- return localStorage.getItem(_a.ID_KEY) || _a.generateUUID();
33
- };
34
- /*
35
- Bellow function is copied from npm 'is-mobile'
36
- */
37
- const mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
38
- const tabletRE = /android|ipad|playbook|silk/i;
39
- const isMobile = (opts) => {
40
- if (!opts)
41
- opts = {};
42
- let ua = opts.ua;
43
- if (!ua && typeof navigator !== 'undefined')
44
- ua = navigator.userAgent;
45
- if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
46
- ua = ua.headers['user-agent'];
47
- }
48
- if (typeof ua !== 'string')
49
- return false;
50
- let result = mobileRE.test(ua) || (!!opts.tablet && tabletRE.test(ua));
51
- if (!result &&
52
- opts.tablet &&
53
- opts.featureDetect &&
54
- navigator &&
55
- navigator.maxTouchPoints > 1 &&
56
- ua.indexOf('Macintosh') !== -1 &&
57
- ua.indexOf('Safari') !== -1) {
58
- result = true;
59
- }
60
- return result;
26
+ // src/utils/Network.ts
27
+ import axios2 from "axios";
28
+ import qs from "query-string";
29
+
30
+ // src/utils/SdkDevice.ts
31
+ import * as uuid from "uuid";
32
+ var _SdkDevice = class _SdkDevice {
33
+ };
34
+ _SdkDevice.ID_KEY = "deviceId";
35
+ _SdkDevice.TYPE = {
36
+ MOBILE: "mobile",
37
+ DESKTOP: "desktop"
38
+ };
39
+ _SdkDevice.getType = () => {
40
+ return isMobile() ? _SdkDevice.TYPE.MOBILE : _SdkDevice.TYPE.DESKTOP;
41
+ };
42
+ _SdkDevice.generateUUID = () => {
43
+ const deviceIdInUUID = uuid.v4().split("-").join("");
44
+ localStorage.setItem(_SdkDevice.ID_KEY, deviceIdInUUID);
45
+ return deviceIdInUUID;
46
+ };
47
+ _SdkDevice.getDeviceId = () => {
48
+ return localStorage.getItem(_SdkDevice.ID_KEY) || _SdkDevice.generateUUID();
49
+ };
50
+ var SdkDevice = _SdkDevice;
51
+ var mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
52
+ var tabletRE = /android|ipad|playbook|silk/i;
53
+ var isMobile = (opts) => {
54
+ if (!opts) opts = {};
55
+ let ua = opts.ua;
56
+ if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent;
57
+ if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") {
58
+ ua = ua.headers["user-agent"];
59
+ }
60
+ if (typeof ua !== "string") return false;
61
+ let result = mobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua);
62
+ if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) {
63
+ result = true;
64
+ }
65
+ return result;
61
66
  };
62
67
 
63
- /*
64
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
65
- * This is licensed software from AccelByte Inc, for limitations
66
- * and restrictions contact your company contract manager.
67
- */
68
- const requestInterceptors = new Map();
69
- const responseInterceptors = new Map();
70
- const injectRequestInterceptors = (requestInterceptor, errorInterceptor) => {
71
- const pair = { interceptor: requestInterceptor, errorInterceptor };
72
- const ejectId = axios.interceptors.request.use(requestInterceptor, errorInterceptor);
73
- requestInterceptors.set(ejectId, pair);
74
- return ejectId;
75
- };
76
- const injectResponseInterceptors = (responseInterceptor, errorInterceptor) => {
77
- const pair = { interceptor: responseInterceptor, errorInterceptor };
78
- const ejectId = axios.interceptors.response.use(responseInterceptor, errorInterceptor);
79
- responseInterceptors.set(ejectId, pair);
80
- return ejectId;
81
- };
82
- const loggerInterceptor = (axiosInstance) => {
83
- axiosInstance.interceptors.request.use(config => {
84
- return config;
85
- }, error => {
86
- return Promise.reject(error);
87
- });
88
- };
89
- class Network {
90
- //
91
- static create(...configs) {
92
- const axiosInstance = axios.create(Object.assign({
93
- paramsSerializer: qs.stringify
94
- }, ...configs));
95
- Array.from(requestInterceptors).forEach(([_key, interceptorPair]) => {
96
- const { interceptor, errorInterceptor } = interceptorPair;
97
- axiosInstance.interceptors.request.use(interceptor, errorInterceptor);
98
- });
99
- Array.from(responseInterceptors).forEach(([_key, interceptorPair]) => {
100
- const { interceptor, errorInterceptor } = interceptorPair;
101
- axiosInstance.interceptors.response.use(interceptor, errorInterceptor);
102
- });
103
- loggerInterceptor(axiosInstance);
104
- return axiosInstance;
105
- }
106
- static withBearerToken(accessToken, config) {
107
- return Network.create(config || {}, {
108
- headers: { Authorization: `Bearer ${accessToken}` }
109
- });
110
- }
111
- }
112
- Network.setDeviceTokenCookie = () => {
113
- const deviceId = SdkDevice.getDeviceId();
114
- document.cookie = `device_token=${deviceId}; path=/;`;
115
- };
116
- Network.removeDeviceTokenCookie = () => {
117
- document.cookie = `device_token=; expires=${new Date(0).toUTCString()}`;
118
- };
119
- Network.getFormUrlEncodedData = (data) => {
120
- const formPayload = new URLSearchParams();
121
- const formKeys = Object.keys(data);
122
- formKeys.forEach(key => {
123
- if (data[key])
124
- formPayload.append(key, data[key]);
125
- });
126
- return formPayload;
68
+ // src/utils/Network.ts
69
+ var _Network = class _Network {
70
+ static create(...configs) {
71
+ const axiosInstance = axios2.create(
72
+ Object.assign(
73
+ {
74
+ paramsSerializer: qs.stringify
75
+ },
76
+ ...configs
77
+ )
78
+ );
79
+ return axiosInstance;
80
+ }
81
+ static withBearerToken(accessToken, config) {
82
+ return _Network.create(config || {}, {
83
+ headers: { Authorization: `Bearer ${accessToken}` }
84
+ });
85
+ }
86
+ };
87
+ _Network.setDeviceTokenCookie = () => {
88
+ const deviceId = SdkDevice.getDeviceId();
89
+ document.cookie = `device_token=${deviceId}; path=/;`;
127
90
  };
91
+ _Network.removeDeviceTokenCookie = () => {
92
+ document.cookie = `device_token=; expires=${(/* @__PURE__ */ new Date(0)).toUTCString()}`;
93
+ };
94
+ _Network.getFormUrlEncodedData = (data) => {
95
+ const formPayload = new URLSearchParams();
96
+ const formKeys = Object.keys(data);
97
+ formKeys.forEach((key) => {
98
+ if (data[key]) formPayload.append(key, data[key]);
99
+ });
100
+ return formPayload;
101
+ };
102
+ var Network = _Network;
128
103
 
129
- const ERROR_ELIGIBILITY_CODE = 13130;
130
- const injectErrorInterceptors = ({ baseUrl, onError, onTooManyRequest, onUserEligibilityChange }) => {
131
- injectResponseInterceptors(response => {
132
- return response;
133
- }, (error) => {
134
- if (error.response) {
135
- const { response } = error;
136
- if (response?.status === 403 && response?.config.url.includes(baseUrl) && response?.config.withCredentials) {
137
- if (response.data.errorCode === ERROR_ELIGIBILITY_CODE && onUserEligibilityChange) {
138
- onUserEligibilityChange();
139
- }
140
- }
141
- if (response?.status === 429 /* TooManyRequests */ && onTooManyRequest) {
142
- onTooManyRequest(error);
143
- }
144
- }
145
- if (onError) {
146
- onError(error);
147
- }
148
- throw error;
149
- });
104
+ // src/AccelByteSDK.ts
105
+ var AccelByte = {
106
+ SDK: (param) => {
107
+ return new AccelByteSDK(param);
108
+ }
109
+ };
110
+ var AccelByteSDK = class _AccelByteSDK {
111
+ constructor({ coreConfig, axiosConfig }) {
112
+ this.coreConfig = {
113
+ ...coreConfig,
114
+ useSchemaValidation: coreConfig.useSchemaValidation ?? true
115
+ };
116
+ this.axiosConfig = {
117
+ /**
118
+ * when user create a variable to store intercepters and passed into sdk
119
+ * the sdk will use the variable as reference value,
120
+ * so when new interceptor added, reference value will also has the new interceptor,
121
+ * to avoid this we create shallow copy for the interceptors
122
+ */
123
+ interceptors: axiosConfig?.interceptors ? [...axiosConfig.interceptors] : void 0,
124
+ request: {
125
+ timeout: 6e4,
126
+ withCredentials: true,
127
+ ...axiosConfig?.request,
128
+ headers: {
129
+ "Content-Type": "application/json",
130
+ ...axiosConfig?.request?.headers
131
+ }
132
+ }
133
+ };
134
+ this.axiosInstance = this.createAxiosInstance();
135
+ this.token = {};
136
+ }
137
+ createAxiosInstance() {
138
+ const axiosInstance = Network.create({ baseURL: this.coreConfig.baseURL, ...this.axiosConfig.request });
139
+ const interceptors = this.axiosConfig.interceptors;
140
+ if (interceptors) {
141
+ for (const interceptor of interceptors) {
142
+ if (interceptor.type === "request") {
143
+ axiosInstance.interceptors.request.use(interceptor?.onRequest, interceptor.onError);
144
+ }
145
+ if (interceptor.type === "response") {
146
+ axiosInstance.interceptors.response.use(interceptor?.onSuccess, interceptor.onError);
147
+ }
148
+ }
149
+ }
150
+ return axiosInstance;
151
+ }
152
+ /**
153
+ * Assembles and returns the current Axios instance along with core and Axios configurations.
154
+ */
155
+ assembly() {
156
+ return {
157
+ axiosInstance: this.axiosInstance,
158
+ coreConfig: this.coreConfig,
159
+ axiosConfig: this.axiosConfig
160
+ };
161
+ }
162
+ /**
163
+ * Creates a new instance of AccelByteSDK with a shallow copy of the current configurations.
164
+ * Optionally allows excluding interceptors.
165
+ * @param {boolean} [opts.interceptors] - Whether to include interceptors in the clone. Default is true.
166
+ * @returns {AccelByteSDK} A new instance of AccelByteSDK with the cloned configuration.
167
+ */
168
+ clone(opts) {
169
+ const newConfigs = {
170
+ coreConfig: { ...this.coreConfig },
171
+ axiosConfig: { ...this.axiosConfig }
172
+ };
173
+ if (opts?.interceptors === false) {
174
+ delete newConfigs.axiosConfig.interceptors;
175
+ }
176
+ const newSdkInstance = new _AccelByteSDK(newConfigs);
177
+ newSdkInstance.setToken(this.token);
178
+ return newSdkInstance;
179
+ }
180
+ /**
181
+ * Adds interceptors to the current Axios configuration.
182
+ */
183
+ addInterceptors(interceptors) {
184
+ if (!this.axiosConfig.interceptors) {
185
+ this.axiosConfig.interceptors = [];
186
+ }
187
+ this.axiosConfig.interceptors.push(...interceptors);
188
+ return this;
189
+ }
190
+ removeInterceptors(filterCallback) {
191
+ if (!this.axiosConfig?.interceptors) return this;
192
+ if (!filterCallback) {
193
+ this.axiosConfig.interceptors = void 0;
194
+ this.axiosInstance.interceptors.request.clear();
195
+ this.axiosInstance.interceptors.response.clear();
196
+ return this;
197
+ }
198
+ this.axiosConfig.interceptors = this.axiosConfig.interceptors.filter(filterCallback);
199
+ this.axiosInstance = this.createAxiosInstance();
200
+ return this;
201
+ }
202
+ /**
203
+ * Updates the SDK's core and Axios configurations.
204
+ * Merges the provided configurations with the current ones.
205
+ */
206
+ setConfig({ coreConfig, axiosConfig }) {
207
+ this.coreConfig = {
208
+ ...this.coreConfig,
209
+ ...coreConfig
210
+ };
211
+ this.axiosConfig = {
212
+ ...this.axiosConfig,
213
+ ...axiosConfig?.interceptors,
214
+ request: ApiUtils.mergeAxiosConfigs(this.axiosConfig.request, axiosConfig?.request)
215
+ };
216
+ this.axiosInstance = this.createAxiosInstance();
217
+ return this;
218
+ }
219
+ /**
220
+ * Set accessToken and refreshToken and updates the Axios request headers to use Bearer authentication.
221
+ */
222
+ setToken(token) {
223
+ this.token = {
224
+ ...this.token,
225
+ ...token
226
+ };
227
+ const configOverride = { headers: { Authorization: this.token.accessToken ? `Bearer ${this.token.accessToken}` : "" } };
228
+ this.axiosConfig = {
229
+ ...this.axiosConfig,
230
+ request: ApiUtils.mergeAxiosConfigs(this.axiosInstance.defaults, configOverride)
231
+ };
232
+ this.axiosInstance = this.createAxiosInstance();
233
+ }
234
+ /**
235
+ * Removes the currently set token.
236
+ */
237
+ removeToken() {
238
+ this.token = {};
239
+ const configOverride = { headers: { Authorization: void 0 } };
240
+ this.axiosConfig = {
241
+ ...this.axiosConfig,
242
+ request: ApiUtils.mergeAxiosConfigs(this.axiosInstance.defaults, configOverride)
243
+ };
244
+ this.axiosInstance = this.createAxiosInstance();
245
+ }
246
+ /**
247
+ * Retrieves the current token configuration.
248
+ */
249
+ getToken() {
250
+ return this.token;
251
+ }
150
252
  };
151
253
 
152
- /*
153
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
154
- * This is licensed software from AccelByte Inc, for limitations
155
- * and restrictions contact your company contract manager.
156
- */
157
- class BrowserHelper {
158
- }
159
- BrowserHelper.isOnBrowser = () => {
160
- return typeof window !== 'undefined' && window.document;
254
+ // src/constants/IamErrorCode.ts
255
+ var IamErrorCode = /* @__PURE__ */ ((IamErrorCode2) => {
256
+ IamErrorCode2[IamErrorCode2["InternalServerError"] = 2e4] = "InternalServerError";
257
+ IamErrorCode2[IamErrorCode2["UnauthorizedAccess"] = 20001] = "UnauthorizedAccess";
258
+ IamErrorCode2[IamErrorCode2["ValidationError"] = 20002] = "ValidationError";
259
+ IamErrorCode2[IamErrorCode2["ForbiddenAccess"] = 20003] = "ForbiddenAccess";
260
+ IamErrorCode2[IamErrorCode2["TooManyRequests"] = 20007] = "TooManyRequests";
261
+ IamErrorCode2[IamErrorCode2["UserNotFound"] = 20008] = "UserNotFound";
262
+ IamErrorCode2[IamErrorCode2["TokenIsExpired"] = 20011] = "TokenIsExpired";
263
+ IamErrorCode2[IamErrorCode2["InsufficientPermissions"] = 20013] = "InsufficientPermissions";
264
+ IamErrorCode2[IamErrorCode2["InvalidAudience"] = 20014] = "InvalidAudience";
265
+ IamErrorCode2[IamErrorCode2["InsufficientScope"] = 20015] = "InsufficientScope";
266
+ IamErrorCode2[IamErrorCode2["UnableToParseRequestBody"] = 20019] = "UnableToParseRequestBody";
267
+ IamErrorCode2[IamErrorCode2["InvalidPaginationParameters"] = 20021] = "InvalidPaginationParameters";
268
+ IamErrorCode2[IamErrorCode2["TokenIsNotUserToken"] = 20022] = "TokenIsNotUserToken";
269
+ IamErrorCode2[IamErrorCode2["InvalidRefererHeader"] = 20023] = "InvalidRefererHeader";
270
+ IamErrorCode2[IamErrorCode2["SubdomainMismatch"] = 20030] = "SubdomainMismatch";
271
+ return IamErrorCode2;
272
+ })(IamErrorCode || {});
273
+
274
+ // src/constants/LinkAccount.ts
275
+ var ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT = 10200;
276
+ var ERROR_CODE_LINK_DELETION_ACCOUNT = 10135;
277
+ var ERROR_CODE_TOKEN_EXPIRED = 10196;
278
+ var ERROR_USER_BANNED = 10134;
279
+
280
+ // src/interceptors/AuthInterceptors.ts
281
+ import axios3 from "axios";
282
+
283
+ // src/utils/DesktopChecker.ts
284
+ var _DesktopChecker = class _DesktopChecker {
285
+ static isDesktopApp() {
286
+ return _DesktopChecker.desktopApp && !_DesktopChecker.isInIframe();
287
+ }
288
+ static isInIframe() {
289
+ try {
290
+ return window.self !== window.top;
291
+ } catch (error) {
292
+ return true;
293
+ }
294
+ }
295
+ // borrowed from https://github.com/cheton/is-electron
296
+ static isElectron() {
297
+ if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") {
298
+ return true;
299
+ }
300
+ if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) {
301
+ return true;
302
+ }
303
+ if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) {
304
+ return true;
305
+ }
306
+ return false;
307
+ }
161
308
  };
309
+ _DesktopChecker.desktopApp = _DesktopChecker.isElectron();
310
+ var DesktopChecker = _DesktopChecker;
162
311
 
163
- class RefreshSession {
164
- }
165
- // --
166
- RefreshSession.KEY = 'RefreshSession.lock';
167
- RefreshSession.isLocked = () => {
168
- if (!BrowserHelper.isOnBrowser())
169
- return false;
170
- const lockStatus = localStorage.getItem(RefreshSession.KEY);
171
- if (!lockStatus) {
172
- return false;
173
- }
174
- const lockExpiry = Number(lockStatus);
175
- if (isNaN(lockExpiry)) {
176
- return false;
177
- }
178
- return lockExpiry > new Date().getTime();
179
- };
180
- RefreshSession.lock = (expiry) => {
181
- if (!BrowserHelper.isOnBrowser())
182
- return;
183
- localStorage.setItem(RefreshSession.KEY, `${new Date().getTime() + expiry}`);
184
- };
185
- RefreshSession.unlock = () => {
186
- if (!BrowserHelper.isOnBrowser())
187
- return;
188
- localStorage.removeItem(RefreshSession.KEY);
189
- };
190
- RefreshSession.sleepAsync = (timeInMs) => new Promise(resolve => setTimeout(resolve, timeInMs));
191
- RefreshSession.isBearerAuth = (config) => {
192
- // @ts-ignore
193
- if (config?.headers?.Authorization?.toLowerCase().indexOf('bearer') > -1) {
194
- return true;
195
- }
196
- return false;
312
+ // src/utils/BrowserHelper.ts
313
+ var BrowserHelper = class {
314
+ };
315
+ BrowserHelper.isOnBrowser = () => {
316
+ return typeof window !== "undefined" && window.document;
197
317
  };
198
318
 
199
- /*
200
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
201
- * This is licensed software from AccelByte Inc, for limitations
202
- * and restrictions contact your company contract manager.
203
- */
204
- class CodeGenUtil {
205
- /**
206
- * Returns a hash code from a string
207
- * @param {String} str The string to hash.
208
- * @return {Number} A 32bit integer
209
- * @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
210
- */
211
- static hashCode(str) {
212
- let hash = 0;
213
- for (let i = 0, len = str.length; i < len; i++) {
214
- const chr = str.charCodeAt(i);
215
- hash = (hash << 5) - hash + chr;
216
- hash |= 0; // Convert to 32bit integer
217
- }
218
- return hash;
219
- }
220
- }
221
- CodeGenUtil.getFormUrlEncodedData = (data) => {
222
- const formPayload = new URLSearchParams();
223
- const formKeys = Object.keys(data);
224
- formKeys.forEach(key => {
225
- if (typeof data[key] !== 'undefined')
226
- formPayload.append(key, data[key]);
227
- });
228
- return formPayload;
319
+ // src/utils/RefreshSession.ts
320
+ var _RefreshSession = class _RefreshSession {
321
+ };
322
+ // --
323
+ _RefreshSession.KEY = "RefreshSession.lock";
324
+ _RefreshSession.isLocked = () => {
325
+ if (!BrowserHelper.isOnBrowser()) return false;
326
+ const lockStatus = localStorage.getItem(_RefreshSession.KEY);
327
+ if (!lockStatus) {
328
+ return false;
329
+ }
330
+ const lockExpiry = Number(lockStatus);
331
+ if (isNaN(lockExpiry)) {
332
+ return false;
333
+ }
334
+ return lockExpiry > (/* @__PURE__ */ new Date()).getTime();
335
+ };
336
+ _RefreshSession.lock = (expiry) => {
337
+ if (!BrowserHelper.isOnBrowser()) return;
338
+ localStorage.setItem(_RefreshSession.KEY, `${(/* @__PURE__ */ new Date()).getTime() + expiry}`);
339
+ };
340
+ _RefreshSession.unlock = () => {
341
+ if (!BrowserHelper.isOnBrowser()) return;
342
+ localStorage.removeItem(_RefreshSession.KEY);
229
343
  };
344
+ _RefreshSession.sleepAsync = (timeInMs) => new Promise((resolve) => setTimeout(resolve, timeInMs));
345
+ _RefreshSession.isBearerAuth = (config) => {
346
+ if (config?.headers?.Authorization?.toLowerCase().indexOf("bearer") > -1) {
347
+ return true;
348
+ }
349
+ return false;
350
+ };
351
+ var RefreshSession = _RefreshSession;
230
352
 
231
- class Validate {
232
- static validateOrReturnResponse(useSchemaValidation, networkCall, Codec, modelName) {
233
- return useSchemaValidation ? Validate.responseType(() => networkCall(), Codec, modelName) : Validate.unsafeResponse(() => networkCall());
234
- }
235
- static responseType(networkCall, Codec, modelName) {
236
- return wrapNetworkCallSafely(async () => {
237
- const response = await networkCall();
238
- const decodeResult = Codec.safeParse(response.data);
239
- if (!decodeResult.success && response.status !== 204) {
240
- throw new DecodeError({ error: decodeResult.error, response, modelName });
241
- }
242
- return response;
243
- });
244
- }
245
- static unsafeResponse(networkCall) {
246
- return wrapNetworkCallSafely(() => networkCall());
247
- }
248
- static safeParse(data, Codec) {
249
- const result = Codec.safeParse(data);
250
- if (result.success) {
251
- return result.data;
252
- }
253
- return null;
254
- }
255
- }
256
- async function wrapNetworkCallSafely(networkCallFunction) {
257
- try {
258
- const response = await networkCallFunction();
259
- // Cleanup so we avoid polluting the response
260
- // @ts-ignore
261
- delete response.headers; // perhaps this may be required?
262
- // @ts-ignore
263
- delete response.statusText;
264
- // @ts-ignore
265
- delete response.config; // axios specific
266
- delete response.request;
267
- return { response, error: null };
268
- }
269
- catch (error) {
270
- return { response: null, error: error };
271
- }
272
- }
273
- class DecodeError extends Error {
274
- constructor({ error, response, modelName }) {
275
- const msg = `response from url "${response.config.url}" doesn't match model "${modelName}"`;
276
- super(msg);
277
- console.error(msg, error);
278
- }
279
- }
353
+ // ../sdk-iam/src/generated-definitions/TokenWithDeviceCookieResponseV3.ts
354
+ import { z as z4 } from "zod";
280
355
 
281
- /*
282
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
283
- * This is licensed software from AccelByte Inc, for limitations
284
- * and restrictions contact your company contract manager.
285
- */
286
- const JwtBanV3 = z.object({
287
- ban: z.string(),
288
- disabledDate: z.string().nullish(),
289
- enabled: z.boolean(),
290
- endDate: z.string(),
291
- targetedNamespace: z.string()
356
+ // ../sdk-iam/src/generated-definitions/JwtBanV3.ts
357
+ import { z } from "zod";
358
+ var JwtBanV3 = z.object({
359
+ ban: z.string(),
360
+ disabledDate: z.string().nullish(),
361
+ enabled: z.boolean(),
362
+ endDate: z.string(),
363
+ targetedNamespace: z.string()
292
364
  });
293
365
 
294
- /*
295
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
296
- * This is licensed software from AccelByte Inc, for limitations
297
- * and restrictions contact your company contract manager.
298
- */
299
- const NamespaceRole = z.object({ namespace: z.string(), roleId: z.string() });
366
+ // ../sdk-iam/src/generated-definitions/NamespaceRole.ts
367
+ import { z as z2 } from "zod";
368
+ var NamespaceRole = z2.object({ namespace: z2.string(), roleId: z2.string() });
300
369
 
301
- /*
302
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
303
- * This is licensed software from AccelByte Inc, for limitations
304
- * and restrictions contact your company contract manager.
305
- */
306
- const PermissionV3 = z.object({
307
- action: z.number().int(),
308
- resource: z.string(),
309
- schedAction: z.number().int().nullish(),
310
- schedCron: z.string().nullish(),
311
- schedRange: z.array(z.string()).nullish()
370
+ // ../sdk-iam/src/generated-definitions/PermissionV3.ts
371
+ import { z as z3 } from "zod";
372
+ var PermissionV3 = z3.object({
373
+ action: z3.number().int(),
374
+ resource: z3.string(),
375
+ schedAction: z3.number().int().nullish(),
376
+ schedCron: z3.string().nullish(),
377
+ schedRange: z3.array(z3.string()).nullish()
312
378
  });
313
379
 
314
- /*
315
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
316
- * This is licensed software from AccelByte Inc, for limitations
317
- * and restrictions contact your company contract manager.
318
- */
319
- const TokenWithDeviceCookieResponseV3 = z.object({
320
- access_token: z.string(),
321
- auth_trust_id: z.string().nullish(),
322
- bans: z.array(JwtBanV3).nullish(),
323
- display_name: z.string().nullish(),
324
- expires_in: z.number().int(),
325
- is_comply: z.boolean().nullish(),
326
- jflgs: z.number().int().nullish(),
327
- namespace: z.string(),
328
- namespace_roles: z.array(NamespaceRole).nullish(),
329
- permissions: z.array(PermissionV3),
330
- platform_id: z.string().nullish(),
331
- platform_user_id: z.string().nullish(),
332
- refresh_expires_in: z.number().int().nullish(),
333
- refresh_token: z.string().nullish(),
334
- roles: z.array(z.string()).nullish(),
335
- scope: z.string(),
336
- simultaneous_platform_id: z.string().nullish(),
337
- simultaneous_platform_user_id: z.string().nullish(),
338
- token_type: z.string(),
339
- unique_display_name: z.string().nullish(),
340
- user_id: z.string().nullish(),
341
- xuid: z.string().nullish()
380
+ // ../sdk-iam/src/generated-definitions/TokenWithDeviceCookieResponseV3.ts
381
+ var TokenWithDeviceCookieResponseV3 = z4.object({
382
+ access_token: z4.string(),
383
+ auth_trust_id: z4.string().nullish(),
384
+ bans: z4.array(JwtBanV3).nullish(),
385
+ display_name: z4.string().nullish(),
386
+ expires_in: z4.number().int(),
387
+ is_comply: z4.boolean().nullish(),
388
+ jflgs: z4.number().int().nullish(),
389
+ namespace: z4.string(),
390
+ namespace_roles: z4.array(NamespaceRole).nullish(),
391
+ permissions: z4.array(PermissionV3),
392
+ platform_id: z4.string().nullish(),
393
+ platform_user_id: z4.string().nullish(),
394
+ refresh_expires_in: z4.number().int().nullish(),
395
+ refresh_token: z4.string().nullish(),
396
+ roles: z4.array(z4.string()).nullish(),
397
+ scope: z4.string(),
398
+ simultaneous_platform_id: z4.string().nullish(),
399
+ simultaneous_platform_user_id: z4.string().nullish(),
400
+ token_type: z4.string(),
401
+ unique_display_name: z4.string().nullish(),
402
+ user_id: z4.string().nullish(),
403
+ xuid: z4.string().nullish()
342
404
  });
343
405
 
344
- /*
345
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
346
- * This is licensed software from AccelByte Inc, for limitations
347
- * and restrictions contact your company contract manager.
348
- */
349
- class OAuth20$ {
350
- // @ts-ignore
351
- constructor(axiosInstance, namespace) {
352
- this.axiosInstance = axiosInstance;
353
- this.namespace = namespace;
354
- }
355
- postOauthToken(data) {
356
- const params = {};
357
- const url = '/iam/v3/oauth/token';
358
- const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
359
- ...params,
360
- headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' }
361
- });
362
- return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, 'TokenWithDeviceCookieResponseV3');
363
- }
364
- }
406
+ // src/utils/CodeGenUtil.ts
407
+ var CodeGenUtil = class {
408
+ /**
409
+ * Returns a hash code from a string
410
+ * @param {String} str The string to hash.
411
+ * @return {Number} A 32bit integer
412
+ * @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
413
+ */
414
+ static hashCode(str) {
415
+ let hash = 0;
416
+ for (let i = 0, len = str.length; i < len; i++) {
417
+ const chr = str.charCodeAt(i);
418
+ hash = (hash << 5) - hash + chr;
419
+ hash |= 0;
420
+ }
421
+ return hash;
422
+ }
423
+ };
424
+ CodeGenUtil.getFormUrlEncodedData = (data) => {
425
+ const formPayload = new URLSearchParams();
426
+ const formKeys = Object.keys(data);
427
+ formKeys.forEach((key) => {
428
+ if (typeof data[key] !== "undefined") formPayload.append(key, data[key]);
429
+ });
430
+ return formPayload;
431
+ };
365
432
 
366
- /*
367
- * Copyright (c) 2022 AccelByte Inc. All Rights Reserved
368
- * This is licensed software from AccelByte Inc, for limitations
369
- * and restrictions contact your company contract manager.
370
- */
371
- class DesktopChecker {
372
- static isDesktopApp() {
373
- return DesktopChecker.desktopApp && !DesktopChecker.isInIframe();
374
- }
375
- static isInIframe() {
376
- try {
377
- return window.self !== window.top;
378
- }
379
- catch (error) {
380
- return true;
381
- }
382
- }
383
- // borrowed from https://github.com/cheton/is-electron
384
- static isElectron() {
385
- // @ts-ignore Renderer process
386
- if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
387
- return true;
388
- }
389
- // Main process
390
- if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {
391
- return true;
392
- }
393
- // Detect the user agent when the `nodeIntegration` option is set to false
394
- if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {
395
- return true;
396
- }
397
- return false;
398
- }
399
- }
400
- DesktopChecker.desktopApp = DesktopChecker.isElectron();
433
+ // src/utils/Validate.ts
434
+ var Validate = class _Validate {
435
+ static validateOrReturnResponse(useSchemaValidation, networkCall, Codec, modelName) {
436
+ return useSchemaValidation ? _Validate.responseType(() => networkCall(), Codec, modelName) : _Validate.unsafeResponse(() => networkCall());
437
+ }
438
+ static responseType(networkCall, Codec, modelName) {
439
+ return wrapNetworkCallSafely(async () => {
440
+ const response = await networkCall();
441
+ const decodeResult = Codec.safeParse(response.data);
442
+ if (!decodeResult.success && response.status !== 204) {
443
+ throw new DecodeError({ error: decodeResult.error, response, modelName });
444
+ }
445
+ return response;
446
+ });
447
+ }
448
+ static unsafeResponse(networkCall) {
449
+ return wrapNetworkCallSafely(() => networkCall());
450
+ }
451
+ static safeParse(data, Codec) {
452
+ const result = Codec.safeParse(data);
453
+ if (result.success) {
454
+ return result.data;
455
+ }
456
+ return null;
457
+ }
458
+ };
459
+ async function wrapNetworkCallSafely(networkCallFunction) {
460
+ try {
461
+ const response = await networkCallFunction();
462
+ return { response, error: null };
463
+ } catch (error) {
464
+ return { response: null, error };
465
+ }
466
+ }
467
+ var DecodeError = class extends Error {
468
+ constructor({ error, response, modelName }) {
469
+ const msg = `response from url "${response.config.url}" doesn't match model "${modelName}"`;
470
+ super(msg);
471
+ console.error(msg, error);
472
+ }
473
+ };
401
474
 
402
- /*
403
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
404
- * This is licensed software from AccelByte Inc, for limitations
405
- * and restrictions contact your company contract manager.
406
- */
407
- const REFRESH_EXPIRY = 1000;
408
- const REFRESH_EXPIRY_UPDATE_RATE = 500;
409
- const REFRESH_EXPIRY_CHECK_RATE = 1000;
410
- var LoginUrls;
411
- (function (LoginUrls) {
412
- LoginUrls["GRANT_TOKEN"] = "/iam/v3/oauth/token";
413
- LoginUrls["REVOKE"] = "/iam/v3/oauth/revoke";
414
- })(LoginUrls || (LoginUrls = {}));
415
- /* eslint camelcase: 0 */
416
- const refreshSession = ({ axiosConfig, refreshToken, clientId }) => {
417
- const config = {
418
- ...axiosConfig,
419
- // Ideally withCredentials should be `true` to make sure that cookies always included when refreshing token
420
- // especially on cross-origin requests.
421
- // But if refreshToken is provided (e.g. from Launcher), we can set it to false and send refresh_token via payload.
422
- withCredentials: !refreshToken,
423
- headers: {
424
- 'Content-Type': 'application/x-www-form-urlencoded',
425
- Authorization: `Basic ${Buffer.from(`${clientId}:`).toString('base64')}`
426
- }
427
- };
428
- const axios = Network.create(config);
429
- const payload = {
430
- refresh_token: refreshToken || undefined,
431
- client_id: clientId,
432
- grant_type: 'refresh_token'
433
- };
434
- const oauth20 = new OAuth20$(axios, 'NAMESPACE-NOT-REQUIRED');
435
- return oauth20.postOauthToken(payload);
436
- };
437
- // Return Promise<true> if refresh in any tab is successful;
438
- const refreshWithLock = ({ axiosConfig, refreshToken, clientId }) => {
439
- //
440
- if (RefreshSession.isLocked()) {
441
- return Promise.resolve().then(async () => {
442
- // This block is executed when other tab / request is refreshing
443
- while (RefreshSession.isLocked()) {
444
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
445
- }
446
- return {};
447
- });
448
- }
449
- RefreshSession.lock(REFRESH_EXPIRY);
450
- let isLocallyRefreshingToken = true;
451
- (async () => {
452
- // eslint-disable-next-line no-unmodified-loop-condition
453
- while (isLocallyRefreshingToken) {
454
- RefreshSession.lock(REFRESH_EXPIRY);
455
- await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
456
- }
457
- })();
458
- return Promise.resolve()
459
- .then(doRefreshSession({ axiosConfig, clientId, refreshToken }))
460
- .finally(() => {
461
- isLocallyRefreshingToken = false;
462
- RefreshSession.unlock();
463
- });
464
- };
465
- const doRefreshSession = ({ axiosConfig, clientId, refreshToken }) => async () => {
466
- // we need this to check if app use “withCredentials: false” and don’t have refreshToken it should return false,
467
- // because we track it as a logout user, if not do this even user logout on the desktop app (that use withCredentials: false)
468
- // will automatically login with refreshSession
469
- if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
470
- return false;
471
- }
472
- const result = await refreshSession({ axiosConfig, clientId, refreshToken });
473
- if (result.error) {
474
- return false;
475
- }
476
- return result.response.data;
477
- };
478
- const injectAuthInterceptors = (clientId, getSDKConfig, onSessionExpired, onGetUserSession, getRefreshToken) => {
479
- // ===== request
480
- injectRequestInterceptors(async (config) => {
481
- // need to lock on the desktop as well to sleep other request before refresh session is done
482
- const isRefreshTokenUrl = config.url === LoginUrls.GRANT_TOKEN;
483
- // eslint-disable-next-line no-unmodified-loop-condition
484
- while (RefreshSession.isLocked() && !isRefreshTokenUrl) {
485
- await RefreshSession.sleepAsync(200);
486
- }
487
- return config;
488
- }, (error) => {
489
- return Promise.reject(error);
490
- });
491
- // ===== response
492
- injectResponseInterceptors(response => {
493
- const { config, status } = response;
494
- if (config.url === LoginUrls.GRANT_TOKEN && status === 200 && onGetUserSession) {
495
- const { access_token, refresh_token } = response.data;
496
- if (access_token) {
497
- onGetUserSession(access_token, refresh_token ?? '');
498
- }
499
- }
500
- return response;
501
- }, async (error) => {
502
- const { config, response } = error;
503
- if (axios.isCancel(error)) {
504
- // expected case, exit
505
- throw error;
506
- }
507
- if (!response) {
508
- console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config?.baseURL}${config?.url}. ${error.message}\n`);
509
- }
510
- if (response?.status === 401) {
511
- const { url } = config || {};
512
- const axiosConfig = getSDKConfig();
513
- const refreshToken = getRefreshToken ? getRefreshToken() : undefined;
514
- // expected business case, exit
515
- // @ts-ignore
516
- if (Object.values(LoginUrls).includes(url)) {
517
- throw error;
518
- }
519
- // need to lock on the desktop as well to prevent multiple token request
520
- return refreshWithLock({ axiosConfig, clientId, refreshToken }).then(tokenResponse => {
521
- return uponRefreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
522
- });
523
- }
524
- return Promise.reject(error);
525
- });
526
- };
527
- const uponRefreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
528
- //
529
- if (tokenResponse) {
530
- const { access_token } = tokenResponse;
531
- // desktop
532
- if (!axiosConfig.withCredentials && access_token) {
533
- return axios({
534
- ...errorConfig,
535
- headers: {
536
- ...errorConfig.headers,
537
- Authorization: `Bearer ${access_token}`
538
- }
539
- });
540
- // web
541
- }
542
- else {
543
- return axios(errorConfig);
544
- }
545
- }
546
- if (onSessionExpired) {
547
- onSessionExpired();
548
- }
549
- throw error;
475
+ // src/interceptors/AuthInterceptorDeps.ts
476
+ var OAuth20$ = class {
477
+ // @ts-ignore
478
+ constructor(axiosInstance) {
479
+ this.axiosInstance = axiosInstance;
480
+ }
481
+ postOauthToken(data) {
482
+ const params = {};
483
+ const url = "/iam/v3/oauth/token";
484
+ const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
485
+ ...params,
486
+ headers: { ...params.headers, "content-type": "application/x-www-form-urlencoded" }
487
+ });
488
+ return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, "TokenWithDeviceCookieResponseV3");
489
+ }
490
+ };
491
+ var OAuth20V4$ = class {
492
+ // @ts-ignore
493
+ // prettier-ignore
494
+ constructor(axiosInstance) {
495
+ this.axiosInstance = axiosInstance;
496
+ }
497
+ /**
498
+ * This endpoint supports grant type: 1. Grant Type == &lt;code&gt;authorization_code&lt;/code&gt;: It generates the user token by given the authorization code which generated in &#34;/iam/v3/authenticate&#34; API response. It should also pass in the redirect_uri, which should be the same as generating the authorization code request. 2. Grant Type == &lt;code&gt;password&lt;/code&gt;: The grant type to use for authenticating a user, whether it&#39;s by email / username and password combination or through platform. 3. Grant Type == &lt;code&gt;refresh_token&lt;/code&gt;: Used to get a new access token for a valid refresh token. 4. Grant Type == &lt;code&gt;client_credentials&lt;/code&gt;: It generates a token by checking the client credentials provided through Authorization header. 5. Grant Type == &lt;code&gt;urn:ietf:params:oauth:grant-type:extend_client_credentials&lt;/code&gt;: It generates a token by checking the client credentials provided through Authorization header. It only allows publisher/studio namespace client. In generated token: 1. There wil be no roles, namespace_roles &amp; permission. 2. The scope will be fixed as &#39;extend&#39;. 3. There will have a new field &#39;extend_namespace&#39;, the value is from token request body. 6. Grant Type == &lt;code&gt;urn:ietf:params:oauth:grant-type:login_queue_ticket&lt;/code&gt;: It generates a token by validating the login queue ticket against login queue service. ## Access Token Content Following is the access token’s content: - **namespace**. It is the namespace the token was generated from. - **display_name**. The display name of the sub. It is empty if the token is generated from the client credential - **roles**. The sub’s roles. It is empty if the token is generated from the client credential - **namespace_roles**. The sub’s roles scoped to namespace. Improvement from roles, which make the role scoped to specific namespace instead of global to publisher namespace - **permissions**. The sub or aud’ permissions - **bans**. The sub’s list of bans. It is used by the IAM client for validating the token. - **jflgs**. It stands for Justice Flags. It is a special flag used for storing additional status information regarding the sub. It is implemented as a bit mask. Following explains what each bit represents: - 1: Email Address Verified - 2: Phone Number Verified - 4: Anonymous - 8: Suspicious Login - **aud**. The aud is the targeted resource server. - **iat**. The time the token issues at. It is in Epoch time format - **exp**. The time the token expires. It is in Epoch time format - **client_id**. The UserID. The sub is omitted if the token is generated from client credential - **scope**. The scope of the access request, expressed as a list of space-delimited, case-sensitive strings ## Bans The JWT contains user&#39;s active bans with its expiry date. List of ban types can be obtained from /bans. ## Device Cookie Validation _**For grant type &#34;password&#34; only**_ Device Cookie is used to protect the user account from brute force login attack, &lt;a target=&#34;_blank&#34; href=&#34;https://owasp.org/www-community/Slow_Down_Online_Guessing_Attacks_with_Device_Cookies&#34;&gt;more detail from OWASP&lt;a&gt;. This endpoint will read device cookie from request header **Auth-Trust-Id**. If device cookie not found, it will generate a new one and set it into response body **auth_trust_id** when successfully login. ## Track Login History This endpoint will track login history to detect suspicious login activity, please provide **Device-Id** (alphanumeric) in request header parameter otherwise it will set to &#34;unknown&#34;. Align with General Data Protection Regulation in Europe, user login history will be kept within 28 days by default&#34; ## 2FA remember device To remember device for 2FA, should provide cookie: device_token or header: Device-Token ## Response note If it is a user token request and user hasn&#39;t accepted required legal policy, the field &lt;code&gt;is_comply&lt;/code&gt; will be false in response and responsed token will have no permission. action code: 10703
499
+ */
500
+ postOauthToken_v4(data, queryParams) {
501
+ const params = { code_challenge_method: "plain", ...queryParams };
502
+ const url = "/iam/v4/oauth/token";
503
+ const resultPromise = this.axiosInstance.post(url, CodeGenUtil.getFormUrlEncodedData(data), {
504
+ ...params,
505
+ headers: { ...params.headers, "content-type": "application/x-www-form-urlencoded" }
506
+ });
507
+ return Validate.responseType(() => resultPromise, TokenWithDeviceCookieResponseV3, "TokenWithDeviceCookieResponseV3");
508
+ }
550
509
  };
551
510
 
552
- /*
553
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
554
- * This is licensed software from AccelByte Inc, for limitations
555
- * and restrictions contact your company contract manager.
556
- */
557
- class ApiUtils {
558
- }
559
- ApiUtils.mergedConfigs = (config, overrides) => {
560
- return {
561
- ...config,
562
- ...overrides?.config,
563
- headers: {
564
- ...config.headers,
565
- ...overrides?.config?.headers
566
- }
567
- };
568
- };
569
- ApiUtils.is4xxError = (error) => {
570
- if (axios.isAxiosError(error) && error.response) {
571
- return error.response.status >= 400 && error.response.status <= 499;
572
- }
573
- return false;
511
+ // src/interceptors/AuthInterceptors.ts
512
+ var REFRESH_EXPIRY = 1e3;
513
+ var REFRESH_EXPIRY_UPDATE_RATE = 500;
514
+ var REFRESH_EXPIRY_CHECK_RATE = 1e3;
515
+ var GrantTokenUrls = /* @__PURE__ */ ((GrantTokenUrls2) => {
516
+ GrantTokenUrls2["GRANT_TOKEN"] = "/iam/v3/oauth/token";
517
+ GrantTokenUrls2["GRANT_TOKEN_V4"] = "/iam/v4/oauth/token";
518
+ return GrantTokenUrls2;
519
+ })(GrantTokenUrls || {});
520
+ var LoginUrls = /* @__PURE__ */ ((LoginUrls2) => {
521
+ LoginUrls2["REVOKE"] = "/iam/v3/oauth/revoke";
522
+ return LoginUrls2;
523
+ })(LoginUrls || {});
524
+ var noOp = () => {
525
+ };
526
+ var RefreshToken = class {
527
+ constructor({ config, interceptors }) {
528
+ // Return Promise<true> if refresh in any tab is successful;
529
+ this.runWithLock = () => {
530
+ if (RefreshSession.isLocked()) {
531
+ return Promise.resolve().then(async () => {
532
+ while (RefreshSession.isLocked()) {
533
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_CHECK_RATE);
534
+ }
535
+ return {};
536
+ });
537
+ }
538
+ RefreshSession.lock(REFRESH_EXPIRY);
539
+ let isLocallyRefreshingToken = true;
540
+ (async () => {
541
+ while (isLocallyRefreshingToken) {
542
+ RefreshSession.lock(REFRESH_EXPIRY);
543
+ await RefreshSession.sleepAsync(REFRESH_EXPIRY_UPDATE_RATE);
544
+ }
545
+ })();
546
+ return Promise.resolve().then(() => this.run()).finally(() => {
547
+ isLocallyRefreshingToken = false;
548
+ RefreshSession.unlock();
549
+ });
550
+ };
551
+ this.run = async () => {
552
+ const { axiosConfig, refreshToken } = this.config;
553
+ if (DesktopChecker.isDesktopApp() && !axiosConfig.withCredentials && !refreshToken) {
554
+ return false;
555
+ }
556
+ const result = await this.refreshToken();
557
+ if (result.error) {
558
+ return false;
559
+ }
560
+ return result.response.data;
561
+ };
562
+ this.refreshToken = () => {
563
+ const { axiosConfig, refreshToken, clientId, tokenUrl } = this.config;
564
+ const config = {
565
+ ...axiosConfig,
566
+ /**
567
+ * Ideally `withCredentials` should be `true` to make sure that
568
+ * cookies always included when refreshing token
569
+ * especially on cross-origin requests.
570
+ * But if `refreshToken` is provided (e.g. from Launcher),
571
+ * we can set it to false and send refresh_token via payload.
572
+ */
573
+ withCredentials: !refreshToken,
574
+ headers: {
575
+ "Content-Type": "application/x-www-form-urlencoded",
576
+ Authorization: `Basic ${Buffer.from(`${clientId}:`).toString("base64")}`
577
+ }
578
+ };
579
+ const axios4 = Network.create(config);
580
+ for (const interceptor of this.interceptors) {
581
+ if (interceptor.type === "request") {
582
+ axios4.interceptors.request.use(interceptor?.onRequest, interceptor.onError);
583
+ }
584
+ if (interceptor.type === "response") {
585
+ axios4.interceptors.response.use(interceptor?.onSuccess, interceptor.onError);
586
+ }
587
+ }
588
+ const payload = {
589
+ refresh_token: refreshToken || void 0,
590
+ client_id: clientId,
591
+ grant_type: "refresh_token"
592
+ };
593
+ if (tokenUrl === "/iam/v4/oauth/token" /* GRANT_TOKEN_V4 */) {
594
+ return new OAuth20V4$(axios4).postOauthToken_v4(payload);
595
+ }
596
+ const oauth20 = new OAuth20$(axios4);
597
+ return oauth20.postOauthToken(payload);
598
+ };
599
+ this.config = config;
600
+ this.interceptors = interceptors || [];
601
+ }
574
602
  };
603
+ var refreshComplete = (error, tokenResponse, onSessionExpired, axiosConfig, errorConfig) => {
604
+ if (tokenResponse) {
605
+ const { access_token } = tokenResponse;
606
+ if (!axiosConfig.withCredentials && access_token) {
607
+ return axios3({
608
+ ...errorConfig,
609
+ headers: {
610
+ ...errorConfig.headers,
611
+ Authorization: `Bearer ${access_token}`
612
+ }
613
+ });
614
+ } else {
615
+ return axios3(errorConfig);
616
+ }
617
+ }
618
+ if (onSessionExpired) {
619
+ onSessionExpired();
620
+ }
621
+ throw error;
622
+ };
623
+ var createAuthInterceptor = ({
624
+ clientId,
625
+ onSessionExpired,
626
+ onGetUserSession,
627
+ expectedErrorUrls = Object.values({ ...LoginUrls, ...GrantTokenUrls }),
628
+ getRefreshToken,
629
+ tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */
630
+ }) => {
631
+ return {
632
+ type: "response",
633
+ name: "session-expired",
634
+ onError: (e) => {
635
+ const error = e;
636
+ const { config, response } = error;
637
+ if (axios3.isCancel(error)) {
638
+ return Promise.reject(error);
639
+ }
640
+ if (!response) {
641
+ console.warn(`sdk:ERR_INTERNET_DISCONNECTED ${config?.baseURL}${config?.url}. ${error.message}
642
+ `);
643
+ }
644
+ if (response?.status === 401) {
645
+ const { url } = config || {};
646
+ const axiosConfig = config;
647
+ const refreshToken = getRefreshToken?.();
648
+ if (!url || url && expectedErrorUrls.includes(url)) {
649
+ return Promise.reject(error);
650
+ }
651
+ const refresh = new RefreshToken({
652
+ config: { axiosConfig, clientId, refreshToken, tokenUrl },
653
+ interceptors: [
654
+ createRefreshSessionInterceptor({ tokenUrl }),
655
+ createGetSessionInterceptor({ onGetUserSession: onGetUserSession || noOp, tokenUrl })
656
+ ]
657
+ });
658
+ return refresh.runWithLock().then((tokenResponse) => {
659
+ return refreshComplete(error, tokenResponse, onSessionExpired, axiosConfig, config || {});
660
+ });
661
+ }
662
+ return Promise.reject(error);
663
+ }
664
+ };
665
+ };
666
+ var createRefreshSessionInterceptor = (options) => {
667
+ const { tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */ } = options || {};
668
+ return {
669
+ type: "request",
670
+ name: "refresh-session",
671
+ onError: (error) => Promise.reject(error),
672
+ onRequest: async (config) => {
673
+ const isRefreshTokenUrl = config.url === tokenUrl;
674
+ while (RefreshSession.isLocked() && !isRefreshTokenUrl) {
675
+ await RefreshSession.sleepAsync(200);
676
+ }
677
+ return config;
678
+ }
679
+ };
680
+ };
681
+ var createGetSessionInterceptor = ({
682
+ tokenUrl = "/iam/v3/oauth/token" /* GRANT_TOKEN */,
683
+ onGetUserSession
684
+ }) => ({
685
+ type: "response",
686
+ name: "get-session",
687
+ onError: (error) => Promise.reject(error),
688
+ onSuccess: (response) => {
689
+ const { config, status } = response;
690
+ if (config.url === tokenUrl && status === 200) {
691
+ const { access_token, refresh_token } = response.data;
692
+ if (access_token) {
693
+ onGetUserSession(access_token, refresh_token ?? "");
694
+ }
695
+ }
696
+ return response;
697
+ }
698
+ });
575
699
 
576
- /*
577
- * Copyright (c) 2023 AccelByte Inc. All Rights Reserved
578
- * This is licensed software from AccelByte Inc, for limitations
579
- * and restrictions contact your company contract manager.
580
- */
581
- const internalServiceMap = {
582
- '/achievement': 'justice-achievement-service',
583
- '/basic': 'justice-basic-service',
584
- '/buildinfo': 'justice-buildinfo-service',
585
- '/chat': 'justice-chat-service',
586
- '/cloudsave': 'justice-cloudsave-service',
587
- '/content-management': 'justice-odin-content-management-service',
588
- '/differ': 'justice-differ',
589
- '/dsmcontroller': 'justice-dsm-controller-service',
590
- '/event': 'justice-event-log-service',
591
- '/game-telemetry': 'analytics-game-telemetry-api',
592
- '/gdpr': 'justice-gdpr-service',
593
- '/group': 'justice-group-service',
594
- '/iam': 'justice-iam-service',
595
- '/leaderboard': 'justice-leaderboard-service',
596
- '/agreement': 'justice-legal-service',
597
- '/lobby': 'justice-lobby-server',
598
- '/match2': 'justice-matchmaking-v2',
599
- '/matchmaking': 'justice-matchmaking',
600
- '/odin-config': 'justice-odin-config-service',
601
- '/platform': 'justice-platform-service',
602
- '/qosm': 'justice-qos-manager-service',
603
- '/reporting': 'justice-reporting-service',
604
- '/seasonpass': 'justice-seasonpass-service',
605
- '/session': 'justice-session-service',
606
- '/sessionbrowser': 'justice-session-browser-service',
607
- '/social': 'justice-social-service',
608
- '/ugc': 'justice-ugc-service',
609
- '/config': 'justice-config-service'
610
- };
611
- const injectInternalNetworkInterceptors = () => {
612
- injectRequestInterceptors(async (config) => {
613
- const { url } = config;
614
- if (url) {
615
- // url example = "/iam/v1/..."
616
- const firstPath = url.split('/')[1];
617
- const internalServiceName = internalServiceMap[`/${firstPath}`];
618
- if (internalServiceName) {
619
- config.baseURL = `http://${internalServiceName}`;
620
- // final url will be
621
- // http://${service-name}/{url}
622
- }
623
- }
624
- return config;
625
- }, (error) => {
626
- return Promise.reject(error);
627
- });
700
+ // src/constants/paths.ts
701
+ var INTERNAL_SERVICES = {
702
+ "/achievement": "justice-achievement-service",
703
+ "/basic": "justice-basic-service",
704
+ "/buildinfo": "justice-buildinfo-service",
705
+ "/chat": "justice-chat-service",
706
+ "/cloudsave": "justice-cloudsave-service",
707
+ "/content-management": "justice-odin-content-management-service",
708
+ "/differ": "justice-differ",
709
+ "/dsmcontroller": "justice-dsm-controller-service",
710
+ "/event": "justice-event-log-service",
711
+ "/game-telemetry": "analytics-game-telemetry-api",
712
+ "/gdpr": "justice-gdpr-service",
713
+ "/group": "justice-group-service",
714
+ "/iam": "justice-iam-service",
715
+ "/leaderboard": "justice-leaderboard-service",
716
+ "/agreement": "justice-legal-service",
717
+ // sdk-legal
718
+ "/lobby": "justice-lobby-server",
719
+ "/match2": "justice-matchmaking-v2",
720
+ // sdk-matchmaking
721
+ "/matchmaking": "justice-matchmaking",
722
+ // sdk-matchmaking-v1
723
+ "/odin-config": "justice-odin-config-service",
724
+ "/platform": "justice-platform-service",
725
+ "/qosm": "justice-qos-manager-service",
726
+ "/reporting": "justice-reporting-service",
727
+ "/seasonpass": "justice-seasonpass-service",
728
+ "/session": "justice-session-service",
729
+ "/sessionbrowser": "justice-session-browser-service",
730
+ "/social": "justice-social-service",
731
+ "/ugc": "justice-ugc-service",
732
+ "/config": "justice-config-service"
628
733
  };
629
734
 
630
- /*
631
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
632
- * This is licensed software from AccelByte Inc, for limitations
633
- * and restrictions contact your company contract manager.
634
- */
635
- class AccelbyteSDKImpl {
636
- constructor(options, config, events) {
637
- this.getRefreshToken = () => this.refreshToken;
638
- this.getConfig = () => this.config;
639
- this.refreshTokensImpl = (accessToken, refreshToken) => {
640
- if (refreshToken) {
641
- this.refreshToken = refreshToken;
642
- }
643
- const configOverride = { headers: { Authorization: accessToken ? `Bearer ${accessToken}` : '' } };
644
- this.config = ApiUtils.mergedConfigs(this.config, { config: configOverride });
645
- };
646
- this.options = {
647
- ...options
648
- };
649
- this.events = events;
650
- this.config = {
651
- timeout: 60000,
652
- baseURL: options.baseURL,
653
- withCredentials: true,
654
- ...config,
655
- headers: {
656
- 'Content-Type': 'application/json',
657
- ...config?.headers
658
- }
659
- };
660
- // TODO: instead of having a "global" axios interceptors, we can create the instance here.
661
- // ```
662
- // this.axiosInstance = Network.create(...)
663
- // this.axiosInstance.interceptors.use(...)
664
- // ```
665
- // After that, our SDK assembly will return this axiosInstance, which will be used by each of the service SDKs.
666
- // ```
667
- // const { axiosInstance, opts } = sdk.assembly()
668
- // axiosInstance.defaults = {
669
- // ...axiosInstance.defaults,
670
- // ...args.config,
671
- // headers: {
672
- // ...axiosInstance.defaults.headers,
673
- // ...args.config.headers
674
- // }
675
- // }
676
- // ```
677
- // This way, each of the SDK instance will have their own interceptors and will not "pollute"
678
- // the global axios interceptors. It's easier to test in isolation as well, because with the global
679
- // interceptors, we can't isolate test the SDK instance... or maybe we can, with `axios.interceptors.request.clear`,
680
- // but they can't be done in parallel.
681
- }
682
- init() {
683
- const { baseURL, clientId, customInterceptors, useInternalNetwork } = this.options;
684
- if (customInterceptors) {
685
- injectRequestInterceptors(customInterceptors.request, customInterceptors.error);
686
- injectResponseInterceptors(customInterceptors.response, customInterceptors.error);
687
- }
688
- else {
689
- // Default interceptors.
690
- if (useInternalNetwork) {
691
- injectInternalNetworkInterceptors();
692
- }
693
- injectAuthInterceptors(clientId, this.getConfig, this.events?.onSessionExpired, this.events?.onGetUserSession, this.getRefreshToken);
694
- injectErrorInterceptors({
695
- baseUrl: baseURL,
696
- onError: this.events?.onError,
697
- onUserEligibilityChange: this.events?.onUserEligibilityChange,
698
- onTooManyRequest: this.events?.onTooManyRequest
699
- });
700
- }
701
- // TODO reintegrate doVersionDiagnostics later on
702
- // setTimeout(() => this.doVersionDiagnostics(), TIMEOUT_TO_DIAGNOSTICS)
703
- return {
704
- refreshTokens: (accessToken, refreshToken) => this.refreshTokensImpl(accessToken, refreshToken),
705
- assembly: () => {
706
- return {
707
- config: this.config,
708
- namespace: this.options.namespace,
709
- clientId: this.options.clientId,
710
- redirectURI: this.options.redirectURI,
711
- baseURL: this.options.baseURL,
712
- refreshToken: this.refreshToken,
713
- useSchemaValidation: this.options.useSchemaValidation !== undefined ? this.options.useSchemaValidation : true
714
- };
715
- }
716
- };
717
- }
718
- }
719
- const sdkInit = ({ options, config, onEvents }) => {
720
- const sdkFactory = new AccelbyteSDKImpl(options, config, onEvents);
721
- return sdkFactory.init();
722
- };
723
- // ts-prune-ignore-next
724
- const Accelbyte = { SDK: sdkInit };
735
+ // src/interceptors/CustomPathInterceptor.ts
736
+ var createCustomPathInterceptor = ({ basePath, isInternalNetwork }) => {
737
+ return {
738
+ type: "request",
739
+ name: "custom-base-path",
740
+ onRequest: async (config) => {
741
+ const { url } = config;
742
+ if (url) {
743
+ const firstPath = url.split("/")[1];
744
+ const servicePath = `/${firstPath}`;
745
+ const newBasePath = basePath?.[servicePath];
746
+ const internalPath = INTERNAL_SERVICES?.[servicePath];
747
+ if (isInternalNetwork && internalPath) {
748
+ config.baseURL = `http://${internalPath}`;
749
+ }
750
+ if (newBasePath) {
751
+ config.url = config.url?.replace(servicePath, newBasePath);
752
+ }
753
+ }
754
+ return config;
755
+ },
756
+ onError: (error) => Promise.reject(error)
757
+ };
758
+ };
725
759
 
726
- /*
727
- * Copyright (c) 2024 AccelByte Inc. All Rights Reserved
728
- * This is licensed software from AccelByte Inc, for limitations
729
- * and restrictions contact your company contract manager.
730
- */
731
- // More detail: https://github.com/AccelByte/go-restful-plugins/blob/master/pkg/auth/iam/event.go
732
- var IamErrorCode;
733
- (function (IamErrorCode) {
734
- IamErrorCode[IamErrorCode["InternalServerError"] = 20000] = "InternalServerError";
735
- IamErrorCode[IamErrorCode["UnauthorizedAccess"] = 20001] = "UnauthorizedAccess";
736
- IamErrorCode[IamErrorCode["ValidationError"] = 20002] = "ValidationError";
737
- IamErrorCode[IamErrorCode["ForbiddenAccess"] = 20003] = "ForbiddenAccess";
738
- IamErrorCode[IamErrorCode["TooManyRequests"] = 20007] = "TooManyRequests";
739
- IamErrorCode[IamErrorCode["UserNotFound"] = 20008] = "UserNotFound";
740
- IamErrorCode[IamErrorCode["TokenIsExpired"] = 20011] = "TokenIsExpired";
741
- IamErrorCode[IamErrorCode["InsufficientPermissions"] = 20013] = "InsufficientPermissions";
742
- IamErrorCode[IamErrorCode["InvalidAudience"] = 20014] = "InvalidAudience";
743
- IamErrorCode[IamErrorCode["InsufficientScope"] = 20015] = "InsufficientScope";
744
- IamErrorCode[IamErrorCode["UnableToParseRequestBody"] = 20019] = "UnableToParseRequestBody";
745
- IamErrorCode[IamErrorCode["InvalidPaginationParameters"] = 20021] = "InvalidPaginationParameters";
746
- IamErrorCode[IamErrorCode["TokenIsNotUserToken"] = 20022] = "TokenIsNotUserToken";
747
- IamErrorCode[IamErrorCode["InvalidRefererHeader"] = 20023] = "InvalidRefererHeader";
748
- IamErrorCode[IamErrorCode["SubdomainMismatch"] = 20030] = "SubdomainMismatch";
749
- })(IamErrorCode || (IamErrorCode = {}));
760
+ // src/interceptors/ErrorInterceptor.ts
761
+ var ERROR_ELIGIBILITY_CODE = 13130;
762
+ var ErrorInterceptors = [
763
+ {
764
+ type: "response",
765
+ name: "user-eligibilitiy-change",
766
+ onError: (e) => {
767
+ const error = e;
768
+ if (error.response) {
769
+ const { response } = error;
770
+ if (response?.status === 403 && (response?.config).url.includes(process.env.BASE_URL) && response?.config.withCredentials) {
771
+ if (response.data.errorCode === ERROR_ELIGIBILITY_CODE) {
772
+ }
773
+ }
774
+ }
775
+ return Promise.reject(error);
776
+ }
777
+ },
778
+ {
779
+ type: "response",
780
+ name: "too-many-request",
781
+ onError: (e) => {
782
+ const error = e;
783
+ if (error.response) {
784
+ const { response } = error;
785
+ if (response?.status === 429) {
786
+ }
787
+ }
788
+ return Promise.reject(error);
789
+ }
790
+ }
791
+ ];
750
792
 
751
- /*
752
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
753
- * This is licensed software from AccelByte Inc, for limitations
754
- * and restrictions contact your company contract manager.
755
- */
756
- const ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT = 10200;
757
- const ERROR_CODE_LINK_DELETION_ACCOUNT = 10135;
758
- const ERROR_CODE_TOKEN_EXPIRED = 10196;
759
- const ERROR_USER_BANNED = 10134;
793
+ // src/utils/Type.ts
794
+ function isType(schema, data) {
795
+ return schema.safeParse(data).success;
796
+ }
760
797
 
761
- /*
762
- * Copyright (c) 2022-2024 AccelByte Inc. All Rights Reserved
763
- * This is licensed software from AccelByte Inc, for limitations
764
- * and restrictions contact your company contract manager.
765
- */
766
- class UrlHelper {
767
- static trimSlashFromStringEnd(pathString) {
768
- let newString = pathString;
769
- while (newString[newString.length - 1] === '/') {
770
- newString = newString.slice(0, -1);
771
- }
772
- return newString;
773
- }
774
- static trimSlashFromStringStart(pathString) {
775
- let newString = pathString;
776
- while (newString[0] === '/') {
777
- newString = newString.slice(1);
778
- }
779
- return newString;
780
- }
781
- static trimSlashFromStringEdges(pathString) {
782
- return UrlHelper.trimSlashFromStringStart(this.trimSlashFromStringEnd(pathString));
783
- }
784
- static combinePaths(...paths) {
785
- const completePath = paths.join('/');
786
- // Replace 2 or more consecutive slashes with a single slash.
787
- // This is also the behavior from Node's `path.join`.
788
- return completePath.replace(/\/{2,}/g, '/');
789
- }
790
- static combineURLPaths(urlString, ...paths) {
791
- const url = new URL(urlString);
792
- const { origin } = url;
793
- const pathname = UrlHelper.trimSlashFromStringEdges(UrlHelper.combinePaths(url.pathname, ...paths));
794
- return new URL(pathname, origin).toString();
795
- }
796
- static removeQueryParam(fullUrlString, param) {
797
- const url = new URL(fullUrlString);
798
- const params = url.searchParams;
799
- const pathname = this.trimSlashFromStringEnd(url.pathname);
800
- // Remove the query parameter
801
- params.delete(param);
802
- // Preserving other URL attributes
803
- let newUrlString;
804
- if (params.toString() === '')
805
- newUrlString = `${url.origin}${pathname}${url.hash}`;
806
- else
807
- newUrlString = `${url.origin}${pathname}?${params.toString()}${url.hash}`;
808
- return newUrlString;
809
- }
810
- }
811
- UrlHelper.isCompleteURLString = (urlString) => {
812
- try {
813
- const url = new URL(urlString);
814
- return url.hostname !== '';
815
- }
816
- catch (error) { }
817
- return false;
798
+ // src/utils/UrlHelper.ts
799
+ var _UrlHelper = class _UrlHelper {
800
+ static trimSlashFromStringEnd(pathString) {
801
+ let newString = pathString;
802
+ while (newString[newString.length - 1] === "/") {
803
+ newString = newString.slice(0, -1);
804
+ }
805
+ return newString;
806
+ }
807
+ static trimSlashFromStringStart(pathString) {
808
+ let newString = pathString;
809
+ while (newString[0] === "/") {
810
+ newString = newString.slice(1);
811
+ }
812
+ return newString;
813
+ }
814
+ static trimSlashFromStringEdges(pathString) {
815
+ return _UrlHelper.trimSlashFromStringStart(this.trimSlashFromStringEnd(pathString));
816
+ }
817
+ static combinePaths(...paths) {
818
+ const completePath = paths.join("/");
819
+ return completePath.replace(/\/{2,}/g, "/");
820
+ }
821
+ static combineURLPaths(urlString, ...paths) {
822
+ const url = new URL(urlString);
823
+ const { origin } = url;
824
+ const pathname = _UrlHelper.trimSlashFromStringEdges(_UrlHelper.combinePaths(url.pathname, ...paths));
825
+ return new URL(pathname, origin).toString();
826
+ }
827
+ static removeQueryParam(fullUrlString, param) {
828
+ const url = new URL(fullUrlString);
829
+ const params = url.searchParams;
830
+ const pathname = this.trimSlashFromStringEnd(url.pathname);
831
+ params.delete(param);
832
+ let newUrlString;
833
+ if (params.toString() === "") newUrlString = `${url.origin}${pathname}${url.hash}`;
834
+ else newUrlString = `${url.origin}${pathname}?${params.toString()}${url.hash}`;
835
+ return newUrlString;
836
+ }
818
837
  };
819
-
820
- export { Accelbyte, ApiUtils, BrowserHelper, CodeGenUtil, DecodeError, DesktopChecker, ERROR_CODE_LINK_DELETION_ACCOUNT, ERROR_CODE_TOKEN_EXPIRED, ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT, ERROR_USER_BANNED, IamErrorCode, Network, RefreshSession, SdkDevice, UrlHelper, Validate, doRefreshSession, injectAuthInterceptors, injectErrorInterceptors, injectRequestInterceptors, injectResponseInterceptors, refreshWithLock };
821
- //# sourceMappingURL=index.browser.js.map
838
+ _UrlHelper.isCompleteURLString = (urlString) => {
839
+ try {
840
+ const url = new URL(urlString);
841
+ return url.hostname !== "";
842
+ } catch (error) {
843
+ }
844
+ return false;
845
+ };
846
+ var UrlHelper = _UrlHelper;
847
+ export {
848
+ AccelByte,
849
+ AccelByteSDK,
850
+ ApiUtils,
851
+ BrowserHelper,
852
+ CodeGenUtil,
853
+ DecodeError,
854
+ DesktopChecker,
855
+ ERROR_CODE_LINK_DELETION_ACCOUNT,
856
+ ERROR_CODE_TOKEN_EXPIRED,
857
+ ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT,
858
+ ERROR_USER_BANNED,
859
+ ErrorInterceptors,
860
+ IamErrorCode,
861
+ Network,
862
+ RefreshSession,
863
+ RefreshToken,
864
+ SdkDevice,
865
+ UrlHelper,
866
+ Validate,
867
+ createAuthInterceptor,
868
+ createCustomPathInterceptor,
869
+ createGetSessionInterceptor,
870
+ createRefreshSessionInterceptor,
871
+ isType
872
+ };
873
+ //# sourceMappingURL=index.browser.js.map