UNPKG

79.4 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var protobufLight = _interopDefault(require('protobufjs/dist/protobuf-light'));
8var EventEmitter = _interopDefault(require('eventemitter3'));
9var _regeneratorRuntime = _interopDefault(require('@babel/runtime/regenerator'));
10var d = _interopDefault(require('debug'));
11var superagent = _interopDefault(require('superagent'));
12var shuffle = _interopDefault(require('lodash/shuffle'));
13var StateMachine = _interopDefault(require('javascript-state-machine'));
14var WebSocket = _interopDefault(require('ws'));
15var isPlainObject = _interopDefault(require('lodash/isPlainObject'));
16
17var messageCompiled = protobufLight.newBuilder({})['import']({
18 package: 'push_server.messages2',
19 syntax: 'proto2',
20 options: {
21 objc_class_prefix: 'AVIM'
22 },
23 messages: [{
24 name: 'JsonObjectMessage',
25 syntax: 'proto2',
26 fields: [{
27 rule: 'required',
28 type: 'string',
29 name: 'data',
30 id: 1
31 }]
32 }, {
33 name: 'UnreadTuple',
34 syntax: 'proto2',
35 fields: [{
36 rule: 'required',
37 type: 'string',
38 name: 'cid',
39 id: 1
40 }, {
41 rule: 'required',
42 type: 'int32',
43 name: 'unread',
44 id: 2
45 }, {
46 rule: 'optional',
47 type: 'string',
48 name: 'mid',
49 id: 3
50 }, {
51 rule: 'optional',
52 type: 'int64',
53 name: 'timestamp',
54 id: 4
55 }, {
56 rule: 'optional',
57 type: 'string',
58 name: 'from',
59 id: 5
60 }, {
61 rule: 'optional',
62 type: 'string',
63 name: 'data',
64 id: 6
65 }, {
66 rule: 'optional',
67 type: 'int64',
68 name: 'patchTimestamp',
69 id: 7
70 }, {
71 rule: 'optional',
72 type: 'bool',
73 name: 'mentioned',
74 id: 8
75 }, {
76 rule: 'optional',
77 type: 'bytes',
78 name: 'binaryMsg',
79 id: 9
80 }, {
81 rule: 'optional',
82 type: 'int32',
83 name: 'convType',
84 id: 10
85 }]
86 }, {
87 name: 'LogItem',
88 syntax: 'proto2',
89 fields: [{
90 rule: 'optional',
91 type: 'string',
92 name: 'from',
93 id: 1
94 }, {
95 rule: 'optional',
96 type: 'string',
97 name: 'data',
98 id: 2
99 }, {
100 rule: 'optional',
101 type: 'int64',
102 name: 'timestamp',
103 id: 3
104 }, {
105 rule: 'optional',
106 type: 'string',
107 name: 'msgId',
108 id: 4
109 }, {
110 rule: 'optional',
111 type: 'int64',
112 name: 'ackAt',
113 id: 5
114 }, {
115 rule: 'optional',
116 type: 'int64',
117 name: 'readAt',
118 id: 6
119 }, {
120 rule: 'optional',
121 type: 'int64',
122 name: 'patchTimestamp',
123 id: 7
124 }, {
125 rule: 'optional',
126 type: 'bool',
127 name: 'mentionAll',
128 id: 8
129 }, {
130 rule: 'repeated',
131 type: 'string',
132 name: 'mentionPids',
133 id: 9
134 }, {
135 rule: 'optional',
136 type: 'bool',
137 name: 'bin',
138 id: 10
139 }, {
140 rule: 'optional',
141 type: 'int32',
142 name: 'convType',
143 id: 11
144 }]
145 }, {
146 name: 'ConvMemberInfo',
147 syntax: 'proto2',
148 fields: [{
149 rule: 'optional',
150 type: 'string',
151 name: 'pid',
152 id: 1
153 }, {
154 rule: 'optional',
155 type: 'string',
156 name: 'role',
157 id: 2
158 }, {
159 rule: 'optional',
160 type: 'string',
161 name: 'infoId',
162 id: 3
163 }]
164 }, {
165 name: 'DataCommand',
166 syntax: 'proto2',
167 fields: [{
168 rule: 'repeated',
169 type: 'string',
170 name: 'ids',
171 id: 1
172 }, {
173 rule: 'repeated',
174 type: 'JsonObjectMessage',
175 name: 'msg',
176 id: 2
177 }, {
178 rule: 'optional',
179 type: 'bool',
180 name: 'offline',
181 id: 3
182 }]
183 }, {
184 name: 'SessionCommand',
185 syntax: 'proto2',
186 fields: [{
187 rule: 'optional',
188 type: 'int64',
189 name: 't',
190 id: 1
191 }, {
192 rule: 'optional',
193 type: 'string',
194 name: 'n',
195 id: 2
196 }, {
197 rule: 'optional',
198 type: 'string',
199 name: 's',
200 id: 3
201 }, {
202 rule: 'optional',
203 type: 'string',
204 name: 'ua',
205 id: 4
206 }, {
207 rule: 'optional',
208 type: 'bool',
209 name: 'r',
210 id: 5
211 }, {
212 rule: 'optional',
213 type: 'string',
214 name: 'tag',
215 id: 6
216 }, {
217 rule: 'optional',
218 type: 'string',
219 name: 'deviceId',
220 id: 7
221 }, {
222 rule: 'repeated',
223 type: 'string',
224 name: 'sessionPeerIds',
225 id: 8
226 }, {
227 rule: 'repeated',
228 type: 'string',
229 name: 'onlineSessionPeerIds',
230 id: 9
231 }, {
232 rule: 'optional',
233 type: 'string',
234 name: 'st',
235 id: 10
236 }, {
237 rule: 'optional',
238 type: 'int32',
239 name: 'stTtl',
240 id: 11
241 }, {
242 rule: 'optional',
243 type: 'int32',
244 name: 'code',
245 id: 12
246 }, {
247 rule: 'optional',
248 type: 'string',
249 name: 'reason',
250 id: 13
251 }, {
252 rule: 'optional',
253 type: 'string',
254 name: 'deviceToken',
255 id: 14
256 }, {
257 rule: 'optional',
258 type: 'bool',
259 name: 'sp',
260 id: 15
261 }, {
262 rule: 'optional',
263 type: 'string',
264 name: 'detail',
265 id: 16
266 }, {
267 rule: 'optional',
268 type: 'int64',
269 name: 'lastUnreadNotifTime',
270 id: 17
271 }, {
272 rule: 'optional',
273 type: 'int64',
274 name: 'lastPatchTime',
275 id: 18
276 }, {
277 rule: 'optional',
278 type: 'int64',
279 name: 'configBitmap',
280 id: 19
281 }]
282 }, {
283 name: 'ErrorCommand',
284 syntax: 'proto2',
285 fields: [{
286 rule: 'required',
287 type: 'int32',
288 name: 'code',
289 id: 1
290 }, {
291 rule: 'required',
292 type: 'string',
293 name: 'reason',
294 id: 2
295 }, {
296 rule: 'optional',
297 type: 'int32',
298 name: 'appCode',
299 id: 3
300 }, {
301 rule: 'optional',
302 type: 'string',
303 name: 'detail',
304 id: 4
305 }, {
306 rule: 'repeated',
307 type: 'string',
308 name: 'pids',
309 id: 5
310 }, {
311 rule: 'optional',
312 type: 'string',
313 name: 'appMsg',
314 id: 6
315 }]
316 }, {
317 name: 'DirectCommand',
318 syntax: 'proto2',
319 fields: [{
320 rule: 'optional',
321 type: 'string',
322 name: 'msg',
323 id: 1
324 }, {
325 rule: 'optional',
326 type: 'string',
327 name: 'uid',
328 id: 2
329 }, {
330 rule: 'optional',
331 type: 'string',
332 name: 'fromPeerId',
333 id: 3
334 }, {
335 rule: 'optional',
336 type: 'int64',
337 name: 'timestamp',
338 id: 4
339 }, {
340 rule: 'optional',
341 type: 'bool',
342 name: 'offline',
343 id: 5
344 }, {
345 rule: 'optional',
346 type: 'bool',
347 name: 'hasMore',
348 id: 6
349 }, {
350 rule: 'repeated',
351 type: 'string',
352 name: 'toPeerIds',
353 id: 7
354 }, {
355 rule: 'optional',
356 type: 'bool',
357 name: 'r',
358 id: 10
359 }, {
360 rule: 'optional',
361 type: 'string',
362 name: 'cid',
363 id: 11
364 }, {
365 rule: 'optional',
366 type: 'string',
367 name: 'id',
368 id: 12
369 }, {
370 rule: 'optional',
371 type: 'bool',
372 name: 'transient',
373 id: 13
374 }, {
375 rule: 'optional',
376 type: 'string',
377 name: 'dt',
378 id: 14
379 }, {
380 rule: 'optional',
381 type: 'string',
382 name: 'roomId',
383 id: 15
384 }, {
385 rule: 'optional',
386 type: 'string',
387 name: 'pushData',
388 id: 16
389 }, {
390 rule: 'optional',
391 type: 'bool',
392 name: 'will',
393 id: 17
394 }, {
395 rule: 'optional',
396 type: 'int64',
397 name: 'patchTimestamp',
398 id: 18
399 }, {
400 rule: 'optional',
401 type: 'bytes',
402 name: 'binaryMsg',
403 id: 19
404 }, {
405 rule: 'repeated',
406 type: 'string',
407 name: 'mentionPids',
408 id: 20
409 }, {
410 rule: 'optional',
411 type: 'bool',
412 name: 'mentionAll',
413 id: 21
414 }, {
415 rule: 'optional',
416 type: 'int32',
417 name: 'convType',
418 id: 22
419 }]
420 }, {
421 name: 'AckCommand',
422 syntax: 'proto2',
423 fields: [{
424 rule: 'optional',
425 type: 'int32',
426 name: 'code',
427 id: 1
428 }, {
429 rule: 'optional',
430 type: 'string',
431 name: 'reason',
432 id: 2
433 }, {
434 rule: 'optional',
435 type: 'string',
436 name: 'mid',
437 id: 3
438 }, {
439 rule: 'optional',
440 type: 'string',
441 name: 'cid',
442 id: 4
443 }, {
444 rule: 'optional',
445 type: 'int64',
446 name: 't',
447 id: 5
448 }, {
449 rule: 'optional',
450 type: 'string',
451 name: 'uid',
452 id: 6
453 }, {
454 rule: 'optional',
455 type: 'int64',
456 name: 'fromts',
457 id: 7
458 }, {
459 rule: 'optional',
460 type: 'int64',
461 name: 'tots',
462 id: 8
463 }, {
464 rule: 'optional',
465 type: 'string',
466 name: 'type',
467 id: 9
468 }, {
469 rule: 'repeated',
470 type: 'string',
471 name: 'ids',
472 id: 10
473 }, {
474 rule: 'optional',
475 type: 'int32',
476 name: 'appCode',
477 id: 11
478 }, {
479 rule: 'optional',
480 type: 'string',
481 name: 'appMsg',
482 id: 12
483 }]
484 }, {
485 name: 'UnreadCommand',
486 syntax: 'proto2',
487 fields: [{
488 rule: 'repeated',
489 type: 'UnreadTuple',
490 name: 'convs',
491 id: 1
492 }, {
493 rule: 'optional',
494 type: 'int64',
495 name: 'notifTime',
496 id: 2
497 }]
498 }, {
499 name: 'ConvCommand',
500 syntax: 'proto2',
501 fields: [{
502 rule: 'repeated',
503 type: 'string',
504 name: 'm',
505 id: 1
506 }, {
507 rule: 'optional',
508 type: 'bool',
509 name: 'transient',
510 id: 2
511 }, {
512 rule: 'optional',
513 type: 'bool',
514 name: 'unique',
515 id: 3
516 }, {
517 rule: 'optional',
518 type: 'string',
519 name: 'cid',
520 id: 4
521 }, {
522 rule: 'optional',
523 type: 'string',
524 name: 'cdate',
525 id: 5
526 }, {
527 rule: 'optional',
528 type: 'string',
529 name: 'initBy',
530 id: 6
531 }, {
532 rule: 'optional',
533 type: 'string',
534 name: 'sort',
535 id: 7
536 }, {
537 rule: 'optional',
538 type: 'int32',
539 name: 'limit',
540 id: 8
541 }, {
542 rule: 'optional',
543 type: 'int32',
544 name: 'skip',
545 id: 9
546 }, {
547 rule: 'optional',
548 type: 'int32',
549 name: 'flag',
550 id: 10
551 }, {
552 rule: 'optional',
553 type: 'int32',
554 name: 'count',
555 id: 11
556 }, {
557 rule: 'optional',
558 type: 'string',
559 name: 'udate',
560 id: 12
561 }, {
562 rule: 'optional',
563 type: 'int64',
564 name: 't',
565 id: 13
566 }, {
567 rule: 'optional',
568 type: 'string',
569 name: 'n',
570 id: 14
571 }, {
572 rule: 'optional',
573 type: 'string',
574 name: 's',
575 id: 15
576 }, {
577 rule: 'optional',
578 type: 'bool',
579 name: 'statusSub',
580 id: 16
581 }, {
582 rule: 'optional',
583 type: 'bool',
584 name: 'statusPub',
585 id: 17
586 }, {
587 rule: 'optional',
588 type: 'int32',
589 name: 'statusTTL',
590 id: 18
591 }, {
592 rule: 'optional',
593 type: 'string',
594 name: 'uniqueId',
595 id: 19
596 }, {
597 rule: 'optional',
598 type: 'string',
599 name: 'targetClientId',
600 id: 20
601 }, {
602 rule: 'optional',
603 type: 'int64',
604 name: 'maxReadTimestamp',
605 id: 21
606 }, {
607 rule: 'optional',
608 type: 'int64',
609 name: 'maxAckTimestamp',
610 id: 22
611 }, {
612 rule: 'optional',
613 type: 'bool',
614 name: 'queryAllMembers',
615 id: 23
616 }, {
617 rule: 'repeated',
618 type: 'MaxReadTuple',
619 name: 'maxReadTuples',
620 id: 24
621 }, {
622 rule: 'repeated',
623 type: 'string',
624 name: 'cids',
625 id: 25
626 }, {
627 rule: 'optional',
628 type: 'ConvMemberInfo',
629 name: 'info',
630 id: 26
631 }, {
632 rule: 'optional',
633 type: 'bool',
634 name: 'tempConv',
635 id: 27
636 }, {
637 rule: 'optional',
638 type: 'int32',
639 name: 'tempConvTTL',
640 id: 28
641 }, {
642 rule: 'repeated',
643 type: 'string',
644 name: 'tempConvIds',
645 id: 29
646 }, {
647 rule: 'repeated',
648 type: 'string',
649 name: 'allowedPids',
650 id: 30
651 }, {
652 rule: 'repeated',
653 type: 'ErrorCommand',
654 name: 'failedPids',
655 id: 31
656 }, {
657 rule: 'optional',
658 type: 'string',
659 name: 'next',
660 id: 40
661 }, {
662 rule: 'optional',
663 type: 'JsonObjectMessage',
664 name: 'results',
665 id: 100
666 }, {
667 rule: 'optional',
668 type: 'JsonObjectMessage',
669 name: 'where',
670 id: 101
671 }, {
672 rule: 'optional',
673 type: 'JsonObjectMessage',
674 name: 'attr',
675 id: 103
676 }, {
677 rule: 'optional',
678 type: 'JsonObjectMessage',
679 name: 'attrModified',
680 id: 104
681 }]
682 }, {
683 name: 'RoomCommand',
684 syntax: 'proto2',
685 fields: [{
686 rule: 'optional',
687 type: 'string',
688 name: 'roomId',
689 id: 1
690 }, {
691 rule: 'optional',
692 type: 'string',
693 name: 's',
694 id: 2
695 }, {
696 rule: 'optional',
697 type: 'int64',
698 name: 't',
699 id: 3
700 }, {
701 rule: 'optional',
702 type: 'string',
703 name: 'n',
704 id: 4
705 }, {
706 rule: 'optional',
707 type: 'bool',
708 name: 'transient',
709 id: 5
710 }, {
711 rule: 'repeated',
712 type: 'string',
713 name: 'roomPeerIds',
714 id: 6
715 }, {
716 rule: 'optional',
717 type: 'string',
718 name: 'byPeerId',
719 id: 7
720 }]
721 }, {
722 name: 'LogsCommand',
723 syntax: 'proto2',
724 fields: [{
725 rule: 'optional',
726 type: 'string',
727 name: 'cid',
728 id: 1
729 }, {
730 rule: 'optional',
731 type: 'int32',
732 name: 'l',
733 id: 2
734 }, {
735 rule: 'optional',
736 type: 'int32',
737 name: 'limit',
738 id: 3
739 }, {
740 rule: 'optional',
741 type: 'int64',
742 name: 't',
743 id: 4
744 }, {
745 rule: 'optional',
746 type: 'int64',
747 name: 'tt',
748 id: 5
749 }, {
750 rule: 'optional',
751 type: 'string',
752 name: 'tmid',
753 id: 6
754 }, {
755 rule: 'optional',
756 type: 'string',
757 name: 'mid',
758 id: 7
759 }, {
760 rule: 'optional',
761 type: 'string',
762 name: 'checksum',
763 id: 8
764 }, {
765 rule: 'optional',
766 type: 'bool',
767 name: 'stored',
768 id: 9
769 }, {
770 rule: 'optional',
771 type: 'QueryDirection',
772 name: 'direction',
773 id: 10,
774 options: {
775 default: 'OLD'
776 }
777 }, {
778 rule: 'optional',
779 type: 'bool',
780 name: 'tIncluded',
781 id: 11
782 }, {
783 rule: 'optional',
784 type: 'bool',
785 name: 'ttIncluded',
786 id: 12
787 }, {
788 rule: 'optional',
789 type: 'int32',
790 name: 'lctype',
791 id: 13
792 }, {
793 rule: 'repeated',
794 type: 'LogItem',
795 name: 'logs',
796 id: 105
797 }],
798 enums: [{
799 name: 'QueryDirection',
800 syntax: 'proto2',
801 values: [{
802 name: 'OLD',
803 id: 1
804 }, {
805 name: 'NEW',
806 id: 2
807 }]
808 }]
809 }, {
810 name: 'RcpCommand',
811 syntax: 'proto2',
812 fields: [{
813 rule: 'optional',
814 type: 'string',
815 name: 'id',
816 id: 1
817 }, {
818 rule: 'optional',
819 type: 'string',
820 name: 'cid',
821 id: 2
822 }, {
823 rule: 'optional',
824 type: 'int64',
825 name: 't',
826 id: 3
827 }, {
828 rule: 'optional',
829 type: 'bool',
830 name: 'read',
831 id: 4
832 }, {
833 rule: 'optional',
834 type: 'string',
835 name: 'from',
836 id: 5
837 }]
838 }, {
839 name: 'ReadTuple',
840 syntax: 'proto2',
841 fields: [{
842 rule: 'required',
843 type: 'string',
844 name: 'cid',
845 id: 1
846 }, {
847 rule: 'optional',
848 type: 'int64',
849 name: 'timestamp',
850 id: 2
851 }, {
852 rule: 'optional',
853 type: 'string',
854 name: 'mid',
855 id: 3
856 }]
857 }, {
858 name: 'MaxReadTuple',
859 syntax: 'proto2',
860 fields: [{
861 rule: 'optional',
862 type: 'string',
863 name: 'pid',
864 id: 1
865 }, {
866 rule: 'optional',
867 type: 'int64',
868 name: 'maxAckTimestamp',
869 id: 2
870 }, {
871 rule: 'optional',
872 type: 'int64',
873 name: 'maxReadTimestamp',
874 id: 3
875 }]
876 }, {
877 name: 'ReadCommand',
878 syntax: 'proto2',
879 fields: [{
880 rule: 'optional',
881 type: 'string',
882 name: 'cid',
883 id: 1
884 }, {
885 rule: 'repeated',
886 type: 'string',
887 name: 'cids',
888 id: 2
889 }, {
890 rule: 'repeated',
891 type: 'ReadTuple',
892 name: 'convs',
893 id: 3
894 }]
895 }, {
896 name: 'PresenceCommand',
897 syntax: 'proto2',
898 fields: [{
899 rule: 'optional',
900 type: 'StatusType',
901 name: 'status',
902 id: 1
903 }, {
904 rule: 'repeated',
905 type: 'string',
906 name: 'sessionPeerIds',
907 id: 2
908 }, {
909 rule: 'optional',
910 type: 'string',
911 name: 'cid',
912 id: 3
913 }]
914 }, {
915 name: 'ReportCommand',
916 syntax: 'proto2',
917 fields: [{
918 rule: 'optional',
919 type: 'bool',
920 name: 'initiative',
921 id: 1
922 }, {
923 rule: 'optional',
924 type: 'string',
925 name: 'type',
926 id: 2
927 }, {
928 rule: 'optional',
929 type: 'string',
930 name: 'data',
931 id: 3
932 }]
933 }, {
934 name: 'PatchItem',
935 syntax: 'proto2',
936 fields: [{
937 rule: 'optional',
938 type: 'string',
939 name: 'cid',
940 id: 1
941 }, {
942 rule: 'optional',
943 type: 'string',
944 name: 'mid',
945 id: 2
946 }, {
947 rule: 'optional',
948 type: 'int64',
949 name: 'timestamp',
950 id: 3
951 }, {
952 rule: 'optional',
953 type: 'bool',
954 name: 'recall',
955 id: 4
956 }, {
957 rule: 'optional',
958 type: 'string',
959 name: 'data',
960 id: 5
961 }, {
962 rule: 'optional',
963 type: 'int64',
964 name: 'patchTimestamp',
965 id: 6
966 }, {
967 rule: 'optional',
968 type: 'string',
969 name: 'from',
970 id: 7
971 }, {
972 rule: 'optional',
973 type: 'bytes',
974 name: 'binaryMsg',
975 id: 8
976 }, {
977 rule: 'optional',
978 type: 'bool',
979 name: 'mentionAll',
980 id: 9
981 }, {
982 rule: 'repeated',
983 type: 'string',
984 name: 'mentionPids',
985 id: 10
986 }, {
987 rule: 'optional',
988 type: 'int64',
989 name: 'patchCode',
990 id: 11
991 }, {
992 rule: 'optional',
993 type: 'string',
994 name: 'patchReason',
995 id: 12
996 }]
997 }, {
998 name: 'PatchCommand',
999 syntax: 'proto2',
1000 fields: [{
1001 rule: 'repeated',
1002 type: 'PatchItem',
1003 name: 'patches',
1004 id: 1
1005 }, {
1006 rule: 'optional',
1007 type: 'int64',
1008 name: 'lastPatchTime',
1009 id: 2
1010 }]
1011 }, {
1012 name: 'PubsubCommand',
1013 syntax: 'proto2',
1014 fields: [{
1015 rule: 'optional',
1016 type: 'string',
1017 name: 'cid',
1018 id: 1
1019 }, {
1020 rule: 'repeated',
1021 type: 'string',
1022 name: 'cids',
1023 id: 2
1024 }, {
1025 rule: 'optional',
1026 type: 'string',
1027 name: 'topic',
1028 id: 3
1029 }, {
1030 rule: 'optional',
1031 type: 'string',
1032 name: 'subtopic',
1033 id: 4
1034 }, {
1035 rule: 'repeated',
1036 type: 'string',
1037 name: 'topics',
1038 id: 5
1039 }, {
1040 rule: 'repeated',
1041 type: 'string',
1042 name: 'subtopics',
1043 id: 6
1044 }, {
1045 rule: 'optional',
1046 type: 'JsonObjectMessage',
1047 name: 'results',
1048 id: 7
1049 }]
1050 }, {
1051 name: 'BlacklistCommand',
1052 syntax: 'proto2',
1053 fields: [{
1054 rule: 'optional',
1055 type: 'string',
1056 name: 'srcCid',
1057 id: 1
1058 }, {
1059 rule: 'repeated',
1060 type: 'string',
1061 name: 'toPids',
1062 id: 2
1063 }, {
1064 rule: 'optional',
1065 type: 'string',
1066 name: 'srcPid',
1067 id: 3
1068 }, {
1069 rule: 'repeated',
1070 type: 'string',
1071 name: 'toCids',
1072 id: 4
1073 }, {
1074 rule: 'optional',
1075 type: 'int32',
1076 name: 'limit',
1077 id: 5
1078 }, {
1079 rule: 'optional',
1080 type: 'string',
1081 name: 'next',
1082 id: 6
1083 }, {
1084 rule: 'repeated',
1085 type: 'string',
1086 name: 'blockedPids',
1087 id: 8
1088 }, {
1089 rule: 'repeated',
1090 type: 'string',
1091 name: 'blockedCids',
1092 id: 9
1093 }, {
1094 rule: 'repeated',
1095 type: 'string',
1096 name: 'allowedPids',
1097 id: 10
1098 }, {
1099 rule: 'repeated',
1100 type: 'ErrorCommand',
1101 name: 'failedPids',
1102 id: 11
1103 }, {
1104 rule: 'optional',
1105 type: 'int64',
1106 name: 't',
1107 id: 12
1108 }, {
1109 rule: 'optional',
1110 type: 'string',
1111 name: 'n',
1112 id: 13
1113 }, {
1114 rule: 'optional',
1115 type: 'string',
1116 name: 's',
1117 id: 14
1118 }]
1119 }, {
1120 name: 'GenericCommand',
1121 syntax: 'proto2',
1122 fields: [{
1123 rule: 'optional',
1124 type: 'CommandType',
1125 name: 'cmd',
1126 id: 1
1127 }, {
1128 rule: 'optional',
1129 type: 'OpType',
1130 name: 'op',
1131 id: 2
1132 }, {
1133 rule: 'optional',
1134 type: 'string',
1135 name: 'appId',
1136 id: 3
1137 }, {
1138 rule: 'optional',
1139 type: 'string',
1140 name: 'peerId',
1141 id: 4
1142 }, {
1143 rule: 'optional',
1144 type: 'int32',
1145 name: 'i',
1146 id: 5
1147 }, {
1148 rule: 'optional',
1149 type: 'string',
1150 name: 'installationId',
1151 id: 6
1152 }, {
1153 rule: 'optional',
1154 type: 'int32',
1155 name: 'priority',
1156 id: 7
1157 }, {
1158 rule: 'optional',
1159 type: 'int32',
1160 name: 'service',
1161 id: 8
1162 }, {
1163 rule: 'optional',
1164 type: 'int64',
1165 name: 'serverTs',
1166 id: 9
1167 }, {
1168 rule: 'optional',
1169 type: 'int64',
1170 name: 'clientTs',
1171 id: 10
1172 }, {
1173 rule: 'optional',
1174 type: 'int32',
1175 name: 'notificationType',
1176 id: 11
1177 }, {
1178 rule: 'optional',
1179 type: 'DataCommand',
1180 name: 'dataMessage',
1181 id: 101
1182 }, {
1183 rule: 'optional',
1184 type: 'SessionCommand',
1185 name: 'sessionMessage',
1186 id: 102
1187 }, {
1188 rule: 'optional',
1189 type: 'ErrorCommand',
1190 name: 'errorMessage',
1191 id: 103
1192 }, {
1193 rule: 'optional',
1194 type: 'DirectCommand',
1195 name: 'directMessage',
1196 id: 104
1197 }, {
1198 rule: 'optional',
1199 type: 'AckCommand',
1200 name: 'ackMessage',
1201 id: 105
1202 }, {
1203 rule: 'optional',
1204 type: 'UnreadCommand',
1205 name: 'unreadMessage',
1206 id: 106
1207 }, {
1208 rule: 'optional',
1209 type: 'ReadCommand',
1210 name: 'readMessage',
1211 id: 107
1212 }, {
1213 rule: 'optional',
1214 type: 'RcpCommand',
1215 name: 'rcpMessage',
1216 id: 108
1217 }, {
1218 rule: 'optional',
1219 type: 'LogsCommand',
1220 name: 'logsMessage',
1221 id: 109
1222 }, {
1223 rule: 'optional',
1224 type: 'ConvCommand',
1225 name: 'convMessage',
1226 id: 110
1227 }, {
1228 rule: 'optional',
1229 type: 'RoomCommand',
1230 name: 'roomMessage',
1231 id: 111
1232 }, {
1233 rule: 'optional',
1234 type: 'PresenceCommand',
1235 name: 'presenceMessage',
1236 id: 112
1237 }, {
1238 rule: 'optional',
1239 type: 'ReportCommand',
1240 name: 'reportMessage',
1241 id: 113
1242 }, {
1243 rule: 'optional',
1244 type: 'PatchCommand',
1245 name: 'patchMessage',
1246 id: 114
1247 }, {
1248 rule: 'optional',
1249 type: 'PubsubCommand',
1250 name: 'pubsubMessage',
1251 id: 115
1252 }, {
1253 rule: 'optional',
1254 type: 'BlacklistCommand',
1255 name: 'blacklistMessage',
1256 id: 116
1257 }]
1258 }],
1259 enums: [{
1260 name: 'CommandType',
1261 syntax: 'proto2',
1262 values: [{
1263 name: 'session',
1264 id: 0
1265 }, {
1266 name: 'conv',
1267 id: 1
1268 }, {
1269 name: 'direct',
1270 id: 2
1271 }, {
1272 name: 'ack',
1273 id: 3
1274 }, {
1275 name: 'rcp',
1276 id: 4
1277 }, {
1278 name: 'unread',
1279 id: 5
1280 }, {
1281 name: 'logs',
1282 id: 6
1283 }, {
1284 name: 'error',
1285 id: 7
1286 }, {
1287 name: 'login',
1288 id: 8
1289 }, {
1290 name: 'data',
1291 id: 9
1292 }, {
1293 name: 'room',
1294 id: 10
1295 }, {
1296 name: 'read',
1297 id: 11
1298 }, {
1299 name: 'presence',
1300 id: 12
1301 }, {
1302 name: 'report',
1303 id: 13
1304 }, {
1305 name: 'echo',
1306 id: 14
1307 }, {
1308 name: 'loggedin',
1309 id: 15
1310 }, {
1311 name: 'logout',
1312 id: 16
1313 }, {
1314 name: 'loggedout',
1315 id: 17
1316 }, {
1317 name: 'patch',
1318 id: 18
1319 }, {
1320 name: 'pubsub',
1321 id: 19
1322 }, {
1323 name: 'blacklist',
1324 id: 20
1325 }, {
1326 name: 'goaway',
1327 id: 21
1328 }]
1329 }, {
1330 name: 'OpType',
1331 syntax: 'proto2',
1332 values: [{
1333 name: 'open',
1334 id: 1
1335 }, {
1336 name: 'add',
1337 id: 2
1338 }, {
1339 name: 'remove',
1340 id: 3
1341 }, {
1342 name: 'close',
1343 id: 4
1344 }, {
1345 name: 'opened',
1346 id: 5
1347 }, {
1348 name: 'closed',
1349 id: 6
1350 }, {
1351 name: 'query',
1352 id: 7
1353 }, {
1354 name: 'query_result',
1355 id: 8
1356 }, {
1357 name: 'conflict',
1358 id: 9
1359 }, {
1360 name: 'added',
1361 id: 10
1362 }, {
1363 name: 'removed',
1364 id: 11
1365 }, {
1366 name: 'refresh',
1367 id: 12
1368 }, {
1369 name: 'refreshed',
1370 id: 13
1371 }, {
1372 name: 'start',
1373 id: 30
1374 }, {
1375 name: 'started',
1376 id: 31
1377 }, {
1378 name: 'joined',
1379 id: 32
1380 }, {
1381 name: 'members_joined',
1382 id: 33
1383 }, {
1384 name: 'left',
1385 id: 39
1386 }, {
1387 name: 'members_left',
1388 id: 40
1389 }, {
1390 name: 'results',
1391 id: 42
1392 }, {
1393 name: 'count',
1394 id: 43
1395 }, {
1396 name: 'result',
1397 id: 44
1398 }, {
1399 name: 'update',
1400 id: 45
1401 }, {
1402 name: 'updated',
1403 id: 46
1404 }, {
1405 name: 'mute',
1406 id: 47
1407 }, {
1408 name: 'unmute',
1409 id: 48
1410 }, {
1411 name: 'status',
1412 id: 49
1413 }, {
1414 name: 'members',
1415 id: 50
1416 }, {
1417 name: 'max_read',
1418 id: 51
1419 }, {
1420 name: 'is_member',
1421 id: 52
1422 }, {
1423 name: 'member_info_update',
1424 id: 53
1425 }, {
1426 name: 'member_info_updated',
1427 id: 54
1428 }, {
1429 name: 'member_info_changed',
1430 id: 55
1431 }, {
1432 name: 'join',
1433 id: 80
1434 }, {
1435 name: 'invite',
1436 id: 81
1437 }, {
1438 name: 'leave',
1439 id: 82
1440 }, {
1441 name: 'kick',
1442 id: 83
1443 }, {
1444 name: 'reject',
1445 id: 84
1446 }, {
1447 name: 'invited',
1448 id: 85
1449 }, {
1450 name: 'kicked',
1451 id: 86
1452 }, {
1453 name: 'upload',
1454 id: 100
1455 }, {
1456 name: 'uploaded',
1457 id: 101
1458 }, {
1459 name: 'subscribe',
1460 id: 120
1461 }, {
1462 name: 'subscribed',
1463 id: 121
1464 }, {
1465 name: 'unsubscribe',
1466 id: 122
1467 }, {
1468 name: 'unsubscribed',
1469 id: 123
1470 }, {
1471 name: 'is_subscribed',
1472 id: 124
1473 }, {
1474 name: 'modify',
1475 id: 150
1476 }, {
1477 name: 'modified',
1478 id: 151
1479 }, {
1480 name: 'block',
1481 id: 170
1482 }, {
1483 name: 'unblock',
1484 id: 171
1485 }, {
1486 name: 'blocked',
1487 id: 172
1488 }, {
1489 name: 'unblocked',
1490 id: 173
1491 }, {
1492 name: 'members_blocked',
1493 id: 174
1494 }, {
1495 name: 'members_unblocked',
1496 id: 175
1497 }, {
1498 name: 'check_block',
1499 id: 176
1500 }, {
1501 name: 'check_result',
1502 id: 177
1503 }, {
1504 name: 'add_shutup',
1505 id: 180
1506 }, {
1507 name: 'remove_shutup',
1508 id: 181
1509 }, {
1510 name: 'query_shutup',
1511 id: 182
1512 }, {
1513 name: 'shutup_added',
1514 id: 183
1515 }, {
1516 name: 'shutup_removed',
1517 id: 184
1518 }, {
1519 name: 'shutup_result',
1520 id: 185
1521 }, {
1522 name: 'shutuped',
1523 id: 186
1524 }, {
1525 name: 'unshutuped',
1526 id: 187
1527 }, {
1528 name: 'members_shutuped',
1529 id: 188
1530 }, {
1531 name: 'members_unshutuped',
1532 id: 189
1533 }, {
1534 name: 'check_shutup',
1535 id: 190
1536 }]
1537 }, {
1538 name: 'StatusType',
1539 syntax: 'proto2',
1540 values: [{
1541 name: 'on',
1542 id: 1
1543 }, {
1544 name: 'off',
1545 id: 2
1546 }]
1547 }],
1548 isNamespace: true
1549}).build();
1550
1551var _messages$push_server = messageCompiled.push_server.messages2,
1552 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
1553 UnreadTuple = _messages$push_server.UnreadTuple,
1554 LogItem = _messages$push_server.LogItem,
1555 DataCommand = _messages$push_server.DataCommand,
1556 SessionCommand = _messages$push_server.SessionCommand,
1557 ErrorCommand = _messages$push_server.ErrorCommand,
1558 DirectCommand = _messages$push_server.DirectCommand,
1559 AckCommand = _messages$push_server.AckCommand,
1560 UnreadCommand = _messages$push_server.UnreadCommand,
1561 ConvCommand = _messages$push_server.ConvCommand,
1562 RoomCommand = _messages$push_server.RoomCommand,
1563 LogsCommand = _messages$push_server.LogsCommand,
1564 RcpCommand = _messages$push_server.RcpCommand,
1565 ReadTuple = _messages$push_server.ReadTuple,
1566 MaxReadTuple = _messages$push_server.MaxReadTuple,
1567 ReadCommand = _messages$push_server.ReadCommand,
1568 PresenceCommand = _messages$push_server.PresenceCommand,
1569 ReportCommand = _messages$push_server.ReportCommand,
1570 GenericCommand = _messages$push_server.GenericCommand,
1571 BlacklistCommand = _messages$push_server.BlacklistCommand,
1572 PatchCommand = _messages$push_server.PatchCommand,
1573 PatchItem = _messages$push_server.PatchItem,
1574 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
1575 CommandType = _messages$push_server.CommandType,
1576 OpType = _messages$push_server.OpType,
1577 StatusType = _messages$push_server.StatusType;
1578
1579var message = /*#__PURE__*/Object.freeze({
1580 JsonObjectMessage: JsonObjectMessage,
1581 UnreadTuple: UnreadTuple,
1582 LogItem: LogItem,
1583 DataCommand: DataCommand,
1584 SessionCommand: SessionCommand,
1585 ErrorCommand: ErrorCommand,
1586 DirectCommand: DirectCommand,
1587 AckCommand: AckCommand,
1588 UnreadCommand: UnreadCommand,
1589 ConvCommand: ConvCommand,
1590 RoomCommand: RoomCommand,
1591 LogsCommand: LogsCommand,
1592 RcpCommand: RcpCommand,
1593 ReadTuple: ReadTuple,
1594 MaxReadTuple: MaxReadTuple,
1595 ReadCommand: ReadCommand,
1596 PresenceCommand: PresenceCommand,
1597 ReportCommand: ReportCommand,
1598 GenericCommand: GenericCommand,
1599 BlacklistCommand: BlacklistCommand,
1600 PatchCommand: PatchCommand,
1601 PatchItem: PatchItem,
1602 ConvMemberInfo: ConvMemberInfo,
1603 CommandType: CommandType,
1604 OpType: OpType,
1605 StatusType: StatusType
1606});
1607
1608function _typeof(obj) {
1609 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
1610 _typeof = function (obj) {
1611 return typeof obj;
1612 };
1613 } else {
1614 _typeof = function (obj) {
1615 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1616 };
1617 }
1618
1619 return _typeof(obj);
1620}
1621
1622function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1623 try {
1624 var info = gen[key](arg);
1625 var value = info.value;
1626 } catch (error) {
1627 reject(error);
1628 return;
1629 }
1630
1631 if (info.done) {
1632 resolve(value);
1633 } else {
1634 Promise.resolve(value).then(_next, _throw);
1635 }
1636}
1637
1638function _asyncToGenerator(fn) {
1639 return function () {
1640 var self = this,
1641 args = arguments;
1642 return new Promise(function (resolve, reject) {
1643 var gen = fn.apply(self, args);
1644
1645 function _next(value) {
1646 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1647 }
1648
1649 function _throw(err) {
1650 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1651 }
1652
1653 _next(undefined);
1654 });
1655 };
1656}
1657
1658function _defineProperties(target, props) {
1659 for (var i = 0; i < props.length; i++) {
1660 var descriptor = props[i];
1661 descriptor.enumerable = descriptor.enumerable || false;
1662 descriptor.configurable = true;
1663 if ("value" in descriptor) descriptor.writable = true;
1664 Object.defineProperty(target, descriptor.key, descriptor);
1665 }
1666}
1667
1668function _createClass(Constructor, protoProps, staticProps) {
1669 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1670 if (staticProps) _defineProperties(Constructor, staticProps);
1671 return Constructor;
1672}
1673
1674function _defineProperty(obj, key, value) {
1675 if (key in obj) {
1676 Object.defineProperty(obj, key, {
1677 value: value,
1678 enumerable: true,
1679 configurable: true,
1680 writable: true
1681 });
1682 } else {
1683 obj[key] = value;
1684 }
1685
1686 return obj;
1687}
1688
1689function _objectSpread(target) {
1690 for (var i = 1; i < arguments.length; i++) {
1691 var source = arguments[i] != null ? arguments[i] : {};
1692 var ownKeys = Object.keys(source);
1693
1694 if (typeof Object.getOwnPropertySymbols === 'function') {
1695 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
1696 return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1697 }));
1698 }
1699
1700 ownKeys.forEach(function (key) {
1701 _defineProperty(target, key, source[key]);
1702 });
1703 }
1704
1705 return target;
1706}
1707
1708function _inheritsLoose(subClass, superClass) {
1709 subClass.prototype = Object.create(superClass.prototype);
1710 subClass.prototype.constructor = subClass;
1711 subClass.__proto__ = superClass;
1712}
1713
1714function _objectWithoutPropertiesLoose(source, excluded) {
1715 if (source == null) return {};
1716 var target = {};
1717 var sourceKeys = Object.keys(source);
1718 var key, i;
1719
1720 for (i = 0; i < sourceKeys.length; i++) {
1721 key = sourceKeys[i];
1722 if (excluded.indexOf(key) >= 0) continue;
1723 target[key] = source[key];
1724 }
1725
1726 return target;
1727}
1728
1729function _objectWithoutProperties(source, excluded) {
1730 if (source == null) return {};
1731
1732 var target = _objectWithoutPropertiesLoose(source, excluded);
1733
1734 var key, i;
1735
1736 if (Object.getOwnPropertySymbols) {
1737 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
1738
1739 for (i = 0; i < sourceSymbolKeys.length; i++) {
1740 key = sourceSymbolKeys[i];
1741 if (excluded.indexOf(key) >= 0) continue;
1742 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1743 target[key] = source[key];
1744 }
1745 }
1746
1747 return target;
1748}
1749
1750function _assertThisInitialized(self) {
1751 if (self === void 0) {
1752 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1753 }
1754
1755 return self;
1756}
1757
1758function _toArray(arr) {
1759 return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
1760}
1761
1762function _toConsumableArray(arr) {
1763 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
1764}
1765
1766function _arrayWithoutHoles(arr) {
1767 if (Array.isArray(arr)) {
1768 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
1769
1770 return arr2;
1771 }
1772}
1773
1774function _arrayWithHoles(arr) {
1775 if (Array.isArray(arr)) return arr;
1776}
1777
1778function _iterableToArray(iter) {
1779 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
1780}
1781
1782function _nonIterableSpread() {
1783 throw new TypeError("Invalid attempt to spread non-iterable instance");
1784}
1785
1786function _nonIterableRest() {
1787 throw new TypeError("Invalid attempt to destructure non-iterable instance");
1788}
1789
1790function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
1791 var desc = {};
1792 Object['ke' + 'ys'](descriptor).forEach(function (key) {
1793 desc[key] = descriptor[key];
1794 });
1795 desc.enumerable = !!desc.enumerable;
1796 desc.configurable = !!desc.configurable;
1797
1798 if ('value' in desc || desc.initializer) {
1799 desc.writable = true;
1800 }
1801
1802 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
1803 return decorator(target, property, desc) || desc;
1804 }, desc);
1805
1806 if (context && desc.initializer !== void 0) {
1807 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
1808 desc.initializer = undefined;
1809 }
1810
1811 if (desc.initializer === void 0) {
1812 Object['define' + 'Property'](target, property, desc);
1813 desc = null;
1814 }
1815
1816 return desc;
1817}
1818
1819/* eslint-disable */
1820var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
1821
1822var EXPIRED = Symbol('expired');
1823var debug = d('LC:Expirable');
1824
1825var Expirable =
1826/*#__PURE__*/
1827function () {
1828 function Expirable(value, ttl) {
1829 this.originalValue = value;
1830
1831 if (typeof ttl === 'number') {
1832 this.expiredAt = Date.now() + ttl;
1833 }
1834 }
1835
1836 _createClass(Expirable, [{
1837 key: "value",
1838 get: function get() {
1839 var expired = this.expiredAt && this.expiredAt <= Date.now();
1840 if (expired) debug("expired: ".concat(this.originalValue));
1841 return expired ? EXPIRED : this.originalValue;
1842 }
1843 }]);
1844
1845 return Expirable;
1846}();
1847Expirable.EXPIRED = EXPIRED;
1848
1849var debug$1 = d('LC:Cache');
1850
1851var Cache =
1852/*#__PURE__*/
1853function () {
1854 function Cache() {
1855 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
1856 this.name = name;
1857 this._map = {};
1858 }
1859
1860 var _proto = Cache.prototype;
1861
1862 _proto.get = function get(key) {
1863 var cache = this._map[key];
1864
1865 if (cache) {
1866 var value = cache.value;
1867
1868 if (value !== Expirable.EXPIRED) {
1869 debug$1('[%s] hit: %s', this.name, key);
1870 return value;
1871 }
1872
1873 delete this._map[key];
1874 }
1875
1876 debug$1("[".concat(this.name, "] missed: ").concat(key));
1877 return null;
1878 };
1879
1880 _proto.set = function set(key, value, ttl) {
1881 debug$1('[%s] set: %s %d', this.name, key, ttl);
1882 this._map[key] = new Expirable(value, ttl);
1883 };
1884
1885 return Cache;
1886}();
1887
1888var debug$2 = {
1889 enable: function enable() {
1890 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
1891 return d.enable(namespaces);
1892 },
1893 disable: d.disable
1894};
1895var tryAll = function tryAll(promiseConstructors) {
1896 var promise = new Promise(promiseConstructors[0]);
1897
1898 if (promiseConstructors.length === 1) {
1899 return promise;
1900 }
1901
1902 return promise.catch(function () {
1903 return tryAll(promiseConstructors.slice(1));
1904 });
1905}; // eslint-disable-next-line no-sequences
1906
1907var tap = function tap(interceptor) {
1908 return function (value) {
1909 return interceptor(value), value;
1910 };
1911};
1912var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
1913var map = new WeakMap(); // protected property helper
1914
1915var internal = function internal(object) {
1916 if (!map.has(object)) {
1917 map.set(object, {});
1918 }
1919
1920 return map.get(object);
1921};
1922var compact = function compact(obj, filter) {
1923 if (!isPlainObject(obj)) return obj;
1924 var object = Object.assign({}, obj); // eslint-disable-next-line no-restricted-syntax
1925
1926 for (var prop in object) {
1927 if ({}.hasOwnProperty.call(object, prop)) {
1928 var value = object[prop];
1929
1930 if (value === filter) {
1931 delete object[prop];
1932 } else {
1933 object[prop] = compact(value, filter);
1934 }
1935 }
1936 }
1937
1938 return object;
1939}; // debug utility
1940
1941var removeNull = function removeNull(obj) {
1942 return compact(obj, null);
1943};
1944
1945var trim = function trim(message) {
1946 return removeNull(JSON.parse(JSON.stringify(message)));
1947};
1948var ensureArray = function ensureArray(target) {
1949 if (Array.isArray(target)) {
1950 return target;
1951 }
1952
1953 if (target === undefined || target === null) {
1954 return [];
1955 }
1956
1957 return [target];
1958};
1959var isWeapp = // eslint-disable-next-line no-undef
1960(typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
1961var isCNApp = function isCNApp(appId) {
1962 return appId.slice(-9) !== '-MdYXbMMI';
1963};
1964
1965var _class;
1966var debug$3 = d('LC:WebSocketPlus');
1967var OPEN = 'open';
1968var DISCONNECT = 'disconnect';
1969var RECONNECT = 'reconnect';
1970var RETRY = 'retry';
1971var SCHEDULE = 'schedule';
1972var OFFLINE = 'offline';
1973var ONLINE = 'online';
1974var ERROR = 'error';
1975var MESSAGE = 'message';
1976var HEARTBEAT_TIME = 180000;
1977var TIMEOUT_TIME = 380000;
1978
1979var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
1980 return Math.min(1000 * Math.pow(2, attempt), 300000);
1981};
1982
1983var requireConnected = function requireConnected(target, name, descriptor) {
1984 return Object.assign({}, descriptor, {
1985 value: function requireConnectedWrapper() {
1986 var _descriptor$value;
1987
1988 this.checkConnectionAvailability(name);
1989
1990 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1991 args[_key] = arguments[_key];
1992 }
1993
1994 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
1995 }
1996 });
1997};
1998
1999var WebSocketPlus = (_class =
2000/*#__PURE__*/
2001function (_EventEmitter) {
2002 _inheritsLoose(WebSocketPlus, _EventEmitter);
2003
2004 _createClass(WebSocketPlus, [{
2005 key: "urls",
2006 get: function get() {
2007 return this._urls;
2008 },
2009 set: function set(urls) {
2010 this._urls = ensureArray(urls);
2011 }
2012 }]);
2013
2014 function WebSocketPlus(getUrls, protocol) {
2015 var _this;
2016
2017 if (typeof WebSocket === 'undefined') {
2018 throw new Error('WebSocket is undefined. Polyfill is required in this runtime.');
2019 }
2020
2021 _this = _EventEmitter.call(this) || this;
2022
2023 _this.init();
2024
2025 _this._protocol = protocol;
2026 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
2027 _this._urls = urls;
2028 return _this._open();
2029 }).then(function () {
2030 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
2031
2032 if (global$1.addEventListener) {
2033 _this.__pause = function () {
2034 if (_this.can('pause')) _this.pause();
2035 };
2036
2037 _this.__resume = function () {
2038 if (_this.can('resume')) _this.resume();
2039 };
2040
2041 global$1.addEventListener('offline', _this.__pause);
2042 global$1.addEventListener('online', _this.__resume);
2043 }
2044
2045 _this.open();
2046 }).catch(_this.throw.bind(_assertThisInitialized(_this)));
2047 return _this;
2048 }
2049
2050 var _proto = WebSocketPlus.prototype;
2051
2052 _proto._open = function _open() {
2053 var _this2 = this;
2054
2055 return this._createWs(this._urls, this._protocol).then(function (ws) {
2056 var _this2$_urls = _toArray(_this2._urls),
2057 first = _this2$_urls[0],
2058 reset = _this2$_urls.slice(1);
2059
2060 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
2061 return ws;
2062 });
2063 };
2064
2065 _proto._createWs = function _createWs(urls, protocol) {
2066 var _this3 = this;
2067
2068 return tryAll(urls.map(function (url) {
2069 return function (resolve, reject) {
2070 debug$3("connect [".concat(url, "] ").concat(protocol));
2071 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
2072 ws.binaryType = _this3.binaryType || 'arraybuffer';
2073
2074 ws.onopen = function () {
2075 return resolve(ws);
2076 };
2077
2078 ws.onclose = function (error) {
2079 if (error instanceof Error) {
2080 return reject(error);
2081 } // in browser, error event is useless
2082
2083
2084 return reject(new Error("Failed to connect [".concat(url, "]")));
2085 };
2086
2087 ws.onerror = ws.onclose;
2088 };
2089 })).then(function (ws) {
2090 _this3._ws = ws;
2091 _this3._ws.onclose = _this3._handleClose.bind(_this3);
2092 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
2093 return ws;
2094 });
2095 };
2096
2097 _proto._destroyWs = function _destroyWs() {
2098 var ws = this._ws;
2099 if (!ws) return;
2100 ws.onopen = null;
2101 ws.onclose = null;
2102 ws.onerror = null;
2103 ws.onmessage = null;
2104 this._ws = null;
2105 ws.close();
2106 } // eslint-disable-next-line class-methods-use-this
2107 ;
2108
2109 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
2110 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
2111 payload[_key2 - 3] = arguments[_key2];
2112 }
2113
2114 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
2115 };
2116
2117 _proto.onopen = function onopen() {
2118 this.emit(OPEN);
2119 };
2120
2121 _proto.onconnected = function onconnected() {
2122 this._startConnectionKeeper();
2123 };
2124
2125 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
2126 this._stopConnectionKeeper();
2127
2128 this._destroyWs();
2129
2130 if (to === 'offline' || to === 'disconnected') {
2131 this.emit(DISCONNECT);
2132 }
2133 };
2134
2135 _proto.onpause = function onpause() {
2136 this.emit(OFFLINE);
2137 };
2138
2139 _proto.onbeforeresume = function onbeforeresume() {
2140 this.emit(ONLINE);
2141 };
2142
2143 _proto.onreconnect = function onreconnect() {
2144 this.emit(RECONNECT);
2145 };
2146
2147 _proto.ondisconnected = function ondisconnected(event, from, to) {
2148 var _this4 = this;
2149
2150 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
2151 var delay = DEFAULT_RETRY_STRATEGY.call(null, attempt);
2152 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
2153 this.emit(SCHEDULE, attempt, delay);
2154
2155 if (this.__scheduledRetry) {
2156 clearTimeout(this.__scheduledRetry);
2157 }
2158
2159 this.__scheduledRetry = setTimeout(function () {
2160 if (_this4.is('disconnected')) {
2161 _this4.retry(attempt);
2162 }
2163 }, delay);
2164 };
2165
2166 _proto.onretry = function onretry(event, from, to) {
2167 var _this5 = this;
2168
2169 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
2170 this.emit(RETRY, attempt);
2171
2172 this._open().then(function () {
2173 return _this5.can('reconnect') ? _this5.reconnect() : _this5._destroyWs();
2174 }, function () {
2175 return _this5.can('fail') && _this5.fail(attempt + 1);
2176 });
2177 };
2178
2179 _proto.onerror = function onerror(event, from, to, error) {
2180 this.emit(ERROR, error);
2181 };
2182
2183 _proto.onclose = function onclose() {
2184 if (global$1.removeEventListener) {
2185 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
2186 if (this.__resume) global$1.removeEventListener('online', this.__resume);
2187 }
2188 };
2189
2190 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
2191 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
2192
2193 if (!this.is('connected')) {
2194 var currentState = this.current;
2195 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
2196
2197 if (this.is('disconnected') || this.is('reconnecting')) {
2198 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
2199 }
2200
2201 throw new Error('Connection unavailable');
2202 }
2203 } // jsdoc-ignore-start
2204 ;
2205
2206 _proto. // jsdoc-ignore-end
2207 _ping = function _ping() {
2208 debug$3('ping');
2209
2210 try {
2211 this.ping();
2212 } catch (error) {
2213 console.warn("websocket ping error: ".concat(error.message));
2214 }
2215 };
2216
2217 _proto.ping = function ping() {
2218 if (this._ws.ping) {
2219 this._ws.ping();
2220 } else {
2221 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
2222 }
2223 };
2224
2225 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
2226 var _this6 = this;
2227
2228 debug$3('_postponeTimeoutTimer');
2229
2230 this._clearTimeoutTimers();
2231
2232 this._timeoutTimer = setTimeout(function () {
2233 debug$3('timeout');
2234
2235 _this6.disconnect();
2236 }, TIMEOUT_TIME);
2237 };
2238
2239 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
2240 if (this._timeoutTimer) {
2241 clearTimeout(this._timeoutTimer);
2242 }
2243 };
2244
2245 _proto._startConnectionKeeper = function _startConnectionKeeper() {
2246 debug$3('start connection keeper');
2247 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
2248 var addListener = this._ws.addListener || this._ws.addEventListener;
2249
2250 if (!addListener) {
2251 debug$3('connection keeper disabled due to the lack of #addEventListener.');
2252 return;
2253 }
2254
2255 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
2256 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
2257
2258 this._postponeTimeoutTimer();
2259 };
2260
2261 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
2262 debug$3('stop connection keeper'); // websockets/ws#489
2263
2264 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
2265
2266 if (removeListener) {
2267 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
2268 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
2269
2270 this._clearTimeoutTimers();
2271 }
2272
2273 if (this._heartbeatTimer) {
2274 clearInterval(this._heartbeatTimer);
2275 }
2276 };
2277
2278 _proto._handleClose = function _handleClose(event) {
2279 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
2280
2281 if (this.isFinished()) return;
2282 this.handleClose(event);
2283 };
2284
2285 _proto.handleClose = function handleClose() {
2286 // reconnect
2287 this.disconnect();
2288 } // jsdoc-ignore-start
2289 ;
2290
2291 _proto. // jsdoc-ignore-end
2292 send = function send(data) {
2293 debug$3('send', data);
2294
2295 this._ws.send(data);
2296 };
2297
2298 _proto._handleMessage = function _handleMessage(event) {
2299 debug$3('message', event.data);
2300 this.handleMessage(event.data);
2301 };
2302
2303 _proto.handleMessage = function handleMessage(message) {
2304 this.emit(MESSAGE, message);
2305 };
2306
2307 return WebSocketPlus;
2308}(EventEmitter), (_applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "_ping"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "send"), _class.prototype)), _class);
2309StateMachine.create({
2310 target: WebSocketPlus.prototype,
2311 initial: {
2312 state: 'initialized',
2313 event: 'init',
2314 defer: true
2315 },
2316 terminal: 'closed',
2317 events: [{
2318 name: 'open',
2319 from: 'initialized',
2320 to: 'connected'
2321 }, {
2322 name: 'disconnect',
2323 from: 'connected',
2324 to: 'disconnected'
2325 }, {
2326 name: 'retry',
2327 from: 'disconnected',
2328 to: 'reconnecting'
2329 }, {
2330 name: 'fail',
2331 from: 'reconnecting',
2332 to: 'disconnected'
2333 }, {
2334 name: 'reconnect',
2335 from: 'reconnecting',
2336 to: 'connected'
2337 }, {
2338 name: 'pause',
2339 from: ['connected', 'disconnected', 'reconnecting'],
2340 to: 'offline'
2341 }, {}, {
2342 name: 'resume',
2343 from: 'offline',
2344 to: 'disconnected'
2345 }, {
2346 name: 'close',
2347 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
2348 to: 'closed'
2349 }, {
2350 name: 'throw',
2351 from: '*',
2352 to: 'error'
2353 }]
2354});
2355
2356var error = Object.freeze({
2357 1000: {
2358 name: 'CLOSE_NORMAL'
2359 },
2360 1006: {
2361 name: 'CLOSE_ABNORMAL'
2362 },
2363 4100: {
2364 name: 'APP_NOT_AVAILABLE',
2365 message: 'App not exists or realtime message service is disabled.'
2366 },
2367 4102: {
2368 name: 'SIGNATURE_FAILED',
2369 message: 'Login signature mismatch.'
2370 },
2371 4103: {
2372 name: 'INVALID_LOGIN',
2373 message: 'Malformed clientId.'
2374 },
2375 4105: {
2376 name: 'SESSION_REQUIRED',
2377 message: 'Message sent before session opened.'
2378 },
2379 4107: {
2380 name: 'READ_TIMEOUT'
2381 },
2382 4108: {
2383 name: 'LOGIN_TIMEOUT'
2384 },
2385 4109: {
2386 name: 'FRAME_TOO_LONG'
2387 },
2388 4110: {
2389 name: 'INVALID_ORIGIN',
2390 message: 'Access denied by domain whitelist.'
2391 },
2392 4111: {
2393 name: 'SESSION_CONFLICT'
2394 },
2395 4112: {
2396 name: 'SESSION_TOKEN_EXPIRED'
2397 },
2398 4113: {
2399 name: 'APP_QUOTA_EXCEEDED',
2400 message: 'The daily active users limit exceeded.'
2401 },
2402 4116: {
2403 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
2404 message: 'Command sent too fast.'
2405 },
2406 4200: {
2407 name: 'INTERNAL_ERROR',
2408 message: 'Internal error, please contact LeanCloud for support.'
2409 },
2410 4301: {
2411 name: 'CONVERSATION_API_FAILED',
2412 message: 'Upstream Conversatoin API failed, see error.detail for details.'
2413 },
2414 4302: {
2415 name: 'CONVERSATION_SIGNATURE_FAILED',
2416 message: 'Conversation action signature mismatch.'
2417 },
2418 4303: {
2419 name: 'CONVERSATION_NOT_FOUND'
2420 },
2421 4304: {
2422 name: 'CONVERSATION_FULL'
2423 },
2424 4305: {
2425 name: 'CONVERSATION_REJECTED_BY_APP',
2426 message: 'Conversation action rejected by hook.'
2427 },
2428 4306: {
2429 name: 'CONVERSATION_UPDATE_FAILED'
2430 },
2431 4307: {
2432 name: 'CONVERSATION_READ_ONLY'
2433 },
2434 4308: {
2435 name: 'CONVERSATION_NOT_ALLOWED'
2436 },
2437 4309: {
2438 name: 'CONVERSATION_UPDATE_REJECTED',
2439 message: 'Conversation update rejected because the client is not a member.'
2440 },
2441 4310: {
2442 name: 'CONVERSATION_QUERY_FAILED',
2443 message: 'Conversation query failed because it is too expansive.'
2444 },
2445 4311: {
2446 name: 'CONVERSATION_LOG_FAILED'
2447 },
2448 4312: {
2449 name: 'CONVERSATION_LOG_REJECTED',
2450 message: 'Message query rejected because the client is not a member of the conversation.'
2451 },
2452 4313: {
2453 name: 'SYSTEM_CONVERSATION_REQUIRED'
2454 },
2455 4314: {
2456 name: 'NORMAL_CONVERSATION_REQUIRED'
2457 },
2458 4315: {
2459 name: 'CONVERSATION_BLACKLISTED',
2460 message: 'Blacklisted in the conversation.'
2461 },
2462 4316: {
2463 name: 'TRANSIENT_CONVERSATION_REQUIRED'
2464 },
2465 4317: {
2466 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
2467 },
2468 4318: {
2469 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
2470 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
2471 },
2472 4323: {
2473 name: 'TEMPORARY_CONVERSATION_EXPIRED',
2474 message: 'Temporary conversation expired or does not exist.'
2475 },
2476 4401: {
2477 name: 'INVALID_MESSAGING_TARGET',
2478 message: 'Conversation does not exist or client is not a member.'
2479 },
2480 4402: {
2481 name: 'MESSAGE_REJECTED_BY_APP',
2482 message: 'Message rejected by hook.'
2483 },
2484 4403: {
2485 name: 'MESSAGE_OWNERSHIP_REQUIRED'
2486 },
2487 4404: {
2488 name: 'MESSAGE_NOT_FOUND'
2489 },
2490 4405: {
2491 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
2492 message: 'Message update rejected by hook.'
2493 },
2494 4406: {
2495 name: 'MESSAGE_EDIT_DISABLED'
2496 },
2497 4407: {
2498 name: 'MESSAGE_RECALL_DISABLED'
2499 },
2500 5130: {
2501 name: 'OWNER_PROMOTION_NOT_ALLOWED',
2502 message: "Updating a member's role to owner is not allowed."
2503 }
2504});
2505var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
2506 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
2507}, {}));
2508var createError = function createError(_ref) {
2509 var code = _ref.code,
2510 reason = _ref.reason,
2511 appCode = _ref.appCode,
2512 detail = _ref.detail,
2513 errorMessage = _ref.error;
2514 var message = reason || detail || errorMessage;
2515 var name = reason;
2516
2517 if (!message && error[code]) {
2518 name = error[code].name;
2519 message = error[code].message || name;
2520 }
2521
2522 if (!message) {
2523 message = "Unknow Error: ".concat(code);
2524 }
2525
2526 var err = new Error(message);
2527 return Object.assign(err, {
2528 code: code,
2529 appCode: appCode,
2530 detail: detail,
2531 name: name
2532 });
2533};
2534
2535var debug$4 = d('LC:Connection');
2536var COMMAND_TIMEOUT = 20000;
2537var EXPIRE = Symbol('expire');
2538
2539var Connection =
2540/*#__PURE__*/
2541function (_WebSocketPlus) {
2542 _inheritsLoose(Connection, _WebSocketPlus);
2543
2544 function Connection(getUrl, _ref) {
2545 var _this;
2546
2547 var format = _ref.format,
2548 version = _ref.version;
2549 debug$4('initializing Connection');
2550 var protocolString = "lc.".concat(format, ".").concat(version);
2551
2552 if (!isWeapp) {
2553 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
2554 } else {
2555 _this = _WebSocketPlus.call(this, getUrl().then(function (urls) {
2556 return urls.map(function (url) {
2557 return "".concat(url).concat(url.indexOf('?') === -1 ? '?' : '&', "subprotocol=").concat(encodeURIComponent(protocolString));
2558 });
2559 })) || this;
2560 }
2561
2562 _this._protocalFormat = format;
2563 _this._commands = {};
2564 _this._serialId = 0;
2565 return _assertThisInitialized(_this);
2566 }
2567
2568 var _proto = Connection.prototype;
2569
2570 _proto.send =
2571 /*#__PURE__*/
2572 function () {
2573 var _send = _asyncToGenerator(
2574 /*#__PURE__*/
2575 _regeneratorRuntime.mark(function _callee(command) {
2576 var _this2 = this;
2577
2578 var waitingForRespond,
2579 serialId,
2580 message,
2581 _args = arguments;
2582 return _regeneratorRuntime.wrap(function _callee$(_context) {
2583 while (1) {
2584 switch (_context.prev = _context.next) {
2585 case 0:
2586 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
2587
2588 if (waitingForRespond) {
2589 this._serialId += 1;
2590 serialId = this._serialId;
2591 command.i = serialId; // eslint-disable-line no-param-reassign
2592 }
2593
2594 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
2595
2596 if (this._protocalFormat === 'proto2base64') {
2597 message = command.toBase64();
2598 } else if (command.toArrayBuffer) {
2599 message = command.toArrayBuffer();
2600 }
2601
2602 if (message) {
2603 _context.next = 6;
2604 break;
2605 }
2606
2607 throw new TypeError("".concat(command, " is not a GenericCommand"));
2608
2609 case 6:
2610 _WebSocketPlus.prototype.send.call(this, message);
2611
2612 if (waitingForRespond) {
2613 _context.next = 9;
2614 break;
2615 }
2616
2617 return _context.abrupt("return", undefined);
2618
2619 case 9:
2620 return _context.abrupt("return", new Promise(function (resolve, reject) {
2621 _this2._commands[serialId] = {
2622 resolve: resolve,
2623 reject: reject,
2624 timeout: setTimeout(function () {
2625 if (_this2._commands[serialId]) {
2626 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
2627 reject(createError({
2628 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
2629 name: 'COMMAND_TIMEOUT'
2630 }));
2631 delete _this2._commands[serialId];
2632 }
2633 }, COMMAND_TIMEOUT)
2634 };
2635 }));
2636
2637 case 10:
2638 case "end":
2639 return _context.stop();
2640 }
2641 }
2642 }, _callee, this);
2643 }));
2644
2645 function send(_x) {
2646 return _send.apply(this, arguments);
2647 }
2648
2649 return send;
2650 }();
2651
2652 _proto.handleMessage = function handleMessage(msg) {
2653 var message;
2654
2655 try {
2656 message = GenericCommand.decode(msg);
2657 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
2658 } catch (e) {
2659 console.warn('Decode message failed:', e.message, msg);
2660 return;
2661 }
2662
2663 var serialId = message.i;
2664
2665 if (serialId) {
2666 if (this._commands[serialId]) {
2667 clearTimeout(this._commands[serialId].timeout);
2668
2669 if (message.cmd === CommandType.error) {
2670 this._commands[serialId].reject(createError(message.errorMessage));
2671 } else {
2672 this._commands[serialId].resolve(message);
2673 }
2674
2675 delete this._commands[serialId];
2676 } else {
2677 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
2678 }
2679 } else {
2680 switch (message.cmd) {
2681 case CommandType.error:
2682 {
2683 this.emit(ERROR, createError(message.errorMessage));
2684 return;
2685 }
2686
2687 case CommandType.goaway:
2688 {
2689 this.emit(EXPIRE);
2690 return;
2691 }
2692
2693 default:
2694 {
2695 this.emit(MESSAGE, message);
2696 }
2697 }
2698 }
2699 };
2700
2701 _proto.ping = function ping() {
2702 return this.send(new GenericCommand({
2703 cmd: CommandType.echo
2704 })).catch(function (error) {
2705 return debug$4('ping failed:', error);
2706 });
2707 };
2708
2709 return Connection;
2710}(WebSocketPlus);
2711
2712var applyDecorators = function applyDecorators(decorators, target) {
2713 if (decorators) {
2714 decorators.forEach(function (decorator) {
2715 try {
2716 decorator(target);
2717 } catch (error) {
2718 if (decorator._pluginName) {
2719 error.message += "[".concat(decorator._pluginName, "]");
2720 }
2721
2722 throw error;
2723 }
2724 });
2725 }
2726};
2727var applyDispatcher = function applyDispatcher(dispatchers, payload) {
2728 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
2729 return resultPromise.then(function (shouldDispatch) {
2730 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
2731 }).catch(function (error) {
2732 if (dispatcher._pluginName) {
2733 // eslint-disable-next-line no-param-reassign
2734 error.message += "[".concat(dispatcher._pluginName, "]");
2735 }
2736
2737 throw error;
2738 });
2739 }, Promise.resolve(true));
2740};
2741
2742var version = "5.0.0-beta.0";
2743
2744var debug$5 = d('LC:Realtime');
2745var debugRequest = d('LC:request');
2746var routerCache = new Cache('push-router');
2747
2748var Realtime =
2749/*#__PURE__*/
2750function (_EventEmitter) {
2751 _inheritsLoose(Realtime, _EventEmitter);
2752
2753 /**
2754 * @extends EventEmitter
2755 * @param {Object} options
2756 * @param {String} options.appId
2757 * @param {String} options.appKey (since 4.0.0)
2758 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
2759 * @param {Boolean} [options.pushOfflineMessages=false] 启用推送离线消息模式(默认为发送未读消息通知模式)
2760 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
2761 * 适用于 WebSocket 实现不支持二进制数据格式的情况
2762 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
2763 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
2764 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
2765 */
2766 function Realtime(_ref) {
2767 var _this2;
2768
2769 var plugins = _ref.plugins,
2770 options = _objectWithoutProperties(_ref, ["plugins"]);
2771
2772 debug$5('initializing Realtime %s %O', version, options);
2773 _this2 = _EventEmitter.call(this) || this;
2774
2775 if (typeof options.appId !== 'string') {
2776 throw new TypeError("appId [".concat(options.appId, "] is not a string"));
2777 }
2778
2779 if (typeof options.appKey !== 'string') {
2780 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
2781 }
2782
2783 if (isCNApp(options.appId)) {
2784 if (!options.server) {
2785 throw new TypeError("server option is required for apps from CN region");
2786 }
2787 }
2788
2789 _this2._options = Object.assign({
2790 appId: undefined,
2791 appKey: undefined,
2792 pushOfflineMessages: false,
2793 noBinary: false,
2794 ssl: true,
2795 RTMServerName: process.env.RTM_SERVER_NAME // undocumented on purpose, internal use only
2796
2797 }, options);
2798 _this2._cache = new Cache('endpoints');
2799
2800 var _this = internal(_assertThisInitialized(_this2));
2801
2802 _this.clients = new Set();
2803 _this.pendingClients = new Set();
2804 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
2805 debug$5('Using plugins %o', mergedPlugins.map(function (plugin) {
2806 return plugin.name;
2807 }));
2808 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
2809 // eslint-disable-next-line no-restricted-syntax
2810 for (var hook in plugin) {
2811 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
2812 if (plugin.name) {
2813 ensureArray(plugin[hook]).forEach(function (value) {
2814 // eslint-disable-next-line no-param-reassign
2815 value._pluginName = plugin.name;
2816 });
2817 } // eslint-disable-next-line no-param-reassign
2818
2819
2820 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
2821 }
2822 }
2823
2824 return result;
2825 }, {}); // onRealtimeCreate hook
2826
2827 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
2828 return _this2;
2829 }
2830
2831 var _proto = Realtime.prototype;
2832
2833 _proto._request =
2834 /*#__PURE__*/
2835 function () {
2836 var _request2 = _asyncToGenerator(
2837 /*#__PURE__*/
2838 _regeneratorRuntime.mark(function _callee(_ref2) {
2839 var method, _ref2$version, version, path, query, headers, _ref2$data, data, _this$_options, appId, server, _ref3, api, url;
2840
2841 return _regeneratorRuntime.wrap(function _callee$(_context) {
2842 while (1) {
2843 switch (_context.prev = _context.next) {
2844 case 0:
2845 method = _ref2.method, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, _ref2$data = _ref2.data, data = _ref2$data === void 0 ? {} : _ref2$data;
2846 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
2847 _context.next = 4;
2848 return this.constructor._getServerUrls({
2849 appId: appId,
2850 server: server
2851 });
2852
2853 case 4:
2854 _ref3 = _context.sent;
2855 api = _ref3.api;
2856 url = "".concat(api, "/").concat(version).concat(path);
2857 debugRequest('Req: %O %O %O', method, url, {
2858 query: query,
2859 headers: headers,
2860 data: data
2861 });
2862 return _context.abrupt("return", superagent(method, url).set(_objectSpread({
2863 'X-LC-Id': this._options.appId,
2864 'X-LC-Key': this._options.appKey
2865 }, headers)).query(query).send(data).then(function (response) {
2866 debugRequest('Res: %O %O %O', url, response.status, response.body);
2867 return response.body;
2868 }, function (error) {
2869 debugRequest('Error: %O %O %O', url, error.response.status, error.response.body);
2870
2871 if (error.response && error.response.body && error.response.body.code) {
2872 throw createError(error.response.body);
2873 }
2874
2875 throw error;
2876 }));
2877
2878 case 9:
2879 case "end":
2880 return _context.stop();
2881 }
2882 }
2883 }, _callee, this);
2884 }));
2885
2886 function _request(_x) {
2887 return _request2.apply(this, arguments);
2888 }
2889
2890 return _request;
2891 }();
2892
2893 _proto._open = function _open() {
2894 var _this3 = this;
2895
2896 if (this._openPromise) return this._openPromise;
2897 var format = 'protobuf2';
2898
2899 if (this._options.noBinary) {
2900 // 不发送 binary data,fallback to base64 string
2901 format = 'proto2base64';
2902 }
2903
2904 var version = 3;
2905
2906 if (this._options.pushOfflineMessages) {
2907 // 不推送离线消息,而是发送对话的未读通知
2908 version = 1;
2909 }
2910
2911 var protocol = {
2912 format: format,
2913 version: version
2914 };
2915 this._openPromise = new Promise(function (resolve, reject) {
2916 debug$5('No connection established, create a new one.');
2917 var connection = new Connection(function () {
2918 return _this3._getRTMServers(_this3._options);
2919 }, protocol);
2920 connection.on(OPEN, function () {
2921 return resolve(connection);
2922 }).on(ERROR, reject).on(EXPIRE,
2923 /*#__PURE__*/
2924 _asyncToGenerator(
2925 /*#__PURE__*/
2926 _regeneratorRuntime.mark(function _callee2() {
2927 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
2928 while (1) {
2929 switch (_context2.prev = _context2.next) {
2930 case 0:
2931 debug$5('Connection expired. Refresh endpoints.');
2932
2933 _this3._cache.set('endpoints', null, 0);
2934
2935 _context2.next = 4;
2936 return _this3._getRTMServers(_this3._options);
2937
2938 case 4:
2939 connection.urls = _context2.sent;
2940 connection.disconnect();
2941
2942 case 6:
2943 case "end":
2944 return _context2.stop();
2945 }
2946 }
2947 }, _callee2, this);
2948 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
2949 /**
2950 * 连接断开。
2951 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
2952 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
2953 * @event Realtime#DISCONNECT
2954 */
2955
2956 /**
2957 * 计划在一段时间后尝试重新连接
2958 * @event Realtime#SCHEDULE
2959 * @param {Number} attempt 尝试重连的次数
2960 * @param {Number} delay 延迟的毫秒数
2961 */
2962
2963 /**
2964 * 正在尝试重新连接
2965 * @event Realtime#RETRY
2966 * @param {Number} attempt 尝试重连的次数
2967 */
2968
2969 /**
2970 * 连接恢复正常。
2971 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
2972 * @event Realtime#RECONNECT
2973 */
2974
2975 /**
2976 * 客户端连接断开
2977 * @event IMClient#DISCONNECT
2978 * @see Realtime#event:DISCONNECT
2979 * @since 3.2.0
2980 */
2981
2982 /**
2983 * 计划在一段时间后尝试重新连接
2984 * @event IMClient#SCHEDULE
2985 * @param {Number} attempt 尝试重连的次数
2986 * @param {Number} delay 延迟的毫秒数
2987 * @since 3.2.0
2988 */
2989
2990 /**
2991 * 正在尝试重新连接
2992 * @event IMClient#RETRY
2993 * @param {Number} attempt 尝试重连的次数
2994 * @since 3.2.0
2995 */
2996
2997 /**
2998 * 客户端进入离线状态。
2999 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
3000 * @event Realtime#OFFLINE
3001 * @since 3.4.0
3002 */
3003
3004 /**
3005 * 客户端恢复在线状态
3006 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
3007 * @event Realtime#ONLINE
3008 * @since 3.4.0
3009 */
3010
3011 /**
3012 * 进入离线状态。
3013 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
3014 * @event IMClient#OFFLINE
3015 * @since 3.4.0
3016 */
3017
3018 /**
3019 * 恢复在线状态
3020 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
3021 * @event IMClient#ONLINE
3022 * @since 3.4.0
3023 */
3024 // event proxy
3025
3026 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
3027 return connection.on(event, function () {
3028 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
3029 payload[_key] = arguments[_key];
3030 }
3031
3032 debug$5("".concat(event, " event emitted. %o"), payload);
3033
3034 _this3.emit.apply(_this3, [event].concat(payload));
3035
3036 if (event !== RECONNECT) {
3037 internal(_this3).clients.forEach(function (client) {
3038 client.emit.apply(client, [event].concat(payload));
3039 });
3040 }
3041 });
3042 }); // override handleClose
3043
3044 connection.handleClose = function handleClose(event) {
3045 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
3046 return errorCode === event.code;
3047 });
3048
3049 if (isFatal) {
3050 // in these cases, SDK should throw.
3051 this.throw(createError(event));
3052 } else {
3053 // reconnect
3054 this.disconnect();
3055 }
3056 };
3057
3058 internal(_this3).connection = connection;
3059 });
3060 return this._openPromise;
3061 };
3062
3063 _proto._getRTMServers =
3064 /*#__PURE__*/
3065 function () {
3066 var _getRTMServers2 = _asyncToGenerator(
3067 /*#__PURE__*/
3068 _regeneratorRuntime.mark(function _callee3(options) {
3069 var info, cachedEndPoints;
3070 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
3071 while (1) {
3072 switch (_context3.prev = _context3.next) {
3073 case 0:
3074 if (!options.RTMServers) {
3075 _context3.next = 2;
3076 break;
3077 }
3078
3079 return _context3.abrupt("return", shuffle(ensureArray(options.RTMServers)));
3080
3081 case 2:
3082 cachedEndPoints = this._cache.get('endpoints');
3083
3084 if (!cachedEndPoints) {
3085 _context3.next = 9;
3086 break;
3087 }
3088
3089 _context3.next = 6;
3090 return cachedEndPoints;
3091
3092 case 6:
3093 info = _context3.sent;
3094 _context3.next = 13;
3095 break;
3096
3097 case 9:
3098 _context3.next = 11;
3099 return this.constructor._fetchRTMServers(options);
3100
3101 case 11:
3102 info = _context3.sent;
3103
3104 this._cache.set('endpoints', info, info.ttl * 1000);
3105
3106 case 13:
3107 debug$5('endpoint info: %O', info);
3108 return _context3.abrupt("return", [info.server, info.secondary]);
3109
3110 case 15:
3111 case "end":
3112 return _context3.stop();
3113 }
3114 }
3115 }, _callee3, this);
3116 }));
3117
3118 function _getRTMServers(_x2) {
3119 return _getRTMServers2.apply(this, arguments);
3120 }
3121
3122 return _getRTMServers;
3123 }();
3124
3125 Realtime._getServerUrls =
3126 /*#__PURE__*/
3127 function () {
3128 var _getServerUrls2 = _asyncToGenerator(
3129 /*#__PURE__*/
3130 _regeneratorRuntime.mark(function _callee4(_ref5) {
3131 var appId, server, cachedRouter, defaultProtocol;
3132 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
3133 while (1) {
3134 switch (_context4.prev = _context4.next) {
3135 case 0:
3136 appId = _ref5.appId, server = _ref5.server;
3137 debug$5('fetch server urls');
3138
3139 if (!server) {
3140 _context4.next = 6;
3141 break;
3142 }
3143
3144 if (!(typeof server !== 'string')) {
3145 _context4.next = 5;
3146 break;
3147 }
3148
3149 return _context4.abrupt("return", server);
3150
3151 case 5:
3152 return _context4.abrupt("return", {
3153 RTMRouter: server,
3154 api: server
3155 });
3156
3157 case 6:
3158 cachedRouter = routerCache.get(appId);
3159
3160 if (!cachedRouter) {
3161 _context4.next = 9;
3162 break;
3163 }
3164
3165 return _context4.abrupt("return", cachedRouter);
3166
3167 case 9:
3168 defaultProtocol = 'https://';
3169 return _context4.abrupt("return", superagent.get('https://app-router.com/2/route').query({
3170 appId: appId
3171 }).timeout(20000).then(function (res) {
3172 return res.body;
3173 }).then(tap(debug$5)).then(function (_ref6) {
3174 var RTMRouterServer = _ref6.rtm_router_server,
3175 APIServer = _ref6.api_server,
3176 _ref6$ttl = _ref6.ttl,
3177 ttl = _ref6$ttl === void 0 ? 3600 : _ref6$ttl;
3178
3179 if (!RTMRouterServer) {
3180 throw new Error('rtm router not exists');
3181 }
3182
3183 var serverUrls = {
3184 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
3185 api: "".concat(defaultProtocol).concat(APIServer)
3186 };
3187 routerCache.set(appId, serverUrls, ttl * 1000);
3188 return serverUrls;
3189 }).catch(function () {
3190 var id = appId.slice(0, 8).toLowerCase();
3191 var domain = 'lncldglobal.com';
3192 return {
3193 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
3194 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
3195 };
3196 }));
3197
3198 case 11:
3199 case "end":
3200 return _context4.stop();
3201 }
3202 }
3203 }, _callee4, this);
3204 }));
3205
3206 function _getServerUrls(_x3) {
3207 return _getServerUrls2.apply(this, arguments);
3208 }
3209
3210 return _getServerUrls;
3211 }();
3212
3213 Realtime._fetchRTMServers = function _fetchRTMServers(_ref7) {
3214 var appId = _ref7.appId,
3215 ssl = _ref7.ssl,
3216 server = _ref7.server,
3217 RTMServerName = _ref7.RTMServerName;
3218 debug$5('fetch endpoint info');
3219 return this._getServerUrls({
3220 appId: appId,
3221 server: server
3222 }).then(tap(debug$5)).then(function (_ref8) {
3223 var RTMRouter = _ref8.RTMRouter;
3224 return superagent.get("".concat(RTMRouter, "/v1/route")).query({
3225 appId: appId,
3226 secure: ssl,
3227 features: isWeapp ? 'wechat' : undefined,
3228 server: RTMServerName,
3229 _t: Date.now()
3230 }).timeout(20000).then(function (res) {
3231 return res.body;
3232 }).then(tap(debug$5));
3233 });
3234 };
3235
3236 _proto._close = function _close() {
3237 if (this._openPromise) {
3238 this._openPromise.then(function (connection) {
3239 return connection.close();
3240 });
3241 }
3242
3243 delete this._openPromise;
3244 }
3245 /**
3246 * 手动进行重连。
3247 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
3248 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
3249 */
3250 ;
3251
3252 _proto.retry = function retry() {
3253 var _internal = internal(this),
3254 connection = _internal.connection;
3255
3256 if (!connection) {
3257 throw new Error('no connection established');
3258 }
3259
3260 if (connection.cannot('retry')) {
3261 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
3262 }
3263
3264 return connection.retry();
3265 }
3266 /**
3267 * 暂停,使 SDK 进入离线状态。
3268 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
3269 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
3270 *
3271 * @since 3.4.0
3272 * @see Realtime#event:OFFLINE
3273 */
3274 ;
3275
3276 _proto.pause = function pause() {
3277 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
3278 // 因此不像 retry,这个方法应该尽可能 loose
3279 var _internal2 = internal(this),
3280 connection = _internal2.connection;
3281
3282 if (!connection) return;
3283 if (connection.can('pause')) connection.pause();
3284 }
3285 /**
3286 * 恢复在线状态。
3287 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
3288 *
3289 * @since 3.4.0
3290 * @see Realtime#event:ONLINE
3291 */
3292 ;
3293
3294 _proto.resume = function resume() {
3295 // 与 pause 一样,这个方法应该尽可能 loose
3296 var _internal3 = internal(this),
3297 connection = _internal3.connection;
3298
3299 if (!connection) return;
3300 if (connection.can('resume')) connection.resume();
3301 };
3302
3303 _proto._registerPending = function _registerPending(value) {
3304 internal(this).pendingClients.add(value);
3305 };
3306
3307 _proto._deregisterPending = function _deregisterPending(client) {
3308 internal(this).pendingClients.delete(client);
3309 };
3310
3311 _proto._register = function _register(client) {
3312 internal(this).clients.add(client);
3313 };
3314
3315 _proto._deregister = function _deregister(client) {
3316 var _this = internal(this);
3317
3318 _this.clients.delete(client);
3319
3320 if (_this.clients.size + _this.pendingClients.size === 0) {
3321 this._close();
3322 }
3323 };
3324
3325 _proto._dispatchCommand = function _dispatchCommand(command) {
3326 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
3327 // no plugin handled this command
3328 if (shouldDispatch) return debug$5('[WARN] Unexpected message received: %O', trim(command));
3329 return false;
3330 });
3331 };
3332
3333 return Realtime;
3334}(EventEmitter);
3335
3336var polyfilledPromise = Promise;
3337
3338exports.EventEmitter = EventEmitter;
3339exports.Protocals = message;
3340exports.Promise = polyfilledPromise;
3341exports.Realtime = Realtime;
3342exports.debug = debug$2;
3343//# sourceMappingURL=realtime-core.js.map