@accelbyte/sdk 3.0.7 → 4.0.0

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