UNPKG

38.6 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5/*! *****************************************************************************
6Copyright (c) Microsoft Corporation.
7
8Permission to use, copy, modify, and/or distribute this software for any
9purpose with or without fee is hereby granted.
10
11THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17PERFORMANCE OF THIS SOFTWARE.
18***************************************************************************** */
19/* global Reflect, Promise */
20
21var extendStatics = function(d, b) {
22 extendStatics = Object.setPrototypeOf ||
23 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
25 return extendStatics(d, b);
26};
27
28function __extends(d, b) {
29 extendStatics(d, b);
30 function __() { this.constructor = d; }
31 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32}
33
34var __assign = function() {
35 __assign = Object.assign || function __assign(t) {
36 for (var s, i = 1, n = arguments.length; i < n; i++) {
37 s = arguments[i];
38 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
39 }
40 return t;
41 };
42 return __assign.apply(this, arguments);
43};
44
45function __rest(s, e) {
46 var t = {};
47 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
48 t[p] = s[p];
49 if (s != null && typeof Object.getOwnPropertySymbols === "function")
50 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
51 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
52 t[p[i]] = s[p[i]];
53 }
54 return t;
55}
56
57function __awaiter(thisArg, _arguments, P, generator) {
58 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
59 return new (P || (P = Promise))(function (resolve, reject) {
60 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
61 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
62 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
63 step((generator = generator.apply(thisArg, _arguments || [])).next());
64 });
65}
66
67function __generator(thisArg, body) {
68 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
69 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
70 function verb(n) { return function (v) { return step([n, v]); }; }
71 function step(op) {
72 if (f) throw new TypeError("Generator is already executing.");
73 while (_) try {
74 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;
75 if (y = 0, t) op = [op[0] & 2, t.value];
76 switch (op[0]) {
77 case 0: case 1: t = op; break;
78 case 4: _.label++; return { value: op[1], done: false };
79 case 5: _.label++; y = op[1]; op = [0]; continue;
80 case 7: op = _.ops.pop(); _.trys.pop(); continue;
81 default:
82 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
83 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
84 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
85 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
86 if (t[2]) _.ops.pop();
87 _.trys.pop(); continue;
88 }
89 op = body.call(thisArg, _);
90 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
91 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
92 }
93}
94
95var PROVIDER = "lc_weapp";
96var PLATFORM = "weixin";
97function getLoginCode() {
98 return new Promise(function (resolve, reject) {
99 wx.login({
100 success: function (res) {
101 return res.code ? resolve(res.code) : reject(new Error(res.errMsg));
102 },
103 fail: function (_a) {
104 var errMsg = _a.errMsg;
105 return reject(new Error(errMsg));
106 },
107 });
108 });
109}
110var getAuthInfo = function (_a) {
111 var _b = _a === void 0 ? {} : _a, _c = _b.platform, platform = _c === void 0 ? PLATFORM : _c, _d = _b.preferUnionId, preferUnionId = _d === void 0 ? false : _d, _e = _b.asMainAccount, asMainAccount = _e === void 0 ? false : _e;
112 return __awaiter(this, void 0, void 0, function () {
113 var code, authData;
114 return __generator(this, function (_f) {
115 switch (_f.label) {
116 case 0: return [4 /*yield*/, getLoginCode()];
117 case 1:
118 code = _f.sent();
119 authData = { code: code };
120 if (preferUnionId) {
121 authData.platform = platform;
122 authData.main_account = asMainAccount;
123 }
124 return [2 /*return*/, {
125 authData: authData,
126 platform: platform,
127 provider: PROVIDER,
128 }];
129 }
130 });
131 });
132};
133
134var storage = {
135 getItem: function (key) {
136 return wx.getStorageSync(key);
137 },
138 setItem: function (key, value) {
139 return wx.setStorageSync(key, value);
140 },
141 removeItem: function (key) {
142 return wx.removeStorageSync(key);
143 },
144 clear: function () {
145 return wx.clearStorageSync();
146 },
147};
148
149/*! *****************************************************************************
150Copyright (c) Microsoft Corporation.
151
152Permission to use, copy, modify, and/or distribute this software for any
153purpose with or without fee is hereby granted.
154
155THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
156REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
157AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
158INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
159LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
160OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
161PERFORMANCE OF THIS SOFTWARE.
162***************************************************************************** */
163/* global Reflect, Promise */
164
165var extendStatics$1 = function(d, b) {
166 extendStatics$1 = Object.setPrototypeOf ||
167 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
168 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
169 return extendStatics$1(d, b);
170};
171
172function __extends$1(d, b) {
173 extendStatics$1(d, b);
174 function __() { this.constructor = d; }
175 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
176}
177
178var AbortError = /** @class */ (function (_super) {
179 __extends$1(AbortError, _super);
180 function AbortError() {
181 var _this = _super !== null && _super.apply(this, arguments) || this;
182 _this.name = "AbortError";
183 return _this;
184 }
185 return AbortError;
186}(Error));
187
188var request = function (url, options) {
189 if (options === void 0) { options = {}; }
190 var method = options.method, data = options.data, headers = options.headers, signal = options.signal;
191 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
192 return Promise.reject(new AbortError("Request aborted"));
193 }
194 return new Promise(function (resolve, reject) {
195 var task = wx.request({
196 url: url,
197 method: method,
198 data: data,
199 header: headers,
200 complete: function (res) {
201 signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener);
202 if (!res.statusCode) {
203 reject(new Error(res.errMsg));
204 return;
205 }
206 resolve({
207 ok: !(res.statusCode >= 400),
208 status: res.statusCode,
209 headers: res.header,
210 data: res.data,
211 });
212 },
213 });
214 var abortListener = function () {
215 reject(new AbortError("Request aborted"));
216 task.abort();
217 };
218 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
219 });
220};
221var upload = function (url, file, options) {
222 if (options === void 0) { options = {}; }
223 var headers = options.headers, data = options.data, onprogress = options.onprogress, signal = options.signal;
224 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
225 return Promise.reject(new AbortError("Request aborted"));
226 }
227 if (!(file && file.data && file.data.uri)) {
228 return Promise.reject(new TypeError("File data must be an object like { uri: localPath }."));
229 }
230 return new Promise(function (resolve, reject) {
231 var task = wx.uploadFile({
232 url: url,
233 header: headers,
234 filePath: file.data.uri,
235 name: file.field,
236 formData: data,
237 success: function (response) {
238 var status = response.statusCode, data = response.data, rest = __rest(response, ["statusCode", "data"]);
239 resolve(__assign(__assign({}, rest), { data: typeof data === "string" ? JSON.parse(data) : data, status: status, ok: !(status >= 400) }));
240 },
241 fail: function (response) {
242 reject(new Error(response.errMsg));
243 },
244 complete: function () {
245 signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener);
246 },
247 });
248 var abortListener = function () {
249 reject(new AbortError("Request aborted"));
250 task.abort();
251 };
252 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
253 if (onprogress) {
254 task.onProgressUpdate(function (event) {
255 return onprogress({
256 loaded: event.totalBytesSent,
257 total: event.totalBytesExpectedToSend,
258 percent: event.progress,
259 });
260 });
261 }
262 });
263};
264
265/**
266 * @author Toru Nagashima <https://github.com/mysticatea>
267 * @copyright 2015 Toru Nagashima. All rights reserved.
268 * See LICENSE file in root directory for full license.
269 */
270/**
271 * @typedef {object} PrivateData
272 * @property {EventTarget} eventTarget The event target.
273 * @property {{type:string}} event The original event object.
274 * @property {number} eventPhase The current event phase.
275 * @property {EventTarget|null} currentTarget The current event target.
276 * @property {boolean} canceled The flag to prevent default.
277 * @property {boolean} stopped The flag to stop propagation.
278 * @property {boolean} immediateStopped The flag to stop propagation immediately.
279 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
280 * @property {number} timeStamp The unix time.
281 * @private
282 */
283
284/**
285 * Private data for event wrappers.
286 * @type {WeakMap<Event, PrivateData>}
287 * @private
288 */
289const privateData = new WeakMap();
290
291/**
292 * Cache for wrapper classes.
293 * @type {WeakMap<Object, Function>}
294 * @private
295 */
296const wrappers = new WeakMap();
297
298/**
299 * Get private data.
300 * @param {Event} event The event object to get private data.
301 * @returns {PrivateData} The private data of the event.
302 * @private
303 */
304function pd(event) {
305 const retv = privateData.get(event);
306 console.assert(
307 retv != null,
308 "'this' is expected an Event object, but got",
309 event
310 );
311 return retv
312}
313
314/**
315 * https://dom.spec.whatwg.org/#set-the-canceled-flag
316 * @param data {PrivateData} private data.
317 */
318function setCancelFlag(data) {
319 if (data.passiveListener != null) {
320 if (
321 typeof console !== "undefined" &&
322 typeof console.error === "function"
323 ) {
324 console.error(
325 "Unable to preventDefault inside passive event listener invocation.",
326 data.passiveListener
327 );
328 }
329 return
330 }
331 if (!data.event.cancelable) {
332 return
333 }
334
335 data.canceled = true;
336 if (typeof data.event.preventDefault === "function") {
337 data.event.preventDefault();
338 }
339}
340
341/**
342 * @see https://dom.spec.whatwg.org/#interface-event
343 * @private
344 */
345/**
346 * The event wrapper.
347 * @constructor
348 * @param {EventTarget} eventTarget The event target of this dispatching.
349 * @param {Event|{type:string}} event The original event to wrap.
350 */
351function Event(eventTarget, event) {
352 privateData.set(this, {
353 eventTarget,
354 event,
355 eventPhase: 2,
356 currentTarget: eventTarget,
357 canceled: false,
358 stopped: false,
359 immediateStopped: false,
360 passiveListener: null,
361 timeStamp: event.timeStamp || Date.now(),
362 });
363
364 // https://heycam.github.io/webidl/#Unforgeable
365 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
366
367 // Define accessors
368 const keys = Object.keys(event);
369 for (let i = 0; i < keys.length; ++i) {
370 const key = keys[i];
371 if (!(key in this)) {
372 Object.defineProperty(this, key, defineRedirectDescriptor(key));
373 }
374 }
375}
376
377// Should be enumerable, but class methods are not enumerable.
378Event.prototype = {
379 /**
380 * The type of this event.
381 * @type {string}
382 */
383 get type() {
384 return pd(this).event.type
385 },
386
387 /**
388 * The target of this event.
389 * @type {EventTarget}
390 */
391 get target() {
392 return pd(this).eventTarget
393 },
394
395 /**
396 * The target of this event.
397 * @type {EventTarget}
398 */
399 get currentTarget() {
400 return pd(this).currentTarget
401 },
402
403 /**
404 * @returns {EventTarget[]} The composed path of this event.
405 */
406 composedPath() {
407 const currentTarget = pd(this).currentTarget;
408 if (currentTarget == null) {
409 return []
410 }
411 return [currentTarget]
412 },
413
414 /**
415 * Constant of NONE.
416 * @type {number}
417 */
418 get NONE() {
419 return 0
420 },
421
422 /**
423 * Constant of CAPTURING_PHASE.
424 * @type {number}
425 */
426 get CAPTURING_PHASE() {
427 return 1
428 },
429
430 /**
431 * Constant of AT_TARGET.
432 * @type {number}
433 */
434 get AT_TARGET() {
435 return 2
436 },
437
438 /**
439 * Constant of BUBBLING_PHASE.
440 * @type {number}
441 */
442 get BUBBLING_PHASE() {
443 return 3
444 },
445
446 /**
447 * The target of this event.
448 * @type {number}
449 */
450 get eventPhase() {
451 return pd(this).eventPhase
452 },
453
454 /**
455 * Stop event bubbling.
456 * @returns {void}
457 */
458 stopPropagation() {
459 const data = pd(this);
460
461 data.stopped = true;
462 if (typeof data.event.stopPropagation === "function") {
463 data.event.stopPropagation();
464 }
465 },
466
467 /**
468 * Stop event bubbling.
469 * @returns {void}
470 */
471 stopImmediatePropagation() {
472 const data = pd(this);
473
474 data.stopped = true;
475 data.immediateStopped = true;
476 if (typeof data.event.stopImmediatePropagation === "function") {
477 data.event.stopImmediatePropagation();
478 }
479 },
480
481 /**
482 * The flag to be bubbling.
483 * @type {boolean}
484 */
485 get bubbles() {
486 return Boolean(pd(this).event.bubbles)
487 },
488
489 /**
490 * The flag to be cancelable.
491 * @type {boolean}
492 */
493 get cancelable() {
494 return Boolean(pd(this).event.cancelable)
495 },
496
497 /**
498 * Cancel this event.
499 * @returns {void}
500 */
501 preventDefault() {
502 setCancelFlag(pd(this));
503 },
504
505 /**
506 * The flag to indicate cancellation state.
507 * @type {boolean}
508 */
509 get defaultPrevented() {
510 return pd(this).canceled
511 },
512
513 /**
514 * The flag to be composed.
515 * @type {boolean}
516 */
517 get composed() {
518 return Boolean(pd(this).event.composed)
519 },
520
521 /**
522 * The unix time of this event.
523 * @type {number}
524 */
525 get timeStamp() {
526 return pd(this).timeStamp
527 },
528
529 /**
530 * The target of this event.
531 * @type {EventTarget}
532 * @deprecated
533 */
534 get srcElement() {
535 return pd(this).eventTarget
536 },
537
538 /**
539 * The flag to stop event bubbling.
540 * @type {boolean}
541 * @deprecated
542 */
543 get cancelBubble() {
544 return pd(this).stopped
545 },
546 set cancelBubble(value) {
547 if (!value) {
548 return
549 }
550 const data = pd(this);
551
552 data.stopped = true;
553 if (typeof data.event.cancelBubble === "boolean") {
554 data.event.cancelBubble = true;
555 }
556 },
557
558 /**
559 * The flag to indicate cancellation state.
560 * @type {boolean}
561 * @deprecated
562 */
563 get returnValue() {
564 return !pd(this).canceled
565 },
566 set returnValue(value) {
567 if (!value) {
568 setCancelFlag(pd(this));
569 }
570 },
571
572 /**
573 * Initialize this event object. But do nothing under event dispatching.
574 * @param {string} type The event type.
575 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
576 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
577 * @deprecated
578 */
579 initEvent() {
580 // Do nothing.
581 },
582};
583
584// `constructor` is not enumerable.
585Object.defineProperty(Event.prototype, "constructor", {
586 value: Event,
587 configurable: true,
588 writable: true,
589});
590
591// Ensure `event instanceof window.Event` is `true`.
592if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
593 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
594
595 // Make association for wrappers.
596 wrappers.set(window.Event.prototype, Event);
597}
598
599/**
600 * Get the property descriptor to redirect a given property.
601 * @param {string} key Property name to define property descriptor.
602 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
603 * @private
604 */
605function defineRedirectDescriptor(key) {
606 return {
607 get() {
608 return pd(this).event[key]
609 },
610 set(value) {
611 pd(this).event[key] = value;
612 },
613 configurable: true,
614 enumerable: true,
615 }
616}
617
618/**
619 * Get the property descriptor to call a given method property.
620 * @param {string} key Property name to define property descriptor.
621 * @returns {PropertyDescriptor} The property descriptor to call the method property.
622 * @private
623 */
624function defineCallDescriptor(key) {
625 return {
626 value() {
627 const event = pd(this).event;
628 return event[key].apply(event, arguments)
629 },
630 configurable: true,
631 enumerable: true,
632 }
633}
634
635/**
636 * Define new wrapper class.
637 * @param {Function} BaseEvent The base wrapper class.
638 * @param {Object} proto The prototype of the original event.
639 * @returns {Function} The defined wrapper class.
640 * @private
641 */
642function defineWrapper(BaseEvent, proto) {
643 const keys = Object.keys(proto);
644 if (keys.length === 0) {
645 return BaseEvent
646 }
647
648 /** CustomEvent */
649 function CustomEvent(eventTarget, event) {
650 BaseEvent.call(this, eventTarget, event);
651 }
652
653 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
654 constructor: { value: CustomEvent, configurable: true, writable: true },
655 });
656
657 // Define accessors.
658 for (let i = 0; i < keys.length; ++i) {
659 const key = keys[i];
660 if (!(key in BaseEvent.prototype)) {
661 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
662 const isFunc = typeof descriptor.value === "function";
663 Object.defineProperty(
664 CustomEvent.prototype,
665 key,
666 isFunc
667 ? defineCallDescriptor(key)
668 : defineRedirectDescriptor(key)
669 );
670 }
671 }
672
673 return CustomEvent
674}
675
676/**
677 * Get the wrapper class of a given prototype.
678 * @param {Object} proto The prototype of the original event to get its wrapper.
679 * @returns {Function} The wrapper class.
680 * @private
681 */
682function getWrapper(proto) {
683 if (proto == null || proto === Object.prototype) {
684 return Event
685 }
686
687 let wrapper = wrappers.get(proto);
688 if (wrapper == null) {
689 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
690 wrappers.set(proto, wrapper);
691 }
692 return wrapper
693}
694
695/**
696 * Wrap a given event to management a dispatching.
697 * @param {EventTarget} eventTarget The event target of this dispatching.
698 * @param {Object} event The event to wrap.
699 * @returns {Event} The wrapper instance.
700 * @private
701 */
702function wrapEvent(eventTarget, event) {
703 const Wrapper = getWrapper(Object.getPrototypeOf(event));
704 return new Wrapper(eventTarget, event)
705}
706
707/**
708 * Get the immediateStopped flag of a given event.
709 * @param {Event} event The event to get.
710 * @returns {boolean} The flag to stop propagation immediately.
711 * @private
712 */
713function isStopped(event) {
714 return pd(event).immediateStopped
715}
716
717/**
718 * Set the current event phase of a given event.
719 * @param {Event} event The event to set current target.
720 * @param {number} eventPhase New event phase.
721 * @returns {void}
722 * @private
723 */
724function setEventPhase(event, eventPhase) {
725 pd(event).eventPhase = eventPhase;
726}
727
728/**
729 * Set the current target of a given event.
730 * @param {Event} event The event to set current target.
731 * @param {EventTarget|null} currentTarget New current target.
732 * @returns {void}
733 * @private
734 */
735function setCurrentTarget(event, currentTarget) {
736 pd(event).currentTarget = currentTarget;
737}
738
739/**
740 * Set a passive listener of a given event.
741 * @param {Event} event The event to set current target.
742 * @param {Function|null} passiveListener New passive listener.
743 * @returns {void}
744 * @private
745 */
746function setPassiveListener(event, passiveListener) {
747 pd(event).passiveListener = passiveListener;
748}
749
750/**
751 * @typedef {object} ListenerNode
752 * @property {Function} listener
753 * @property {1|2|3} listenerType
754 * @property {boolean} passive
755 * @property {boolean} once
756 * @property {ListenerNode|null} next
757 * @private
758 */
759
760/**
761 * @type {WeakMap<object, Map<string, ListenerNode>>}
762 * @private
763 */
764const listenersMap = new WeakMap();
765
766// Listener types
767const CAPTURE = 1;
768const BUBBLE = 2;
769const ATTRIBUTE = 3;
770
771/**
772 * Check whether a given value is an object or not.
773 * @param {any} x The value to check.
774 * @returns {boolean} `true` if the value is an object.
775 */
776function isObject(x) {
777 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
778}
779
780/**
781 * Get listeners.
782 * @param {EventTarget} eventTarget The event target to get.
783 * @returns {Map<string, ListenerNode>} The listeners.
784 * @private
785 */
786function getListeners(eventTarget) {
787 const listeners = listenersMap.get(eventTarget);
788 if (listeners == null) {
789 throw new TypeError(
790 "'this' is expected an EventTarget object, but got another value."
791 )
792 }
793 return listeners
794}
795
796/**
797 * Get the property descriptor for the event attribute of a given event.
798 * @param {string} eventName The event name to get property descriptor.
799 * @returns {PropertyDescriptor} The property descriptor.
800 * @private
801 */
802function defineEventAttributeDescriptor(eventName) {
803 return {
804 get() {
805 const listeners = getListeners(this);
806 let node = listeners.get(eventName);
807 while (node != null) {
808 if (node.listenerType === ATTRIBUTE) {
809 return node.listener
810 }
811 node = node.next;
812 }
813 return null
814 },
815
816 set(listener) {
817 if (typeof listener !== "function" && !isObject(listener)) {
818 listener = null; // eslint-disable-line no-param-reassign
819 }
820 const listeners = getListeners(this);
821
822 // Traverse to the tail while removing old value.
823 let prev = null;
824 let node = listeners.get(eventName);
825 while (node != null) {
826 if (node.listenerType === ATTRIBUTE) {
827 // Remove old value.
828 if (prev !== null) {
829 prev.next = node.next;
830 } else if (node.next !== null) {
831 listeners.set(eventName, node.next);
832 } else {
833 listeners.delete(eventName);
834 }
835 } else {
836 prev = node;
837 }
838
839 node = node.next;
840 }
841
842 // Add new value.
843 if (listener !== null) {
844 const newNode = {
845 listener,
846 listenerType: ATTRIBUTE,
847 passive: false,
848 once: false,
849 next: null,
850 };
851 if (prev === null) {
852 listeners.set(eventName, newNode);
853 } else {
854 prev.next = newNode;
855 }
856 }
857 },
858 configurable: true,
859 enumerable: true,
860 }
861}
862
863/**
864 * Define an event attribute (e.g. `eventTarget.onclick`).
865 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
866 * @param {string} eventName The event name to define.
867 * @returns {void}
868 */
869function defineEventAttribute(eventTargetPrototype, eventName) {
870 Object.defineProperty(
871 eventTargetPrototype,
872 `on${eventName}`,
873 defineEventAttributeDescriptor(eventName)
874 );
875}
876
877/**
878 * Define a custom EventTarget with event attributes.
879 * @param {string[]} eventNames Event names for event attributes.
880 * @returns {EventTarget} The custom EventTarget.
881 * @private
882 */
883function defineCustomEventTarget(eventNames) {
884 /** CustomEventTarget */
885 function CustomEventTarget() {
886 EventTarget.call(this);
887 }
888
889 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
890 constructor: {
891 value: CustomEventTarget,
892 configurable: true,
893 writable: true,
894 },
895 });
896
897 for (let i = 0; i < eventNames.length; ++i) {
898 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
899 }
900
901 return CustomEventTarget
902}
903
904/**
905 * EventTarget.
906 *
907 * - This is constructor if no arguments.
908 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
909 *
910 * For example:
911 *
912 * class A extends EventTarget {}
913 * class B extends EventTarget("message") {}
914 * class C extends EventTarget("message", "error") {}
915 * class D extends EventTarget(["message", "error"]) {}
916 */
917function EventTarget() {
918 /*eslint-disable consistent-return */
919 if (this instanceof EventTarget) {
920 listenersMap.set(this, new Map());
921 return
922 }
923 if (arguments.length === 1 && Array.isArray(arguments[0])) {
924 return defineCustomEventTarget(arguments[0])
925 }
926 if (arguments.length > 0) {
927 const types = new Array(arguments.length);
928 for (let i = 0; i < arguments.length; ++i) {
929 types[i] = arguments[i];
930 }
931 return defineCustomEventTarget(types)
932 }
933 throw new TypeError("Cannot call a class as a function")
934 /*eslint-enable consistent-return */
935}
936
937// Should be enumerable, but class methods are not enumerable.
938EventTarget.prototype = {
939 /**
940 * Add a given listener to this event target.
941 * @param {string} eventName The event name to add.
942 * @param {Function} listener The listener to add.
943 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
944 * @returns {void}
945 */
946 addEventListener(eventName, listener, options) {
947 if (listener == null) {
948 return
949 }
950 if (typeof listener !== "function" && !isObject(listener)) {
951 throw new TypeError("'listener' should be a function or an object.")
952 }
953
954 const listeners = getListeners(this);
955 const optionsIsObj = isObject(options);
956 const capture = optionsIsObj
957 ? Boolean(options.capture)
958 : Boolean(options);
959 const listenerType = capture ? CAPTURE : BUBBLE;
960 const newNode = {
961 listener,
962 listenerType,
963 passive: optionsIsObj && Boolean(options.passive),
964 once: optionsIsObj && Boolean(options.once),
965 next: null,
966 };
967
968 // Set it as the first node if the first node is null.
969 let node = listeners.get(eventName);
970 if (node === undefined) {
971 listeners.set(eventName, newNode);
972 return
973 }
974
975 // Traverse to the tail while checking duplication..
976 let prev = null;
977 while (node != null) {
978 if (
979 node.listener === listener &&
980 node.listenerType === listenerType
981 ) {
982 // Should ignore duplication.
983 return
984 }
985 prev = node;
986 node = node.next;
987 }
988
989 // Add it.
990 prev.next = newNode;
991 },
992
993 /**
994 * Remove a given listener from this event target.
995 * @param {string} eventName The event name to remove.
996 * @param {Function} listener The listener to remove.
997 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
998 * @returns {void}
999 */
1000 removeEventListener(eventName, listener, options) {
1001 if (listener == null) {
1002 return
1003 }
1004
1005 const listeners = getListeners(this);
1006 const capture = isObject(options)
1007 ? Boolean(options.capture)
1008 : Boolean(options);
1009 const listenerType = capture ? CAPTURE : BUBBLE;
1010
1011 let prev = null;
1012 let node = listeners.get(eventName);
1013 while (node != null) {
1014 if (
1015 node.listener === listener &&
1016 node.listenerType === listenerType
1017 ) {
1018 if (prev !== null) {
1019 prev.next = node.next;
1020 } else if (node.next !== null) {
1021 listeners.set(eventName, node.next);
1022 } else {
1023 listeners.delete(eventName);
1024 }
1025 return
1026 }
1027
1028 prev = node;
1029 node = node.next;
1030 }
1031 },
1032
1033 /**
1034 * Dispatch a given event.
1035 * @param {Event|{type:string}} event The event to dispatch.
1036 * @returns {boolean} `false` if canceled.
1037 */
1038 dispatchEvent(event) {
1039 if (event == null || typeof event.type !== "string") {
1040 throw new TypeError('"event.type" should be a string.')
1041 }
1042
1043 // If listeners aren't registered, terminate.
1044 const listeners = getListeners(this);
1045 const eventName = event.type;
1046 let node = listeners.get(eventName);
1047 if (node == null) {
1048 return true
1049 }
1050
1051 // Since we cannot rewrite several properties, so wrap object.
1052 const wrappedEvent = wrapEvent(this, event);
1053
1054 // This doesn't process capturing phase and bubbling phase.
1055 // This isn't participating in a tree.
1056 let prev = null;
1057 while (node != null) {
1058 // Remove this listener if it's once
1059 if (node.once) {
1060 if (prev !== null) {
1061 prev.next = node.next;
1062 } else if (node.next !== null) {
1063 listeners.set(eventName, node.next);
1064 } else {
1065 listeners.delete(eventName);
1066 }
1067 } else {
1068 prev = node;
1069 }
1070
1071 // Call this listener
1072 setPassiveListener(
1073 wrappedEvent,
1074 node.passive ? node.listener : null
1075 );
1076 if (typeof node.listener === "function") {
1077 try {
1078 node.listener.call(this, wrappedEvent);
1079 } catch (err) {
1080 if (
1081 typeof console !== "undefined" &&
1082 typeof console.error === "function"
1083 ) {
1084 console.error(err);
1085 }
1086 }
1087 } else if (
1088 node.listenerType !== ATTRIBUTE &&
1089 typeof node.listener.handleEvent === "function"
1090 ) {
1091 node.listener.handleEvent(wrappedEvent);
1092 }
1093
1094 // Break if `event.stopImmediatePropagation` was called.
1095 if (isStopped(wrappedEvent)) {
1096 break
1097 }
1098
1099 node = node.next;
1100 }
1101 setPassiveListener(wrappedEvent, null);
1102 setEventPhase(wrappedEvent, 0);
1103 setCurrentTarget(wrappedEvent, null);
1104
1105 return !wrappedEvent.defaultPrevented
1106 },
1107};
1108
1109// `constructor` is not enumerable.
1110Object.defineProperty(EventTarget.prototype, "constructor", {
1111 value: EventTarget,
1112 configurable: true,
1113 writable: true,
1114});
1115
1116// Ensure `eventTarget instanceof window.EventTarget` is `true`.
1117if (
1118 typeof window !== "undefined" &&
1119 typeof window.EventTarget !== "undefined"
1120) {
1121 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
1122}
1123
1124var WS = /** @class */ (function (_super) {
1125 __extends(WS, _super);
1126 function WS(url, protocol) {
1127 var _this = _super.call(this) || this;
1128 _this._readyState = WS.CLOSED;
1129 if (!url) {
1130 throw new TypeError("Failed to construct 'WebSocket': url required");
1131 }
1132 _this._url = url;
1133 _this._protocol = protocol;
1134 return _this;
1135 }
1136 Object.defineProperty(WS.prototype, "url", {
1137 get: function () {
1138 return this._url;
1139 },
1140 enumerable: false,
1141 configurable: true
1142 });
1143 Object.defineProperty(WS.prototype, "protocol", {
1144 get: function () {
1145 return this._protocol;
1146 },
1147 enumerable: false,
1148 configurable: true
1149 });
1150 Object.defineProperty(WS.prototype, "readyState", {
1151 get: function () {
1152 return this._readyState;
1153 },
1154 enumerable: false,
1155 configurable: true
1156 });
1157 WS.CONNECTING = 0;
1158 WS.OPEN = 1;
1159 WS.CLOSING = 2;
1160 WS.CLOSED = 3;
1161 return WS;
1162}(EventTarget("open", "error", "message", "close")));
1163var WechatWS = /** @class */ (function (_super) {
1164 __extends(WechatWS, _super);
1165 function WechatWS(url, protocol) {
1166 var _this = _super.call(this, url, protocol) || this;
1167 if (protocol &&
1168 !(wx.canIUse && wx.canIUse("connectSocket.object.protocols"))) {
1169 throw new Error("subprotocol not supported in weapp");
1170 }
1171 _this._readyState = WS.CONNECTING;
1172 var errorHandler = function (event) {
1173 _this._readyState = WS.CLOSED;
1174 _this.dispatchEvent({
1175 type: "error",
1176 message: event.errMsg,
1177 });
1178 };
1179 var socketTask = wx.connectSocket({
1180 url: url,
1181 protocols: _this._protocol === undefined || Array.isArray(_this._protocol)
1182 ? _this._protocol
1183 : [_this._protocol],
1184 fail: function (error) { return setTimeout(function () { return errorHandler(error); }, 0); },
1185 });
1186 _this._socketTask = socketTask;
1187 socketTask.onOpen(function () {
1188 _this._readyState = WS.OPEN;
1189 _this.dispatchEvent({
1190 type: "open",
1191 });
1192 });
1193 socketTask.onError(errorHandler);
1194 socketTask.onMessage(function (event) {
1195 var data = event.data;
1196 _this.dispatchEvent({
1197 data: data,
1198 type: "message",
1199 });
1200 });
1201 socketTask.onClose(function (event) {
1202 _this._readyState = WS.CLOSED;
1203 var code = event.code, reason = event.reason;
1204 _this.dispatchEvent({
1205 code: code,
1206 reason: reason,
1207 type: "close",
1208 });
1209 });
1210 return _this;
1211 }
1212 WechatWS.prototype.close = function () {
1213 if (this.readyState === WS.CLOSED)
1214 return;
1215 if (this.readyState === WS.CONNECTING) {
1216 console.warn("close WebSocket which is connecting might not work");
1217 }
1218 this._socketTask.close({});
1219 };
1220 WechatWS.prototype.send = function (data) {
1221 if (this.readyState !== WS.OPEN) {
1222 throw new Error("INVALID_STATE_ERR");
1223 }
1224 if (!(typeof data === "string" || data instanceof ArrayBuffer)) {
1225 throw new TypeError("only String/ArrayBuffer supported");
1226 }
1227 this._socketTask.send({
1228 data: data,
1229 });
1230 };
1231 return WechatWS;
1232}(WS));
1233var WebSocket = WechatWS;
1234
1235var platformInfo = {
1236 name: "Weapp",
1237};
1238
1239exports.WebSocket = WebSocket;
1240exports.getAuthInfo = getAuthInfo;
1241exports.platformInfo = platformInfo;
1242exports.request = request;
1243exports.storage = storage;
1244exports.upload = upload;
1245//# sourceMappingURL=index.js.map