-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
2357 lines (2323 loc) · 91.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright(c) 2023 SendBird, Inc.
SendBird Desk JavaScript SDK v1.1.0 */
import { DeviceOsPlatform, SendbirdProduct, SendbirdPlatform } from '@sendbird/chat';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var version = "1.1.0";
var _debug = false;
var _sendbird;
var _platform = DeviceOsPlatform.WEB;
var _deskApiHost;
var DESK_SDK_VERSION = version;
var MIN_SENDBIRD_VERSION = '4.9.6';
/**
* @since 1.0.0
* @ignore
*/
var Config = /** @class */ (function () {
function Config() {
}
Object.defineProperty(Config, "sendbird", {
/**
* @static
* @since 1.0.5
* @ignore
* @desc Get Sendbird instance.
*/
get: function () {
return _sendbird;
},
/**
* @static
* @since 1.0.5
* @ignore
* @desc Set Sendbird instance.
*/
set: function (sb) {
_sendbird = sb;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Config, "platform", {
/**
* @static
* @since 1.1.0
* @ignore
* @desc Get platform for setting in SendbirdInstance.
* @default DeviceOsPlatform.WEB
*/
get: function () {
return _platform;
},
/**
* @static
* @since 1.1.0
* @ignore
* @desc Set platform for setting in SendbirdInstance.
*/
set: function (platform) {
_platform = platform;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Config, "isDebugMode", {
/**
* @static
* @since 1.0.0
* @ignore
* @desc Check if SDK is in debug mode.
*/
get: function () {
return _debug;
},
enumerable: false,
configurable: true
});
/**
* @static
* @since 1.0.0
* @ignore
* @desc Set SDK to debug mode which leads to change API endpoint and app ID into development server.
*/
Config.setDebugMode = function () {
_debug = true;
};
/**
* @static
* @since 1.0.0
* @ignore
* @desc Set SDK to production mode which leads to change API endpoint and app ID into production server.
*/
Config.unsetDebugMode = function () {
_debug = false;
};
Object.defineProperty(Config, "apiHost", {
/**
* @ignore
*/
get: function () {
if (!_deskApiHost) {
var sb = _sendbird;
_deskApiHost = "https://desk-api-".concat(sb.appId, ".sendbird.com/sapi");
}
return _deskApiHost;
},
/**
* @ignore
*/
set: function (val) {
_deskApiHost = val;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Config, "sdkVersion", {
/**
* @ignore
*/
get: function () {
return DESK_SDK_VERSION;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Config, "minSendbirdVersion", {
/**
* @ignore
*/
get: function () {
return MIN_SENDBIRD_VERSION;
},
enumerable: false,
configurable: true
});
/**
* @static
* @since 1.0.0
* @ignore
* @desc Check if Sendbird SDK version meets the min supported version.
* @returns {boolean} - true if it's compatible.
*/
Config.isSendbirdSdkCompatible = function (version) {
var _minSupportedVersion = MIN_SENDBIRD_VERSION.split('.');
var _targetVersion = version.split('.');
if (_minSupportedVersion.length === _targetVersion.length) {
for (var i in _minSupportedVersion) {
if (parseInt(_minSupportedVersion[i]) < parseInt(_targetVersion[i])) {
return true;
}
else if (parseInt(_minSupportedVersion[i]) > parseInt(_targetVersion[i])) {
return false;
}
}
return true;
}
return false;
};
return Config;
}());
/**
* @since 1.0.0
* @desc Sendbird Desk specific errors.
* @property {IErrorType} ERROR_SENDBIRD_SDK_MISSING - 100
* @property {IErrorType} ERROR_SENDBIRD_SDK_VERSION_NOT_SUPPORTED - 101
* @property {IErrorType} ERROR_SENDBIRD_DESK_INIT_MISSING - 102
* @property {IErrorType} ERROR_SENDBIRD_SDK_MESSAGE_LIST_FAILED - 200
* @property {IErrorType} ERROR_INVALID_PARAMETER - 403
* @property {IErrorType} ERROR_DATA_NOT_FOUND - 404
* @property {IErrorType} ERROR_REQUEST - 500
* @property {IErrorType} ERROR_REQUEST_CANCELED - 501
*/
var ErrorType = {
ERROR_SENDBIRD_SDK_MISSING: {
code: 100,
message: 'Sendbird SDK is missing.',
},
ERROR_SENDBIRD_SDK_VERSION_NOT_SUPPORTED: {
code: 101,
message: 'This Sendbird SDK version is not supported.',
},
ERROR_SENDBIRD_DESK_INIT_MISSING: {
code: 102,
message: 'Sendbird Desk SDK is not initialized. It should be done before authentication.',
},
ERROR_SENDBIRD_DESK_AUTH_FAILED: {
code: 103,
message: 'Sendbird Desk authentication failed.',
},
ERROR_SENDBIRD_SDK_MESSAGE_LIST_FAILED: {
code: 200,
message: 'Cannot load messages in SDK client.',
},
ERROR_INVALID_PARAMETER: {
code: 403,
message: 'Invalid parameter.',
},
ERROR_DATA_NOT_FOUND: {
code: 404,
message: 'Data not found.',
},
ERROR_REQUEST_TIMEOUT: {
code: 409,
message: 'Request timed-out.',
},
ERROR_REQUEST: {
code: 500,
message: 'Request failed.',
},
ERROR_REQUEST_CANCELED: {
code: 501,
message: 'Request canceled.',
},
};
/**
* An error class for Desk.
* @extends {Error}
* @since 1.0.0
*/
var SendbirdDeskError = /** @class */ (function (_super) {
__extends(SendbirdDeskError, _super);
/**
* @since 1.0.0
* @param {string} message - Error message.
* @param {number} code - Error code.
*/
function SendbirdDeskError(message, code) {
var _this = _super.call(this, message) || this;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(_this, _this.constructor);
}
else {
_this.stack = new Error(message).stack;
}
_this.name = 'SendbirdDeskError';
_this.code = code;
return _this;
}
Object.defineProperty(SendbirdDeskError, "Type", {
get: function () {
return ErrorType;
},
enumerable: false,
configurable: true
});
/**
* @static
* @since 1.0.5
* @ignore
* @desc Create an error.
*/
SendbirdDeskError.create = function (type) {
return type ? new SendbirdDeskError(type.message, type.code) : new Error('SendbirdDeskError type missing.');
};
/**
* @static
* @since 1.0.0
* @ignore
* @desc Throw an error.
*/
SendbirdDeskError.throw = function (type) {
throw new SendbirdDeskError(type.message, type.code);
};
return SendbirdDeskError;
}(Error));
/**
* @since 1.0.1
* @ignore
*/
var Logger = /** @class */ (function () {
function Logger() {
}
Logger.write = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (Config.isDebugMode) {
// eslint-disable-next-line no-console
console.log.apply(console, __spreadArray([], __read(args), false));
}
};
Logger.error = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (Config.isDebugMode) {
// eslint-disable-next-line no-console
console.error.apply(console, __spreadArray([], __read(args), false));
}
};
return Logger;
}());
var _privateData = {};
/**
* @since 1.0.0
* @ignore
*/
var Auth = /** @class */ (function () {
function Auth() {
}
/**
* @static
* @since 1.0.0
* @ignore
* @desc Authenticate and connect to Desk server.
*/
Auth.connect = function (userId, accessToken) {
return __awaiter(this, void 0, void 0, function () {
var sb, res, data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
sb = Config.sendbird;
sb.addSendbirdExtensions([
{
product: SendbirdProduct.DESK,
version: version,
platform: SendbirdPlatform.JS,
},
], {
platform: Config.platform,
});
if (!sb) return [3 /*break*/, 3];
return [4 /*yield*/, fetch("".concat(Config.apiHost, "/customers/auth/"), {
method: 'POST',
headers: {
sendbirdAccessToken: accessToken || '',
'content-type': 'application/json',
},
body: JSON.stringify({
sendbirdAppId: sb.appId,
sendbirdId: userId,
}),
})];
case 1:
res = _a.sent();
return [4 /*yield*/, res.json()];
case 2:
data = _a.sent();
_privateData.deskToken = data.token;
Logger.write('[REQ] connection established');
return [3 /*break*/, 4];
case 3: throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_SENDBIRD_SDK_MISSING);
case 4: return [2 /*return*/];
}
});
});
};
Object.defineProperty(Auth, "header", {
/**
* @ignore
*/
get: function () {
if (_privateData.deskToken) {
return {
sendbirdDeskToken: _privateData.deskToken,
'content-type': 'application/json',
'user-agent': "desk-js@".concat(version),
};
}
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_SENDBIRD_DESK_INIT_MISSING);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Auth, "getParam", {
/**
* @ignore
*/
get: function () {
var sb = Config.sendbird;
return sb ? "sendbirdAppId=".concat(sb.appId) : '';
},
enumerable: false,
configurable: true
});
Object.defineProperty(Auth, "postParam", {
/**
* @ignore
*/
get: function () {
var sb = Config.sendbird;
return sb ? { sendbirdAppId: sb.appId } : {};
},
enumerable: false,
configurable: true
});
return Auth;
}());
/**
* @module Agent
* @ignore
*/
/**
* @since 1.0.0
*/
var Agent = /** @class */ (function () {
/**
* @since 1.0.0
* @private
* @desc Create an agent.
*/
function Agent(params) {
this.fetchFromJSON(params);
}
/**
* @since 1.0.0
* @private
* @desc Parse JSON data and patch Agent object.
*/
Agent.prototype.fetchFromJSON = function (params) {
var _a, _b, _c, _d, _e;
if ('id' in params) {
this.userId = params.id;
this.name = (_a = params.displayName) !== null && _a !== void 0 ? _a : '';
this.profileUrl = (_b = params.photoThumbnailUrl) !== null && _b !== void 0 ? _b : '';
this.sendbirdId = params.sendbirdId;
return;
}
// legacy
this.userId = (_c = params.user) !== null && _c !== void 0 ? _c : 0;
this.name = (_d = params.displayName) !== null && _d !== void 0 ? _d : '';
this.profileUrl = (_e = params.photoThumbnailUrl) !== null && _e !== void 0 ? _e : '';
};
return Agent;
}());
/**
* @classdesc RelatedChannel
* @since 1.0.14
*/
var RelatedChannel = /** @class */ (function () {
/**
* @since 1.0.14
* @private
* @desc Create a related channel
*/
function RelatedChannel(params) {
this.fetchFromJSON(params);
}
/**
* @since 1.0.14
* @private
* @desc Parse JSON data and patch RelatedChannel object.
*/
RelatedChannel.prototype.fetchFromJSON = function (params) {
var _a, _b;
this.channelUrl = (_a = params.channel_url) !== null && _a !== void 0 ? _a : '';
this.name = (_b = params.name) !== null && _b !== void 0 ? _b : '';
};
return RelatedChannel;
}());
// --------- Misc Types --------- //
// Enums arent good match for runtime values.
// Would they work? Yeah.. but they would be annoying for customer
// to use. They just need to call create(..., 'URGENT', ...) instead of
// create(..., TicketPriority.URGENT, ...)
// to use. So we use const-enums instead.
var TicketPriorityMap = {
URGENT: 'URGENT',
HIGH: 'HIGH',
MEDIUM: 'MEDIUM',
LOW: 'LOW',
};
var TicketStatusMap = {
INITIALIZED: 'INITIALIZED',
PROACTIVE: 'PROACTIVE',
UNASSIGNED: 'UNASSIGNED',
ASSIGNED: 'ASSIGNED',
OPEN: 'OPEN',
CLOSED: 'CLOSED',
};
function mapCreateTicketArgs(args) {
if ((args === null || args === void 0 ? void 0 : args.length) < 3 || (args === null || args === void 0 ? void 0 : args.length) > 8) {
Logger.error('[REQ] Close ticket should have at least 1 param.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (args.length === 3) {
var _a = __read(args, 3), title = _a[0], name_1 = _a[1], cb = _a[2];
return { title: title, name: name_1, cb: cb };
}
if (args.length === 4) {
var _b = __read(args, 4), title = _b[0], name_2 = _b[1], groupKey = _b[2], cb = _b[3];
return { title: title, name: name_2, groupKey: groupKey, cb: cb };
}
if (args.length === 5) {
var _c = __read(args, 5), title = _c[0], name_3 = _c[1], groupKey = _c[2], customFields = _c[3], cb = _c[4];
return { title: title, name: name_3, groupKey: groupKey, customFields: customFields, cb: cb };
}
if (args.length === 6) {
var _d = __read(args, 6), title = _d[0], name_4 = _d[1], groupKey = _d[2], customFields = _d[3], priority = _d[4], cb = _d[5];
return { title: title, name: name_4, groupKey: groupKey, customFields: customFields, priority: priority, cb: cb };
}
if (args.length === 7) {
var _e = __read(args, 7), title = _e[0], name_5 = _e[1], groupKey = _e[2], customFields = _e[3], priority = _e[4], relatedChannelUrls = _e[5], cb = _e[6];
return { title: title, name: name_5, groupKey: groupKey, customFields: customFields, priority: priority, relatedChannelUrls: relatedChannelUrls, cb: cb };
}
if (args.length === 8) {
var _f = __read(args, 8), title = _f[0], name_6 = _f[1], groupKey = _f[2], customFields = _f[3], priority = _f[4], relatedChannelUrls = _f[5], botKey = _f[6], cb = _f[7];
return { title: title, name: name_6, groupKey: groupKey, customFields: customFields, priority: priority, relatedChannelUrls: relatedChannelUrls, botKey: botKey, cb: cb };
}
// TS dont know that we have checked for length
Logger.error('[REQ] Create ticket should have between 3 to 8 paramters.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
function validateCreateTicketArgs(params) {
var title = params.title, name = params.name, groupKey = params.groupKey, customFields = params.customFields, relatedChannelUrls = params.relatedChannelUrls, botKey = params.botKey, priority = params.priority;
if (typeof title !== 'string') {
Logger.error('[REQ] Create ticket title should be a string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (typeof name !== 'string') {
Logger.error('[REQ] Create ticket name should be a string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (groupKey && typeof groupKey !== 'string') {
Logger.error('[REQ] Create ticket groupKey should be a string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (priority && TicketPriorityMap[priority] === undefined) {
Logger.error('[REQ] Create ticket priority should be a string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (customFields && typeof customFields !== 'object') {
Logger.error('[REQ] Create ticket customFields should be an object.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (Array.isArray(customFields)) {
Logger.error('[REQ] Create ticket customFields cannot be an array.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (relatedChannelUrls && (!Array.isArray(relatedChannelUrls)
|| relatedChannelUrls.some(function (channelUrl) { return typeof channelUrl !== 'string'; }))) {
Logger.error('[REQ] Create ticket relatedChannelUrls should be an array.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (botKey && typeof botKey !== 'string') {
Logger.error('[REQ] Create ticket botKey should be a string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (typeof params.cb !== 'function') {
Logger.error('[REQ] Create ticket callback should be a function.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
function noop() { }
function mapCloseArgs(params) {
// more than 2 args
if (params.length > 2) {
Logger.error('[REQ] Close ticket should have only 2 params.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
// no args
var comment = '';
var cb = noop;
// one arg
if (params.length === 1) {
if (typeof params[0] === 'string') {
comment = params[0];
}
else if (typeof params[0] === 'function') {
cb = params[0];
}
}
// both args
if (params.length === 2) {
comment = params[0];
cb = params[1];
}
return {
comment: comment,
cb: cb,
};
}
function validateCloseArgs(params) {
var comment = params.comment, cb = params.cb;
if (typeof comment !== 'string') {
Logger.error('[REQ] first param must be string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (typeof cb !== 'function') {
Logger.error('[REQ] second param must be callback.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
}
/**
* @module Message
* @ignore
*/
/**
* @since 1.0.0
*/
var Message = /** @class */ (function () {
function Message() {
}
Object.defineProperty(Message, "CustomType", {
/**
* @static
* @since 1.0.0
* @desc message custom type.
* @property {string} RICH_MESSAGE - SENDBIRD_DESK_RICH_MESSAGE
* @property {string} ADMIN_MESSAGE - SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE
*/
get: function () {
return {
RICH_MESSAGE: 'SENDBIRD_DESK_RICH_MESSAGE',
ADMIN_MESSAGE: 'SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE',
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(Message, "DataType", {
/**
* @static
* @since 1.0.0
* @desc message data type.
* @property {string} TICKET_INQUIRE_CLOSURE - SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE
* @property {string} TICKET_ASSIGN - TICKET_ASSIGN
* @property {string} TICKET_TRANSFER - TICKET_TRANSFER
* @property {string} TICKET_CLOSE - TICKET_CLOSE
* @property {string} URL_PREVIEW - URL_PREVIEW
*/
get: function () {
return {
TICKET_INQUIRE_CLOSURE: 'SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE',
TICKET_ASSIGN: 'TICKET_ASSIGN',
TICKET_TRANSFER: 'TICKET_TRANSFER',
TICKET_CLOSE: 'TICKET_CLOSE',
TICKET_FEEDBACK: 'SENDBIRD_DESK_CUSTOMER_SATISFACTION',
URL_PREVIEW: 'SENDBIRD_DESK_URL_PREVIEW',
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(Message, "ClosureState", {
/**
* @static
* @since 1.0.0
* @desc closure inquiry messsage state.
* @property {string} WAITING - WAITING
* @property {string} CONFIRMED - CONFIRMED
* @property {string} DECLINED - DECLINED
*/
get: function () {
return {
WAITING: 'WAITING',
CONFIRMED: 'CONFIRMED',
DECLINED: 'DECLINED',
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(Message, "FeedbackState", {
/**
* @module Message
* @ignore
*/
/**
* @static
* @since 1.0.8
* @desc closure inquiry messsage state.
* @property {string} WAITING - WAITING
* @property {string} CONFIRMED - CONFIRMED
*/
get: function () {
return {
WAITING: 'WAITING',
CONFIRMED: 'CONFIRMED',
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(Message, "UrlRegExp", {
/**
* @ignore
*/
get: function () {
return /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?/gi;
},
enumerable: false,
configurable: true
});
return Message;
}());
function mapCancelArgs(params) {
if ((params === null || params === void 0 ? void 0 : params.length) < 1) {
Logger.error('Cancel ticket should have at least 1 param.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (params.length > 2) {
Logger.error('Cancel ticket should have only 2 params.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
var groupKeyForTransfer = '';
var cb = noop;
if (params.length === 1 && typeof params[0] === 'function') {
cb = params[0];
}
if (params.length === 1 && typeof params[0] === 'string') {
groupKeyForTransfer = params[0];
}
if (params.length === 2) {
groupKeyForTransfer = params[0];
cb = params[1];
}
return {
groupKeyForTransfer: groupKeyForTransfer,
cb: cb,
};
}
function validateCancelArgs(args) {
if (typeof args.groupKeyForTransfer !== 'string') {
Logger.error('First param must be string.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
if (typeof args.cb !== 'function') {
Logger.error('Second param must be callback.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
}
function mapGetByChannelUrlArgs(params) {
if ((params === null || params === void 0 ? void 0 : params.length) < 2 || (params === null || params === void 0 ? void 0 : params.length) > 3) {
Logger.error('[REQ] Get ticket should have 2 or 3 paramters.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_INVALID_PARAMETER);
}
// order of params is important
var channelUrl = params[0];
var cachingEnabled = params[1];
// last param is callback
var cb = params[params.length - 1] || noop;
// @ts-expect-error This will be validated in validateGetByChannelUrlArgs
return { channelUrl: channelUrl, cachingEnabled: cachingEnabled, cb: cb };
}
var TICKET_CUSTOM_TYPE = 'SENDBIRD_DESK_CHANNEL_CUSTOM_TYPE';
var DEFAULT_LIMIT = 10;
var _getByChannelUrls = function (channelUrls) { return __awaiter(void 0, void 0, void 0, function () {
var sb, query, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
sb = Config.sendbird;
if (!sb) return [3 /*break*/, 5];
query = sb.groupChannel.createMyGroupChannelListQuery({
customTypesFilter: [TICKET_CUSTOM_TYPE],
channelUrlsFilter: channelUrls,
includeEmpty: true,
});
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, query.next()];
case 2: return [2 /*return*/, _a.sent()];
case 3:
error_1 = _a.sent();
Logger.error('[REQ] ticket get by channel urls failed:', error_1);
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_REQUEST);
case 4: return [3 /*break*/, 6];
case 5:
Logger.error('[REQ] ticket get by channel urls failed: chat SDK is not initialized.');
throw SendbirdDeskError.create(SendbirdDeskError.Type.ERROR_SENDBIRD_SDK_MISSING);
case 6: return [2 /*return*/];
}
});
}); };
function generatePath(apiHost, authParam, params) {
var _a = params.offset, offset = _a === void 0 ? 0 : _a, _b = params.limit, limit = _b === void 0 ? DEFAULT_LIMIT : _b, _c = params.order, order = _c === void 0 ? '-updated_at' : _c, channelUrl = params.channelUrl, customFieldFilter = params.customFieldFilter, group = params.group, _d = params.status, status = _d === void 0 ? 'ALL' : _d;
var statusQuery = status !== TicketStatusMap.CLOSED ? 'status=ASSIGNED&status=UNASSIGNED' : 'status=CLOSED';
var path = "".concat(apiHost, "/tickets/") +
"?".concat(authParam, "&limit=").concat(limit, "&offset=").concat(offset) +
"".concat(status === 'ALL' ? '' : "&".concat(statusQuery), "&order=").concat(order);
if (channelUrl) {
path += "&channelUrl=".concat(channelUrl);
}
if (group) {
path += "&group=".concat(group);
}
if (customFieldFilter && typeof customFieldFilter === 'object') {
path +=
'&customFields=' +
encodeURIComponent(Object.keys(customFieldFilter)
.map(function (key) { return "".concat(key, ":").concat(encodeURIComponent(customFieldFilter[key])); })
.join(','));
}
return path;
}
function mapGetTicketArgs(args) {
if ((args === null || args === void 0 ? void 0 : args.length) < 2 || (args === null || args === void 0 ? void 0 : args.length) > 3) {
throw new Error('Get ticket should have 2 or 3 paramters.');
}
var offset = 0;
var filter = {};
var cb = noop;
if (args.length === 2) {
offset = args[0];
cb = args[1];
}
if (args.length === 3) {
offset = args[0];
filter = args[1];
cb = args[2];
}
return { offset: offset, filter: filter, cb: cb };
}
function validateGetTicketArgs(arg) {
var offset = arg.offset, filter = arg.filter, cb = arg.cb;
if (typeof offset !== 'number') {
throw new Error('Get ticket offset should be a number.');
}
if (typeof cb !== 'function') {
throw new Error('Get ticket callback should be a function.');
}
if (filter && typeof filter !== 'object') {
throw new Error('Get ticket filter should be an object.');
}
}
// bad scoping practice - rewrite this in v2
var _cachedTicket = {};
// Dear future me(July 2023),
// If you go through this code, you will see that the Ticket class is a mess.
// It's a mess because it's trying to do too many things.
// It has static methods to create tickets, and instance methods to update tickets.
// Ideally they should be separated in 2 places
// We should make a builder or something to create tickets
// and then we should have a Ticket instance to update/close/cancel tickets
// Also, I added some things that you might have found weird
// For example - why is there async _create and create methods?
// Desk(1.0.0) was written in 2017(with chatSDK 2 or 3) when cbs were the norm, and async/await was not a thing
// In 2023 management decided to update the chat SDK to chat 4. Now its a mess of cbs and async/await
// Sadly we were not allowed to make breaking changes, so we had to keep the old cb methods in Desk
// These _async methods are a workaround to keep the old cb methods and add async/await support
// Also, I have implemented in a way that - every difficult method is ->
// pub method(args_list) {
// args_map = argListToArgMap() -> validate()
// private async _method(args_map){
// [ args_map -> fetch() ] -> output
// }
// }
// later if we can refactor -
// * you can remove the cb-based public methods
// * you can change the private async _method -> pub async method
// * you can remove the argListToArgMap() -> and just use the args directly
// --- Ticket class !important---
// !Important: If you implement a public method here, please add it to type: `TicketClass`.
// --- Ticket class !important---
/**
* @since 1.0.0
*/
var Ticket = /** @class */ (function () {
/**
* @since 1.0.0
* @private
* @desc Create a ticket.
*/