@opexa/portal-sdk 0.34.6 → 0.35.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.
package/dist/index.d.cts CHANGED
@@ -34,6 +34,14 @@ type OperationResult<Error extends string = never, Data = never> = [Data] extend
34
34
  error?: never;
35
35
  };
36
36
 
37
+ type ModifiableKey = 'mode' | 'cache' | 'signal' | 'headers' | 'integrity' | 'keepalive' | 'credentials';
38
+ type Modifiable = {
39
+ [K in ModifiableKey]: Request[K];
40
+ };
41
+ interface ModifiedRequest extends Readonly<Omit<Request, ModifiableKey>>, Modifiable {
42
+ }
43
+ type GraphQLClientMiddleware = (request: ModifiedRequest) => ModifiedRequest | Promise<ModifiedRequest>;
44
+
37
45
  interface ObjectIdFilterField {
38
46
  equal?: string;
39
47
  notEqual?: string;
@@ -1478,6 +1486,8 @@ interface SdkConfig {
1478
1486
  sitePlatform: string;
1479
1487
  platform: string;
1480
1488
  logs?: boolean;
1489
+ sessionStorage?: 'cookie' | 'localStorage';
1490
+ middleware?: GraphQLClientMiddleware;
1481
1491
  }
1482
1492
  declare class Sdk {
1483
1493
  private cmsPortalService;
@@ -1497,6 +1507,9 @@ declare class Sdk {
1497
1507
  private cache;
1498
1508
  private config;
1499
1509
  constructor(config: SdkConfig);
1510
+ private _middleware;
1511
+ set middleware(value: GraphQLClientMiddleware);
1512
+ get middleware(): GraphQLClientMiddleware;
1500
1513
  set adClickId(value: string | null);
1501
1514
  get adClickId(): string | null;
1502
1515
  private get locale();
package/dist/index.d.ts CHANGED
@@ -34,6 +34,14 @@ type OperationResult<Error extends string = never, Data = never> = [Data] extend
34
34
  error?: never;
35
35
  };
36
36
 
37
+ type ModifiableKey = 'mode' | 'cache' | 'signal' | 'headers' | 'integrity' | 'keepalive' | 'credentials';
38
+ type Modifiable = {
39
+ [K in ModifiableKey]: Request[K];
40
+ };
41
+ interface ModifiedRequest extends Readonly<Omit<Request, ModifiableKey>>, Modifiable {
42
+ }
43
+ type GraphQLClientMiddleware = (request: ModifiedRequest) => ModifiedRequest | Promise<ModifiedRequest>;
44
+
37
45
  interface ObjectIdFilterField {
38
46
  equal?: string;
39
47
  notEqual?: string;
@@ -1478,6 +1486,8 @@ interface SdkConfig {
1478
1486
  sitePlatform: string;
1479
1487
  platform: string;
1480
1488
  logs?: boolean;
1489
+ sessionStorage?: 'cookie' | 'localStorage';
1490
+ middleware?: GraphQLClientMiddleware;
1481
1491
  }
1482
1492
  declare class Sdk {
1483
1493
  private cmsPortalService;
@@ -1497,6 +1507,9 @@ declare class Sdk {
1497
1507
  private cache;
1498
1508
  private config;
1499
1509
  constructor(config: SdkConfig);
1510
+ private _middleware;
1511
+ set middleware(value: GraphQLClientMiddleware);
1512
+ get middleware(): GraphQLClientMiddleware;
1500
1513
  set adClickId(value: string | null);
1501
1514
  get adClickId(): string | null;
1502
1515
  private get locale();
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ObjectId } from '@opexa/object-id';
2
2
  export { ObjectId } from '@opexa/object-id';
3
+ import cookies from 'js-cookie';
3
4
 
4
5
  // src/sdk/object-id.ts
5
6
 
@@ -3974,16 +3975,17 @@ function arrayToObject(array) {
3974
3975
  // src/utils/graphql-client.ts
3975
3976
  var GraphQLClient = class {
3976
3977
  url;
3977
- options;
3978
- middlewares;
3978
+ config;
3979
3979
  constructor(url, config) {
3980
- const headers = new Headers(config?.fetchOptions?.headers);
3981
3980
  this.url = url;
3982
- this.options = { ...config?.fetchOptions, headers };
3983
- this.middlewares = config?.middlewares ?? [];
3981
+ this.config = config ?? (() => ({}));
3984
3982
  }
3985
3983
  async request(query, variables, options) {
3986
- const opts = mergeFetchOptions(this.options, options);
3984
+ const cfg = this.config();
3985
+ const opts = mergeFetchOptions(
3986
+ { ...cfg?.fetchOptions, headers: new Headers(cfg?.fetchOptions?.headers) },
3987
+ options
3988
+ );
3987
3989
  const body = JSON.stringify({
3988
3990
  query,
3989
3991
  variables
@@ -4002,13 +4004,18 @@ var GraphQLClient = class {
4002
4004
  body,
4003
4005
  headers,
4004
4006
  method: "POST"
4005
- })
4007
+ }),
4008
+ cfg?.middlewares ?? []
4006
4009
  );
4007
4010
  return await this.exec(req);
4008
4011
  }
4009
4012
  /** Single file upload */
4010
4013
  async upload(query, variables, options) {
4011
- const opts = mergeFetchOptions(this.options, options);
4014
+ const cfg = this.config();
4015
+ const opts = mergeFetchOptions(
4016
+ { ...cfg?.fetchOptions, headers: new Headers(cfg?.fetchOptions?.headers) },
4017
+ options
4018
+ );
4012
4019
  const body = this.createUploadBody(query, variables);
4013
4020
  const headers = new Headers(opts.headers);
4014
4021
  headers.delete("Content-Type");
@@ -4023,7 +4030,8 @@ var GraphQLClient = class {
4023
4030
  body,
4024
4031
  headers,
4025
4032
  method: "POST"
4026
- })
4033
+ }),
4034
+ cfg?.middlewares ?? []
4027
4035
  );
4028
4036
  return await this.exec(req);
4029
4037
  }
@@ -4062,9 +4070,9 @@ var GraphQLClient = class {
4062
4070
  };
4063
4071
  }
4064
4072
  }
4065
- async runMiddlewares(req) {
4073
+ async runMiddlewares(req, middlewares) {
4066
4074
  let result = req.clone();
4067
- for (const middleware of this.middlewares) {
4075
+ for (const middleware of middlewares) {
4068
4076
  result = await middleware(result);
4069
4077
  }
4070
4078
  return result;
@@ -4293,6 +4301,309 @@ function pollable(func, config) {
4293
4301
  };
4294
4302
  }
4295
4303
 
4304
+ // src/sdk/session-manager-cookie.ts
4305
+ var SessionManagerCookie = class {
4306
+ logger;
4307
+ storageKey = "session";
4308
+ platformStorageKey = "session/platform";
4309
+ authService;
4310
+ walletService;
4311
+ _refreshing = false;
4312
+ constructor(config) {
4313
+ this.authService = config.authService;
4314
+ this.walletService = config.walletService;
4315
+ this.logger = config.logger;
4316
+ }
4317
+ get refreshing() {
4318
+ return this._refreshing;
4319
+ }
4320
+ set refreshing(value) {
4321
+ this._refreshing = value;
4322
+ }
4323
+ async create(input) {
4324
+ if (input.type === "MAYA") {
4325
+ localStorage.setItem(this.platformStorageKey, "MAYA");
4326
+ const f0 = () => this.walletService.mayaSession({ id: input.sessionId });
4327
+ const r0 = await pollable(f0, {
4328
+ until: (r) => r.ok && r.data?.member != null,
4329
+ interval: 1e3,
4330
+ maxAttempt: 5
4331
+ })();
4332
+ if (!r0.ok) return r0;
4333
+ if (!r0.data?.member) {
4334
+ return {
4335
+ ok: false,
4336
+ error: {
4337
+ name: "HttpForbidden",
4338
+ message: "Forbidden"
4339
+ }
4340
+ };
4341
+ }
4342
+ const f1 = () => this.authService.createSession(input);
4343
+ const r1 = await pollable(f1, {
4344
+ until: (r) => r.ok,
4345
+ interval: 1e3,
4346
+ maxAttempt: 5
4347
+ })();
4348
+ if (!r1.ok) return r1;
4349
+ const now2 = /* @__PURE__ */ new Date();
4350
+ cookies.set(
4351
+ this.storageKey,
4352
+ JSON.stringify({
4353
+ ...r1.data,
4354
+ accessTokenExpiresAt: addMinutes(now2, 8).getTime(),
4355
+ refreshTokenExpiresAt: subMinutes(addDays(now2, 30), 2).getTime()
4356
+ }),
4357
+ { expires: subMinutes(addDays(now2, 30), 2).getTime() }
4358
+ );
4359
+ return {
4360
+ ok: true,
4361
+ data: null
4362
+ };
4363
+ }
4364
+ if (input.type === "MOBILE_NUMBER") {
4365
+ const res2 = await this.authService.createSession(input);
4366
+ if (res2.ok) {
4367
+ const now2 = /* @__PURE__ */ new Date();
4368
+ cookies.set(
4369
+ this.storageKey,
4370
+ JSON.stringify({
4371
+ ...res2.data,
4372
+ accessTokenExpiresAt: addMinutes(now2, 8).getTime(),
4373
+ refreshTokenExpiresAt: subMinutes(addDays(now2, 30), 2).getTime()
4374
+ }),
4375
+ {
4376
+ expires: subMinutes(addDays(now2, 30), 2).getTime()
4377
+ }
4378
+ );
4379
+ return {
4380
+ ok: true,
4381
+ data: null
4382
+ };
4383
+ }
4384
+ return res2;
4385
+ }
4386
+ if (input.type === "SOCIALS" || input.type === "TOKEN") {
4387
+ const res2 = await this.authService.createSession({
4388
+ type: "SOCIALS",
4389
+ token: input.token
4390
+ });
4391
+ if (res2.ok) {
4392
+ const now2 = /* @__PURE__ */ new Date();
4393
+ cookies.set(
4394
+ this.storageKey,
4395
+ JSON.stringify({
4396
+ ...res2.data,
4397
+ accessTokenExpiresAt: addMinutes(now2, 8).getTime(),
4398
+ refreshTokenExpiresAt: subMinutes(addDays(now2, 30), 2).getTime()
4399
+ }),
4400
+ { expires: subMinutes(addDays(now2, 30), 2).getTime() }
4401
+ );
4402
+ return {
4403
+ ok: true,
4404
+ data: null
4405
+ };
4406
+ }
4407
+ return res2;
4408
+ }
4409
+ if (input.type === "CABINET") {
4410
+ localStorage.setItem(this.platformStorageKey, "CABINET");
4411
+ const res2 = await this.authService.createSession(input);
4412
+ if (res2.ok) {
4413
+ const now2 = /* @__PURE__ */ new Date();
4414
+ cookies.set(
4415
+ this.storageKey,
4416
+ JSON.stringify({
4417
+ ...res2.data,
4418
+ accessTokenExpiresAt: addMinutes(now2, 8).getTime(),
4419
+ refreshTokenExpiresAt: subMinutes(addDays(now2, 30), 2).getTime()
4420
+ }),
4421
+ { expires: subMinutes(addDays(now2, 30), 2).getTime() }
4422
+ );
4423
+ return {
4424
+ ok: true,
4425
+ data: null
4426
+ };
4427
+ }
4428
+ return res2;
4429
+ }
4430
+ const res = await this.authService.createSession(input);
4431
+ if (!res.ok) return res;
4432
+ if (res.data.authenticator) {
4433
+ return {
4434
+ ok: true,
4435
+ data: {
4436
+ authenticator: res.data.authenticator
4437
+ }
4438
+ };
4439
+ }
4440
+ const now = /* @__PURE__ */ new Date();
4441
+ cookies.set(
4442
+ this.storageKey,
4443
+ JSON.stringify({
4444
+ ...res.data,
4445
+ accessTokenExpiresAt: addMinutes(now, 8).getTime(),
4446
+ refreshTokenExpiresAt: subMinutes(addDays(now, 30), 2).getTime()
4447
+ }),
4448
+ {}
4449
+ );
4450
+ return {
4451
+ ok: true,
4452
+ data: null
4453
+ };
4454
+ }
4455
+ async createFromAuthenticator(input) {
4456
+ const res = await this.authService.authenticate(input);
4457
+ if (res.ok) {
4458
+ const now = /* @__PURE__ */ new Date();
4459
+ if (this.isServer) {
4460
+ this.logger.warn("'client cookies' is not available on the server.");
4461
+ } else {
4462
+ cookies.set(
4463
+ this.storageKey,
4464
+ JSON.stringify({
4465
+ ...res.data,
4466
+ accessTokenExpiresAt: addMinutes(now, 8).getTime(),
4467
+ refreshTokenExpiresAt: subMinutes(addDays(now, 30), 2).getTime()
4468
+ }),
4469
+ {
4470
+ expires: subMinutes(addDays(now, 30), 2).getTime()
4471
+ }
4472
+ );
4473
+ }
4474
+ return { ok: true };
4475
+ } else {
4476
+ return res;
4477
+ }
4478
+ }
4479
+ async get() {
4480
+ if (this.isServer) {
4481
+ this.logger.warn("'client cookies' is not available on the server.");
4482
+ return {
4483
+ ok: true,
4484
+ data: null
4485
+ };
4486
+ }
4487
+ if (this.refreshing) {
4488
+ await sleep(1e3);
4489
+ return await this.get();
4490
+ }
4491
+ const val = cookies.get(this.storageKey);
4492
+ if (!val) {
4493
+ return {
4494
+ ok: true,
4495
+ data: null
4496
+ };
4497
+ }
4498
+ try {
4499
+ let obj = JSON.parse(val);
4500
+ let now = /* @__PURE__ */ new Date();
4501
+ const accessTokenExpiresAt = new Date(obj.accessTokenExpiresAt);
4502
+ const refreshTokenExpiresAt = new Date(obj.refreshTokenExpiresAt);
4503
+ if (isAfter(now, refreshTokenExpiresAt)) {
4504
+ this.logger.warn("Session expired. Logging out..");
4505
+ cookies.remove(this.storageKey);
4506
+ return {
4507
+ ok: false,
4508
+ error: {
4509
+ name: "SessionExpiredError",
4510
+ message: "Session expired."
4511
+ }
4512
+ };
4513
+ }
4514
+ if (isAfter(now, accessTokenExpiresAt)) {
4515
+ this.logger.info("Refreshing session...");
4516
+ this.refreshing = true;
4517
+ const res = await this.authService.refreshSession(obj.refreshToken);
4518
+ this.refreshing = false;
4519
+ if (!res.ok) {
4520
+ this.logger.error(`Failed to refresh session: ${res.error.message}`);
4521
+ if (res.error.name === "InvalidTokenError" || res.error.name === "AccountBlacklistedError") {
4522
+ cookies.remove(this.storageKey);
4523
+ return {
4524
+ ok: false,
4525
+ error: res.error
4526
+ };
4527
+ } else {
4528
+ this.logger.warn("Old session returned.");
4529
+ return {
4530
+ ok: true,
4531
+ data: obj
4532
+ };
4533
+ }
4534
+ }
4535
+ this.logger.success("Session refreshed!");
4536
+ now = /* @__PURE__ */ new Date();
4537
+ obj = {
4538
+ ...obj,
4539
+ ...res.data,
4540
+ accessTokenExpiresAt: addMinutes(now, 8).getTime(),
4541
+ refreshTokenExpiresAt: subMinutes(addDays(now, 30), 2).getTime()
4542
+ };
4543
+ cookies.set(this.storageKey, JSON.stringify(obj), {
4544
+ expires: subMinutes(addDays(now, 30), 2).getTime()
4545
+ });
4546
+ }
4547
+ return {
4548
+ ok: true,
4549
+ data: obj
4550
+ };
4551
+ } catch {
4552
+ return {
4553
+ ok: false,
4554
+ error: {
4555
+ name: "UnknownError",
4556
+ message: "Something went wrong."
4557
+ }
4558
+ };
4559
+ }
4560
+ }
4561
+ async destroy() {
4562
+ if (this.isServer) {
4563
+ this.logger.warn("'client cookies' is not available on the server.");
4564
+ return;
4565
+ }
4566
+ const res = await this.get();
4567
+ if (res.data?.accessToken) {
4568
+ await this.authService.destroySession(res.data.accessToken);
4569
+ }
4570
+ cookies.remove(this.storageKey);
4571
+ }
4572
+ async verify() {
4573
+ if (this.isServer) {
4574
+ this.logger.warn("'client cookies' is not available on the server.");
4575
+ return true;
4576
+ }
4577
+ const s = await this.get();
4578
+ if (s.error?.name === "InvalidTokenError") return false;
4579
+ if (s.error?.name === "SessionExpiredError") return false;
4580
+ if (s.error?.name === "AccountBlacklistedError") return false;
4581
+ if (!s.data) return true;
4582
+ const v = await this.authService.verifySession(s.data.accessToken);
4583
+ if (!v) {
4584
+ cookies.remove(this.storageKey);
4585
+ }
4586
+ return v;
4587
+ }
4588
+ get onMaya() {
4589
+ if (this.isServer) {
4590
+ this.logger.warn("'client cookies' is not available on the server.");
4591
+ return false;
4592
+ }
4593
+ return localStorage.getItem(this.platformStorageKey) === "MAYA";
4594
+ }
4595
+ get onCabinet() {
4596
+ if (this.isServer) {
4597
+ this.logger.warn("'localStorage' is not available on the server.");
4598
+ return false;
4599
+ }
4600
+ return localStorage.getItem(this.platformStorageKey) === "CABINET";
4601
+ }
4602
+ get isServer() {
4603
+ return typeof window === "undefined";
4604
+ }
4605
+ };
4606
+
4296
4607
  // src/sdk/session-manager.ts
4297
4608
  var SessionManager = class {
4298
4609
  logger;
@@ -5587,12 +5898,14 @@ var Sdk = class {
5587
5898
  site,
5588
5899
  platform: sitePlatform
5589
5900
  });
5590
- const graphqlClientConfig = {
5901
+ this._middleware = config.middleware ?? ((req) => req);
5902
+ const graphqlClientConfig = () => ({
5591
5903
  middlewares: [
5592
5904
  /**/
5593
5905
  this.authMiddleware,
5594
5906
  this.domainMiddleware,
5595
- this.miscMiddleware
5907
+ this.miscMiddleware,
5908
+ this.middleware
5596
5909
  ],
5597
5910
  fetchOptions: {
5598
5911
  headers: {
@@ -5600,7 +5913,7 @@ var Sdk = class {
5600
5913
  "Platform-Code": platform
5601
5914
  }
5602
5915
  }
5603
- };
5916
+ });
5604
5917
  const gameService = new GameService(new GraphQLClient(gameUrl, graphqlClientConfig));
5605
5918
  const fileService = new FileService(new GraphQLClient(fileUrl, graphqlClientConfig));
5606
5919
  const walletService = new WalletService(new GraphQLClient(walletUrl, graphqlClientConfig));
@@ -5620,7 +5933,11 @@ var Sdk = class {
5620
5933
  }
5621
5934
  }
5622
5935
  });
5623
- const sessionManager = new SessionManager({
5936
+ const sessionManager = config.sessionStorage === "cookie" ? new SessionManagerCookie({
5937
+ logger,
5938
+ authService,
5939
+ walletService
5940
+ }) : new SessionManager({
5624
5941
  logger,
5625
5942
  authService,
5626
5943
  walletService
@@ -5648,6 +5965,13 @@ var Sdk = class {
5648
5965
  logs
5649
5966
  };
5650
5967
  }
5968
+ _middleware;
5969
+ set middleware(value) {
5970
+ this._middleware = value;
5971
+ }
5972
+ get middleware() {
5973
+ return this._middleware;
5974
+ }
5651
5975
  /*
5652
5976
  *=============================================
5653
5977
  * ADS