@revues/web-sdk-core 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1999 @@
1
+ /*!
2
+ * @revues/web-sdk-core
3
+ * (c) 2024-2024 Alex
4
+ * Released under the MIT License.
5
+ */
6
+ (function (factory) {
7
+ typeof define === 'function' && define.amd ? define(factory) :
8
+ factory();
9
+ })((function () { 'use strict';
10
+
11
+ /*! *****************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+ /* global Reflect, Promise */
26
+
27
+ var extendStatics = function(d, b) {
28
+ extendStatics = Object.setPrototypeOf ||
29
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
31
+ return extendStatics(d, b);
32
+ };
33
+
34
+ function __extends(d, b) {
35
+ extendStatics(d, b);
36
+ function __() { this.constructor = d; }
37
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38
+ }
39
+
40
+ var __assign = function() {
41
+ __assign = Object.assign || function __assign(t) {
42
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
43
+ s = arguments[i];
44
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
45
+ }
46
+ return t;
47
+ };
48
+ return __assign.apply(this, arguments);
49
+ };
50
+
51
+ function __awaiter(thisArg, _arguments, P, generator) {
52
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
53
+ return new (P || (P = Promise))(function (resolve, reject) {
54
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
55
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
56
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
57
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
58
+ });
59
+ }
60
+
61
+ function __generator(thisArg, body) {
62
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
63
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
64
+ function verb(n) { return function (v) { return step([n, v]); }; }
65
+ function step(op) {
66
+ if (f) throw new TypeError("Generator is already executing.");
67
+ while (_) try {
68
+ 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;
69
+ if (y = 0, t) op = [op[0] & 2, t.value];
70
+ switch (op[0]) {
71
+ case 0: case 1: t = op; break;
72
+ case 4: _.label++; return { value: op[1], done: false };
73
+ case 5: _.label++; y = op[1]; op = [0]; continue;
74
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
75
+ default:
76
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
77
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
78
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
79
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
80
+ if (t[2]) _.ops.pop();
81
+ _.trys.pop(); continue;
82
+ }
83
+ op = body.call(thisArg, _);
84
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
85
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
86
+ }
87
+ }
88
+
89
+ function __spreadArrays() {
90
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
91
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
92
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
93
+ r[k] = a[j];
94
+ return r;
95
+ }
96
+
97
+ function getSystem() {
98
+ var e = window.navigator.userAgent.toLowerCase();
99
+ return /(iphone|ipad)/.test(e)
100
+ ? 'IOS'
101
+ : /android/.test(e)
102
+ ? 'Android'
103
+ : 'Windows For HUYA';
104
+ }
105
+ function resolveUrl(url) {
106
+ var _a = url.split('?'), path = _a[0], queryStr = _a[1];
107
+ var query = {};
108
+ if (queryStr != null && queryStr !== '') {
109
+ queryStr.split('&').reduce(function (acc, item) {
110
+ var kv = item.split('=');
111
+ acc[kv[0]] = decodeURIComponent(kv[1]);
112
+ return acc;
113
+ }, query);
114
+ }
115
+ return {
116
+ path: path,
117
+ query: query
118
+ };
119
+ }
120
+ function arrayBufferToBase64(buffer) {
121
+ var binary = '';
122
+ var bytes = new Uint8Array(buffer);
123
+ var len = bytes.byteLength;
124
+ for (var i = 0; i < len; i++) {
125
+ binary += String.fromCharCode(bytes[i]);
126
+ }
127
+ return window.btoa(binary);
128
+ }
129
+ function delay(duration) {
130
+ return new Promise(function (resolve) {
131
+ setTimeout(resolve, duration);
132
+ });
133
+ }
134
+ var promiseTimeout = function (ms, promise, handleTimeout) {
135
+ var id;
136
+ // Create a promise that rejects in <ms> milliseconds
137
+ var timeout = new Promise(function (resolve, reject) {
138
+ id = setTimeout(function () {
139
+ handleTimeout && handleTimeout(ms);
140
+ reject(new Error('Timed out in ' + ms + 'ms.'));
141
+ }, ms);
142
+ });
143
+ // Returns a race between our timeout and the passed in promise
144
+ return new Promise(function (resolve, reject) {
145
+ Promise.race([
146
+ promise,
147
+ timeout
148
+ ]).then(function (res) {
149
+ clearTimeout(id);
150
+ resolve(res);
151
+ }).catch(reject);
152
+ });
153
+ };
154
+ function formatPagePath(v) {
155
+ return v.replace(/\.html$/, '');
156
+ }
157
+
158
+ var basePath = location.protocol + '//' + location.host + location.pathname.replace(/index\.html$/, '');
159
+ // 视图层逻辑模版
160
+ var viewTemplatePath = basePath + 'view.html';
161
+ // 先开着
162
+ var debug = window.__debug != null ? window.__debug : true;
163
+ var Terminal = {
164
+ Service: 'service',
165
+ View: 'view'
166
+ };
167
+ var packageExtConfig = window.__packageExtConfig;
168
+ var launchOption = {
169
+ path: packageExtConfig ? packageExtConfig.entryPagePath : 'index',
170
+ query: {},
171
+ referrerInfo: {},
172
+ scene: 1001
173
+ };
174
+ var onLoadSubPackageTaskStateChange = 'onLoadSubPackageTaskStateChange';
175
+ var onTaskProgressUpdate = 'onTaskProgressUpdate';
176
+ var onTaskHeadersReceived = 'onTaskHeadersReceived';
177
+ var miniGame = 'miniGame';
178
+ var miniProgram = 'miniProgram';
179
+ var localPathPerfix = 'finfile://';
180
+ var imgSets = new Set(['.png', '.jpg', '.jpeg', '.gif', '.svg', '.mp4', '.mp3']);
181
+
182
+ function requestSource(url, opts, cb) {
183
+ var xhr = new XMLHttpRequest();
184
+ var asyncRequest = true;
185
+ if (opts.sync != null) {
186
+ asyncRequest = !opts.sync;
187
+ }
188
+ if (opts.responseType != null) {
189
+ xhr.responseType = opts.responseType;
190
+ }
191
+ xhr.open('GET', url, asyncRequest);
192
+ if (opts.header != null) {
193
+ for (var key in opts.header) {
194
+ xhr.setRequestHeader(key, opts.header[key]);
195
+ }
196
+ }
197
+ xhr.onload = function (e) {
198
+ cb(null, xhr.response, { e: e, xhr: xhr });
199
+ };
200
+ xhr.onerror = function (e) {
201
+ cb(new Error('request settings failed!'), null, { e: e, xhr: xhr });
202
+ };
203
+ xhr.send(null);
204
+ }
205
+ function processFilePath(file) {
206
+ // TODO: 需要判断同域同源才处理
207
+ if (file.endsWith('.wasm')) {
208
+ return file + '.txt';
209
+ }
210
+ return file;
211
+ }
212
+ var cache = {};
213
+ function cacheRequest(url, opts, cb) {
214
+ if (cache[url] != null) {
215
+ return cache[url];
216
+ }
217
+ requestSource(url, opts, function (err, data, eventInfo) {
218
+ if (err !== null) {
219
+ cache[url] = data;
220
+ }
221
+ cb(err, data, eventInfo);
222
+ });
223
+ }
224
+
225
+ function createCommonjsModule(fn, basedir, module) {
226
+ return module = {
227
+ path: basedir,
228
+ exports: {},
229
+ require: function (path, base) {
230
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
231
+ }
232
+ }, fn(module, module.exports), module.exports;
233
+ }
234
+
235
+ function commonjsRequire () {
236
+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
237
+ }
238
+
239
+ var eventemitter3 = createCommonjsModule(function (module) {
240
+
241
+ var has = Object.prototype.hasOwnProperty
242
+ , prefix = '~';
243
+
244
+ /**
245
+ * Constructor to create a storage for our `EE` objects.
246
+ * An `Events` instance is a plain object whose properties are event names.
247
+ *
248
+ * @constructor
249
+ * @private
250
+ */
251
+ function Events() {}
252
+
253
+ //
254
+ // We try to not inherit from `Object.prototype`. In some engines creating an
255
+ // instance in this way is faster than calling `Object.create(null)` directly.
256
+ // If `Object.create(null)` is not supported we prefix the event names with a
257
+ // character to make sure that the built-in object properties are not
258
+ // overridden or used as an attack vector.
259
+ //
260
+ if (Object.create) {
261
+ Events.prototype = Object.create(null);
262
+
263
+ //
264
+ // This hack is needed because the `__proto__` property is still inherited in
265
+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
266
+ //
267
+ if (!new Events().__proto__) prefix = false;
268
+ }
269
+
270
+ /**
271
+ * Representation of a single event listener.
272
+ *
273
+ * @param {Function} fn The listener function.
274
+ * @param {*} context The context to invoke the listener with.
275
+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
276
+ * @constructor
277
+ * @private
278
+ */
279
+ function EE(fn, context, once) {
280
+ this.fn = fn;
281
+ this.context = context;
282
+ this.once = once || false;
283
+ }
284
+
285
+ /**
286
+ * Add a listener for a given event.
287
+ *
288
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
289
+ * @param {(String|Symbol)} event The event name.
290
+ * @param {Function} fn The listener function.
291
+ * @param {*} context The context to invoke the listener with.
292
+ * @param {Boolean} once Specify if the listener is a one-time listener.
293
+ * @returns {EventEmitter}
294
+ * @private
295
+ */
296
+ function addListener(emitter, event, fn, context, once) {
297
+ if (typeof fn !== 'function') {
298
+ throw new TypeError('The listener must be a function');
299
+ }
300
+
301
+ var listener = new EE(fn, context || emitter, once)
302
+ , evt = prefix ? prefix + event : event;
303
+
304
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
305
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
306
+ else emitter._events[evt] = [emitter._events[evt], listener];
307
+
308
+ return emitter;
309
+ }
310
+
311
+ /**
312
+ * Clear event by name.
313
+ *
314
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
315
+ * @param {(String|Symbol)} evt The Event name.
316
+ * @private
317
+ */
318
+ function clearEvent(emitter, evt) {
319
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
320
+ else delete emitter._events[evt];
321
+ }
322
+
323
+ /**
324
+ * Minimal `EventEmitter` interface that is molded against the Node.js
325
+ * `EventEmitter` interface.
326
+ *
327
+ * @constructor
328
+ * @public
329
+ */
330
+ function EventEmitter() {
331
+ this._events = new Events();
332
+ this._eventsCount = 0;
333
+ }
334
+
335
+ /**
336
+ * Return an array listing the events for which the emitter has registered
337
+ * listeners.
338
+ *
339
+ * @returns {Array}
340
+ * @public
341
+ */
342
+ EventEmitter.prototype.eventNames = function eventNames() {
343
+ var names = []
344
+ , events
345
+ , name;
346
+
347
+ if (this._eventsCount === 0) return names;
348
+
349
+ for (name in (events = this._events)) {
350
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
351
+ }
352
+
353
+ if (Object.getOwnPropertySymbols) {
354
+ return names.concat(Object.getOwnPropertySymbols(events));
355
+ }
356
+
357
+ return names;
358
+ };
359
+
360
+ /**
361
+ * Return the listeners registered for a given event.
362
+ *
363
+ * @param {(String|Symbol)} event The event name.
364
+ * @returns {Array} The registered listeners.
365
+ * @public
366
+ */
367
+ EventEmitter.prototype.listeners = function listeners(event) {
368
+ var evt = prefix ? prefix + event : event
369
+ , handlers = this._events[evt];
370
+
371
+ if (!handlers) return [];
372
+ if (handlers.fn) return [handlers.fn];
373
+
374
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
375
+ ee[i] = handlers[i].fn;
376
+ }
377
+
378
+ return ee;
379
+ };
380
+
381
+ /**
382
+ * Return the number of listeners listening to a given event.
383
+ *
384
+ * @param {(String|Symbol)} event The event name.
385
+ * @returns {Number} The number of listeners.
386
+ * @public
387
+ */
388
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
389
+ var evt = prefix ? prefix + event : event
390
+ , listeners = this._events[evt];
391
+
392
+ if (!listeners) return 0;
393
+ if (listeners.fn) return 1;
394
+ return listeners.length;
395
+ };
396
+
397
+ /**
398
+ * Calls each of the listeners registered for a given event.
399
+ *
400
+ * @param {(String|Symbol)} event The event name.
401
+ * @returns {Boolean} `true` if the event had listeners, else `false`.
402
+ * @public
403
+ */
404
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
405
+ var evt = prefix ? prefix + event : event;
406
+
407
+ if (!this._events[evt]) return false;
408
+
409
+ var listeners = this._events[evt]
410
+ , len = arguments.length
411
+ , args
412
+ , i;
413
+
414
+ if (listeners.fn) {
415
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
416
+
417
+ switch (len) {
418
+ case 1: return listeners.fn.call(listeners.context), true;
419
+ case 2: return listeners.fn.call(listeners.context, a1), true;
420
+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;
421
+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
422
+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
423
+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
424
+ }
425
+
426
+ for (i = 1, args = new Array(len -1); i < len; i++) {
427
+ args[i - 1] = arguments[i];
428
+ }
429
+
430
+ listeners.fn.apply(listeners.context, args);
431
+ } else {
432
+ var length = listeners.length
433
+ , j;
434
+
435
+ for (i = 0; i < length; i++) {
436
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
437
+
438
+ switch (len) {
439
+ case 1: listeners[i].fn.call(listeners[i].context); break;
440
+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;
441
+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
442
+ case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
443
+ default:
444
+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
445
+ args[j - 1] = arguments[j];
446
+ }
447
+
448
+ listeners[i].fn.apply(listeners[i].context, args);
449
+ }
450
+ }
451
+ }
452
+
453
+ return true;
454
+ };
455
+
456
+ /**
457
+ * Add a listener for a given event.
458
+ *
459
+ * @param {(String|Symbol)} event The event name.
460
+ * @param {Function} fn The listener function.
461
+ * @param {*} [context=this] The context to invoke the listener with.
462
+ * @returns {EventEmitter} `this`.
463
+ * @public
464
+ */
465
+ EventEmitter.prototype.on = function on(event, fn, context) {
466
+ return addListener(this, event, fn, context, false);
467
+ };
468
+
469
+ /**
470
+ * Add a one-time listener for a given event.
471
+ *
472
+ * @param {(String|Symbol)} event The event name.
473
+ * @param {Function} fn The listener function.
474
+ * @param {*} [context=this] The context to invoke the listener with.
475
+ * @returns {EventEmitter} `this`.
476
+ * @public
477
+ */
478
+ EventEmitter.prototype.once = function once(event, fn, context) {
479
+ return addListener(this, event, fn, context, true);
480
+ };
481
+
482
+ /**
483
+ * Remove the listeners of a given event.
484
+ *
485
+ * @param {(String|Symbol)} event The event name.
486
+ * @param {Function} fn Only remove the listeners that match this function.
487
+ * @param {*} context Only remove the listeners that have this context.
488
+ * @param {Boolean} once Only remove one-time listeners.
489
+ * @returns {EventEmitter} `this`.
490
+ * @public
491
+ */
492
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
493
+ var evt = prefix ? prefix + event : event;
494
+
495
+ if (!this._events[evt]) return this;
496
+ if (!fn) {
497
+ clearEvent(this, evt);
498
+ return this;
499
+ }
500
+
501
+ var listeners = this._events[evt];
502
+
503
+ if (listeners.fn) {
504
+ if (
505
+ listeners.fn === fn &&
506
+ (!once || listeners.once) &&
507
+ (!context || listeners.context === context)
508
+ ) {
509
+ clearEvent(this, evt);
510
+ }
511
+ } else {
512
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
513
+ if (
514
+ listeners[i].fn !== fn ||
515
+ (once && !listeners[i].once) ||
516
+ (context && listeners[i].context !== context)
517
+ ) {
518
+ events.push(listeners[i]);
519
+ }
520
+ }
521
+
522
+ //
523
+ // Reset the array, or remove it completely if we have no more listeners.
524
+ //
525
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
526
+ else clearEvent(this, evt);
527
+ }
528
+
529
+ return this;
530
+ };
531
+
532
+ /**
533
+ * Remove all listeners, or those of the specified event.
534
+ *
535
+ * @param {(String|Symbol)} [event] The event name.
536
+ * @returns {EventEmitter} `this`.
537
+ * @public
538
+ */
539
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
540
+ var evt;
541
+
542
+ if (event) {
543
+ evt = prefix ? prefix + event : event;
544
+ if (this._events[evt]) clearEvent(this, evt);
545
+ } else {
546
+ this._events = new Events();
547
+ this._eventsCount = 0;
548
+ }
549
+
550
+ return this;
551
+ };
552
+
553
+ //
554
+ // Alias methods names because people roll like that.
555
+ //
556
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
557
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
558
+
559
+ //
560
+ // Expose the prefix.
561
+ //
562
+ EventEmitter.prefixed = prefix;
563
+
564
+ //
565
+ // Allow `EventEmitter` to be imported as module namespace.
566
+ //
567
+ EventEmitter.EventEmitter = EventEmitter;
568
+
569
+ //
570
+ // Expose the module.
571
+ //
572
+ {
573
+ module.exports = EventEmitter;
574
+ }
575
+ });
576
+
577
+ var IframeManager = /** @class */ (function () {
578
+ function IframeManager(el) {
579
+ this.sync = false;
580
+ this.events = new eventemitter3();
581
+ this.el = el;
582
+ this.isReady = false;
583
+ }
584
+ IframeManager.prototype.getWindow = function () {
585
+ return this.el.contentWindow;
586
+ };
587
+ IframeManager.prototype.getBridge = function () { };
588
+ IframeManager.prototype.emitSync = function (event) {
589
+ var _a;
590
+ var args = [];
591
+ for (var _i = 1; _i < arguments.length; _i++) {
592
+ args[_i - 1] = arguments[_i];
593
+ }
594
+ this.sync = true;
595
+ (_a = this.events).emit.apply(_a, __spreadArrays([event], args));
596
+ this.sync = false;
597
+ };
598
+ return IframeManager;
599
+ }());
600
+
601
+ var ViewIframeManager = /** @class */ (function (_super) {
602
+ __extends(ViewIframeManager, _super);
603
+ function ViewIframeManager(e) {
604
+ var _this = _super.call(this, e) || this;
605
+ _this.webviewId = null;
606
+ _this.pagePath = '';
607
+ _this.wrapper = null;
608
+ _this.isDestoryed = false;
609
+ _this.active = false;
610
+ _this.isTabView = false;
611
+ return _this;
612
+ }
613
+ ViewIframeManager.prototype.appendContainer = function () {
614
+ var el = this.el;
615
+ el.className = 'webview';
616
+ el.setAttribute('frameborder', '0');
617
+ this.hide();
618
+ var wrapper = document.getElementById('webview-container');
619
+ this.wrapper = wrapper;
620
+ if (wrapper != null) {
621
+ wrapper.appendChild(el);
622
+ }
623
+ };
624
+ ViewIframeManager.prototype.show = function () {
625
+ var el = this.el;
626
+ el.style.zIndex = '2';
627
+ el.style.opacity = '1';
628
+ this.active = true;
629
+ };
630
+ ViewIframeManager.prototype.hide = function () {
631
+ var el = this.el;
632
+ el.style.zIndex = '1';
633
+ el.style.opacity = '0';
634
+ this.active = false;
635
+ };
636
+ ViewIframeManager.prototype.updateWebviewId = function (v) {
637
+ this.webviewId = v;
638
+ this.updateId();
639
+ };
640
+ ViewIframeManager.prototype.updateId = function () {
641
+ this.el.id = "webview-" + this.webviewId;
642
+ };
643
+ ViewIframeManager.prototype.updateSrc = function (pagePath) {
644
+ this.el.src = viewTemplatePath;
645
+ this.pagePath = pagePath;
646
+ };
647
+ ViewIframeManager.prototype.injectScript = function () {
648
+ var _this = this;
649
+ var innerWindow = this.getWindow();
650
+ if (innerWindow != null && this.pagePath != '') {
651
+ var pagePath = this.pagePath.endsWith('.html')
652
+ ? this.pagePath
653
+ : this.pagePath + '.html';
654
+ var reqUrl_1 = basePath + pagePath;
655
+ cacheRequest(reqUrl_1, { sync: true }, function (err, data) {
656
+ if (err != null) {
657
+ console.error("init page fail in " + _this.pagePath + ", req: " + reqUrl_1 + " \n " + err);
658
+ }
659
+ else {
660
+ // @ts-ignore
661
+ innerWindow.injectHtml(innerWindow.document.body, {
662
+ content: data
663
+ });
664
+ }
665
+ });
666
+ }
667
+ };
668
+ ViewIframeManager.prototype.getBridge = function () {
669
+ // @ts-ignore
670
+ return this.getWindow().FinChatJSBridge;
671
+ };
672
+ ViewIframeManager.prototype.sendToView = function (event, data) {
673
+ var _this = this;
674
+ if (this.sync) {
675
+ debug && console.log("%c " + event, "color: green;", data, this.webviewId);
676
+ this.getBridge().subscribeHandler(event, data, this.webviewId);
677
+ }
678
+ else {
679
+ // 事件交互 必须异步发送到视图层,不然可能会成闭塞环引发 bug
680
+ setTimeout(function () {
681
+ debug &&
682
+ console.log("%c " + event, "color: green;", data, _this.webviewId);
683
+ _this.getBridge().subscribeHandler(event, data, _this.webviewId);
684
+ });
685
+ }
686
+ };
687
+ ViewIframeManager.prototype.destory = function () {
688
+ if (this.wrapper !== null) {
689
+ this.wrapper.removeChild(this.el);
690
+ // @ts-ignore
691
+ this.el = null;
692
+ this.wrapper = null;
693
+ this.isDestoryed = true;
694
+ this.active = false;
695
+ }
696
+ };
697
+ return ViewIframeManager;
698
+ }(IframeManager));
699
+
700
+ var Router = /** @class */ (function () {
701
+ function Router() {
702
+ this._slotStack = [];
703
+ this._extraStack = [];
704
+ this._slots = [];
705
+ this._webviewId = 0;
706
+ this.rootIndex = 0;
707
+ }
708
+ Object.defineProperty(Router.prototype, "pagePath", {
709
+ get: function () {
710
+ var _a;
711
+ return ((_a = this.currPage) === null || _a === void 0 ? void 0 : _a.pagePath) || null;
712
+ },
713
+ enumerable: false,
714
+ configurable: true
715
+ });
716
+ Object.defineProperty(Router.prototype, "currPage", {
717
+ get: function () {
718
+ return this.stack[this.stack.length - 2] || null;
719
+ },
720
+ enumerable: false,
721
+ configurable: true
722
+ });
723
+ Object.defineProperty(Router.prototype, "top", {
724
+ get: function () {
725
+ return this.stack[this.stack.length - 1];
726
+ },
727
+ enumerable: false,
728
+ configurable: true
729
+ });
730
+ Object.defineProperty(Router.prototype, "stack", {
731
+ get: function () {
732
+ var root = this._slotStack[this.rootIndex];
733
+ if (root == null)
734
+ return [];
735
+ return __spreadArrays([root], this._extraStack);
736
+ },
737
+ enumerable: false,
738
+ configurable: true
739
+ });
740
+ Object.defineProperty(Router.prototype, "allPages", {
741
+ get: function () {
742
+ var root = this._slotStack[this.rootIndex];
743
+ if (root == null)
744
+ return [];
745
+ return __spreadArrays([root], this._extraStack.slice(0, this._extraStack.length - 1));
746
+ },
747
+ enumerable: false,
748
+ configurable: true
749
+ });
750
+ Router.prototype.initFirstPage = function (slots, pagePath) {
751
+ if (!Array.isArray(slots) || slots.length === 0) {
752
+ throw new Error('slots must exist.');
753
+ }
754
+ var targetIndex = findSlotIndex(this, pagePath);
755
+ this._slots = slots;
756
+ for (var i = 0; i < slots.length; i++) {
757
+ var iframe = document.createElement('iframe');
758
+ var viewIfameManager = new ViewIframeManager(iframe);
759
+ viewIfameManager.appendContainer();
760
+ this._slotStack.push(viewIfameManager);
761
+ }
762
+ if (targetIndex > -1) {
763
+ this.rootIndex = targetIndex;
764
+ }
765
+ var first = this._slotStack[this.rootIndex];
766
+ first.updateSrc(pagePath);
767
+ this.initEmptyPage();
768
+ };
769
+ Router.prototype.reinitPages = function (pagePath) {
770
+ var slotStack = this._slotStack;
771
+ var extraStack = this._extraStack;
772
+ slotStack.forEach(function (page) {
773
+ page.destory();
774
+ });
775
+ extraStack.forEach(function (page) {
776
+ page.destory();
777
+ });
778
+ this._slotStack = [];
779
+ this._extraStack = [];
780
+ this.initFirstPage(this._slots, pagePath);
781
+ this.currPage.updateWebviewId(this._webviewId++);
782
+ };
783
+ Router.prototype.reLaunch = function (pagePath) {
784
+ this.reinitPages(pagePath);
785
+ };
786
+ Router.prototype.redirectTo = function (pagePath) {
787
+ var targetIndex = findSlotIndex(this, pagePath);
788
+ if (targetIndex > -1) {
789
+ throw new Error('不允许跳转到 tabbar 页面:' + pagePath);
790
+ }
791
+ var extraStack = this._extraStack;
792
+ if (extraStack.length > 1) {
793
+ var pendingPage = extraStack.pop();
794
+ var currPage = extraStack.pop();
795
+ currPage.destory();
796
+ pendingPage.updateSrc(pagePath);
797
+ pendingPage.updateWebviewId(this._webviewId++);
798
+ extraStack.push(pendingPage);
799
+ this.initEmptyPage();
800
+ }
801
+ else {
802
+ // TODO: 可以优化的方案是 单个replace,而不是全销毁
803
+ var pendingPage = extraStack.pop();
804
+ pendingPage === null || pendingPage === void 0 ? void 0 : pendingPage.destory();
805
+ this._slotStack.forEach(function (page) {
806
+ page.destory();
807
+ });
808
+ this.reinitPages(pagePath);
809
+ }
810
+ };
811
+ Router.prototype.initSlotWebviewId = function (id) {
812
+ this._webviewId = id;
813
+ this._slotStack[this.rootIndex].updateWebviewId(this._webviewId++);
814
+ };
815
+ Router.prototype.initEmptyPage = function () {
816
+ var iframe = document.createElement('iframe');
817
+ var viewIfameManager = new ViewIframeManager(iframe);
818
+ viewIfameManager.appendContainer();
819
+ this._extraStack.push(viewIfameManager);
820
+ };
821
+ Router.prototype.initNextPage = function (page) {
822
+ var curr = this.currPage;
823
+ var pendingPage = this.top;
824
+ curr.hide();
825
+ pendingPage.updateSrc(page);
826
+ pendingPage.updateWebviewId(this._webviewId++);
827
+ this.initEmptyPage();
828
+ return pendingPage;
829
+ };
830
+ Router.prototype.switch = function (page, index) {
831
+ index = index != null ? index : findSlotIndex(this, page);
832
+ var stack = this._slotStack;
833
+ var view = stack[index];
834
+ if (view == null) {
835
+ throw new Error("switchTab url is invalid: " + page);
836
+ }
837
+ this.resetExtraStack();
838
+ stack.forEach(function (page) {
839
+ if (page.isReady) {
840
+ page.hide();
841
+ }
842
+ });
843
+ this.rootIndex = index;
844
+ if (view.isReady) {
845
+ view.show();
846
+ }
847
+ else {
848
+ view.updateWebviewId(this._webviewId++);
849
+ view.updateSrc(page);
850
+ }
851
+ return view;
852
+ };
853
+ Router.prototype.go = function (page) {
854
+ var targetIndex = findSlotIndex(this, page);
855
+ if (targetIndex > -1) {
856
+ return this.switch(page, targetIndex);
857
+ }
858
+ else {
859
+ return this.initNextPage(page);
860
+ }
861
+ };
862
+ Router.prototype.back = function (delta) {
863
+ var _a;
864
+ var extraStack = this._extraStack.slice();
865
+ var pending = extraStack.pop();
866
+ var len = extraStack.length;
867
+ if (delta <= 0) {
868
+ throw new Error('delta 不能 <= 0');
869
+ }
870
+ if (len < delta) {
871
+ throw new Error('delta 不能超过总栈长度:' + (len + 1));
872
+ }
873
+ var gapIndex = len - delta;
874
+ var reaminList = extraStack.slice(0, gapIndex);
875
+ var removeList = extraStack.slice(gapIndex, len);
876
+ removeList.forEach(function (item) {
877
+ item.destory();
878
+ });
879
+ if (reaminList.length > 0) {
880
+ var nestedPage = reaminList[reaminList.length - 1];
881
+ nestedPage.show();
882
+ }
883
+ else {
884
+ (_a = this._slotStack[this.rootIndex]) === null || _a === void 0 ? void 0 : _a.show();
885
+ }
886
+ pending && reaminList.push(pending);
887
+ this._extraStack = reaminList;
888
+ };
889
+ Router.prototype.resetExtraStack = function () {
890
+ if (this._extraStack.length === 0)
891
+ return;
892
+ var pendingPage = this.top;
893
+ this._extraStack.slice(0, this._extraStack.length - 1).forEach(function (page) {
894
+ page.destory();
895
+ });
896
+ this._extraStack = [pendingPage];
897
+ };
898
+ return Router;
899
+ }());
900
+ function findSlotIndex(router, pagePath) {
901
+ var slots = router._slots;
902
+ return slots.findIndex(function (a) { return a === formatPagePath(pagePath); });
903
+ }
904
+ var router = new Router;
905
+
906
+ var ServiceIframeManagerEventNames = {
907
+ 'onViewDOMContentLoaded': 'onViewDOMContentLoaded',
908
+ 'onInjectHTMLCallback': 'onInjectHTMLCallback',
909
+ };
910
+ var loadedMap = {};
911
+ function isLoadedPackage(root) {
912
+ return loadedMap[root];
913
+ }
914
+ var ServiceIframeManager = /** @class */ (function (_super) {
915
+ __extends(ServiceIframeManager, _super);
916
+ function ServiceIframeManager(e) {
917
+ return _super.call(this, e) || this;
918
+ }
919
+ ServiceIframeManager.prototype.sendToSerivce = function (event, data, webviewId) {
920
+ debug && console.log("%c " + event, "color: blue;", data, webviewId);
921
+ this.getBridge().subscribeHandler(event, data, webviewId);
922
+ };
923
+ // 加载子包
924
+ ServiceIframeManager.prototype.loadSubBundle = function (root, bundlePath) {
925
+ if (loadedMap[root] === true)
926
+ return;
927
+ var innerWindow = this.getWindow();
928
+ if (innerWindow != null) {
929
+ // @ts-ignore
930
+ innerWindow.injectHtml(innerWindow.document.body, {
931
+ content: "<script charset=\"utf-8\" src=\"" + bundlePath + "\"></script>"
932
+ });
933
+ loadedMap[root] = true;
934
+ }
935
+ };
936
+ ServiceIframeManager.prototype.invokeCallbackHandler = function (cbId, data, apiName) {
937
+ debug &&
938
+ console.log("%c " + (apiName || 'API') + " call callback", "color: blue;", cbId, data);
939
+ this.getBridge().invokeCallbackHandler(cbId, data);
940
+ };
941
+ ServiceIframeManager.prototype.getBridge = function () {
942
+ // @ts-ignore
943
+ return this.getWindow().ServiceJSBridge;
944
+ };
945
+ return ServiceIframeManager;
946
+ }(IframeManager));
947
+
948
+ var serviceIframeId = 'webview-service';
949
+ var iframeManagerMap = new Map();
950
+ function getIframeManager(id) {
951
+ var target = iframeManagerMap.get(id);
952
+ if (target)
953
+ return target;
954
+ var iframe = document.getElementById(id);
955
+ if (iframe != null) {
956
+ var Manager = id === serviceIframeId ? ServiceIframeManager : ViewIframeManager;
957
+ var manager = new Manager(iframe);
958
+ iframeManagerMap.set(id, manager);
959
+ return manager;
960
+ }
961
+ throw new Error("\u83B7\u53D6IframeManager\u5931\u8D25, id: " + id);
962
+ }
963
+ function getServiceIframeManager() {
964
+ return getIframeManager(serviceIframeId);
965
+ }
966
+
967
+ function invokeServiceCallbackHandler(cbId, data, apiName) {
968
+ var service = getIframeManager(serviceIframeId);
969
+ service.invokeCallbackHandler(cbId, data, apiName);
970
+ }
971
+
972
+ function dispatchViewEvent(event, data, webviewIds) {
973
+ router.stack.forEach(function (manager) {
974
+ if (manager.webviewId == null)
975
+ return;
976
+ if (webviewIds.indexOf(manager.webviewId) > -1) {
977
+ if (manager.isReady) {
978
+ manager.sendToView(event, data);
979
+ }
980
+ else {
981
+ console.error("shouldn't exctute");
982
+ }
983
+ }
984
+ });
985
+ }
986
+ function dispatchServiceEvent(event, data, webviewId) {
987
+ var service = getIframeManager(serviceIframeId);
988
+ service.sendToSerivce(event, data, webviewId);
989
+ }
990
+
991
+ var AdapterTarget = null;
992
+ function setTarget(target) {
993
+ AdapterTarget = target;
994
+ }
995
+ function getTarget() {
996
+ return AdapterTarget;
997
+ }
998
+
999
+ var CoreAdapter = /** @class */ (function () {
1000
+ function CoreAdapter() {
1001
+ // SDK 接口调用
1002
+ this._invokeServiceCallbackHandler = invokeServiceCallbackHandler;
1003
+ // 往 ui/逻辑 进程发消息
1004
+ this._dispatchViewEvent = dispatchViewEvent;
1005
+ this._dispatchServiceEvent = dispatchServiceEvent;
1006
+ // 获得当前页面信息,发消息 所需要的 webviewId,可以从这些接口拿
1007
+ this._getCurrentPage = function () {
1008
+ return router.currPage;
1009
+ };
1010
+ this._getAllPages = function () {
1011
+ return router.allPages;
1012
+ };
1013
+ }
1014
+ CoreAdapter.prototype.init = function () {
1015
+ setTarget(this);
1016
+ };
1017
+ return CoreAdapter;
1018
+ }());
1019
+ window.__CoreAdapter = CoreAdapter;
1020
+
1021
+ function toLocalTempFilePath(url) {
1022
+ return url.replace(/^http(s?)\:\/\//, localPathPerfix);
1023
+ }
1024
+
1025
+ function headersStr2Obj(headers) {
1026
+ var arr = headers.trim().split(/[\r\n]+/);
1027
+ // Create a map of header names to values
1028
+ var headerMap = {};
1029
+ arr.forEach(function (line) {
1030
+ var parts = line.split(": ");
1031
+ var header = parts.shift();
1032
+ var value = parts.join(": ");
1033
+ headerMap[header] = value;
1034
+ });
1035
+ return headerMap;
1036
+ }
1037
+
1038
+ function nextTick(cb) {
1039
+ setTimeout(cb, 17);
1040
+ }
1041
+
1042
+ var fsUtilApis = {
1043
+ readFileSync: function (opts) {
1044
+ var filePath = opts.filePath;
1045
+ // 本地文件 不能通过http请求的,走缓存系统
1046
+ if (filePath.startsWith(localPathPerfix)) {
1047
+ var cache = localStorage.getItem(filePath);
1048
+ if (cache != null) {
1049
+ return { data: cache, errMsg: 'readFileSync:ok' };
1050
+ }
1051
+ else {
1052
+ return { data: null, errMsg: "readFileSync:fail " + filePath + " not exist" };
1053
+ }
1054
+ }
1055
+ filePath = processFilePath(filePath);
1056
+ var rsp = null;
1057
+ var rspErr = null;
1058
+ requestSource(basePath + filePath, { sync: true }, function (err, data) {
1059
+ rsp = data;
1060
+ rspErr = err;
1061
+ });
1062
+ if (rsp != null) {
1063
+ return { data: rsp, errMsg: 'readFileSync:ok' };
1064
+ }
1065
+ else if (rspErr != null) {
1066
+ return {
1067
+ data: null,
1068
+ errMsg: 'readFileSync:fail ' + rspErr.message
1069
+ };
1070
+ }
1071
+ return { data: null, errMsg: 'readFileSync:fail' };
1072
+ },
1073
+ // 异步读取
1074
+ readFile: function (opts, callbackId) {
1075
+ var filePath = opts.filePath, encoding = opts.encoding;
1076
+ var isBase64 = encoding === 'base64';
1077
+ var url = basePath + filePath;
1078
+ if (filePath.startsWith(localPathPerfix)) {
1079
+ nextTick(function () {
1080
+ var result = localStorage.getItem(filePath);
1081
+ if (result != null) {
1082
+ invokeServiceCallbackHandler(callbackId, {
1083
+ data: result,
1084
+ errMsg: 'readFile:ok'
1085
+ });
1086
+ }
1087
+ else {
1088
+ invokeServiceCallbackHandler(callbackId, {
1089
+ errMsg: "readFile:fail " + filePath + " is not existed"
1090
+ });
1091
+ }
1092
+ });
1093
+ return;
1094
+ }
1095
+ requestSource(url, {
1096
+ responseType: isBase64 ? 'arraybuffer' : ''
1097
+ }, function (err, data) {
1098
+ if (err != null) {
1099
+ invokeServiceCallbackHandler(callbackId, {
1100
+ errMsg: 'readFile:fail ' + err.message
1101
+ });
1102
+ return;
1103
+ }
1104
+ invokeServiceCallbackHandler(callbackId, {
1105
+ data: isBase64 ? arrayBufferToBase64(data) : data,
1106
+ errMsg: 'readFile:ok'
1107
+ });
1108
+ });
1109
+ },
1110
+ // 文件是否存在
1111
+ access: function () {
1112
+ return { errMsg: 'access:ok' };
1113
+ },
1114
+ mkdirSync: function () {
1115
+ return { errMsg: 'mkdirSync:ok' };
1116
+ },
1117
+ writeFileSync: function (_a) {
1118
+ var filePath = _a.filePath, data = _a.data;
1119
+ // 缓存模拟文件系统
1120
+ localStorage.setItem(filePath, data);
1121
+ return { errMsg: 'writeFileSync:ok' };
1122
+ },
1123
+ unlink: function (_a, callbackId) {
1124
+ var filePath = _a.filePath;
1125
+ nextTick(function () {
1126
+ localStorage.removeItem(filePath);
1127
+ invokeServiceCallbackHandler(callbackId, {
1128
+ errMsg: 'unlink:ok'
1129
+ });
1130
+ });
1131
+ },
1132
+ downloadFile: function (_a, callbackId) {
1133
+ var url = _a.url, _b = _a.timeout, timeout = _b === void 0 ? 6000 : _b; _a.taskId; _a.header; _a.filePath;
1134
+ promiseTimeout(timeout, doDownload({
1135
+ url: url,
1136
+ callbackId: callbackId
1137
+ }), function (ms) {
1138
+ invokeServiceCallbackHandler(callbackId, {
1139
+ errMsg: "downloadFile:fail timeout in " + ms + "ms."
1140
+ });
1141
+ });
1142
+ }
1143
+ };
1144
+ function doDownload(_a) {
1145
+ var url = _a.url, callbackId = _a.callbackId, filePath = _a.filePath, header = _a.header;
1146
+ return __awaiter(this, void 0, void 0, function () {
1147
+ return __generator(this, function (_b) {
1148
+ requestSource(url, { header: header }, function (err, data, info) {
1149
+ var e = info.e, xhr = info.xhr;
1150
+ if (err != null) {
1151
+ invokeServiceCallbackHandler(callbackId, {
1152
+ errMsg: 'downloadFile:fail ' + err.message
1153
+ });
1154
+ return;
1155
+ }
1156
+ // 格式化
1157
+ var tempFilePath = toLocalTempFilePath(url);
1158
+ var usedFilePath = filePath || tempFilePath;
1159
+ localStorage.setItem(usedFilePath, data);
1160
+ var rspHeaders = xhr.getAllResponseHeaders();
1161
+ var headerMap = headersStr2Obj(rspHeaders);
1162
+ var rspCookies = (headerMap['set-cookie'] || '').split(',');
1163
+ // 推送两个事件
1164
+ dispatchServiceEvent(onTaskProgressUpdate, {
1165
+ cookies: [],
1166
+ progress: 100,
1167
+ totalBytesExpectedToWrite: e.loaded,
1168
+ totalBytesWritten: e.loaded
1169
+ });
1170
+ dispatchServiceEvent(onTaskHeadersReceived, {
1171
+ cookies: rspCookies,
1172
+ header: headerMap
1173
+ });
1174
+ var processedTempFilePath = processTempFilePath(tempFilePath, url);
1175
+ invokeServiceCallbackHandler(callbackId, {
1176
+ filePath: filePath,
1177
+ tempFilePath: filePath ? undefined : processedTempFilePath,
1178
+ profile: [],
1179
+ statusCode: 200,
1180
+ errMsg: 'downloadFile:ok'
1181
+ });
1182
+ });
1183
+ return [2 /*return*/];
1184
+ });
1185
+ });
1186
+ }
1187
+ function processTempFilePath(tempFilePath, url) {
1188
+ var arr = tempFilePath.split('.');
1189
+ var suffix = arr[arr.length - 1];
1190
+ if (imgSets.has('.' + suffix)) {
1191
+ return url;
1192
+ }
1193
+ return tempFilePath;
1194
+ }
1195
+
1196
+ var globalApis = {
1197
+ getGlobalVariables: function (data) {
1198
+ var variable = data.variable;
1199
+ if (variable === '_launchOption') {
1200
+ // 先写死
1201
+ return {
1202
+ _launchOption: launchOption
1203
+ };
1204
+ }
1205
+ return null;
1206
+ },
1207
+ // 上报的
1208
+ reportApmMonitor: function (data) { },
1209
+ addPerformance: function () { },
1210
+ // dom渲染完成
1211
+ // 这里关闭加载遮罩
1212
+ initReady: function () {
1213
+ //
1214
+ },
1215
+ updateAppData: function () { },
1216
+ injectHtmlCallback: function (data, cbId, from) {
1217
+ if (from === 'service') {
1218
+ getServiceIframeManager().events.emit(ServiceIframeManagerEventNames.onInjectHTMLCallback);
1219
+ }
1220
+ },
1221
+ pageScrollTo: function (opts, callbackId) {
1222
+ var scrollTop = opts.scrollTop; opts.duration;
1223
+ var curPage = router.currPage;
1224
+ var innerW = curPage.getWindow();
1225
+ innerW === null || innerW === void 0 ? void 0 : innerW.scrollTo({
1226
+ top: scrollTop,
1227
+ behavior: "smooth",
1228
+ });
1229
+ return {
1230
+ errMsg: 'pageScrollTo:ok'
1231
+ };
1232
+ }
1233
+ };
1234
+
1235
+ var wxConfig = null;
1236
+ function setWxConfig(v) {
1237
+ wxConfig = v;
1238
+ }
1239
+ function getWxConfig() {
1240
+ if (wxConfig == null) {
1241
+ throw new Error("WxConfig is not ready.");
1242
+ }
1243
+ return wxConfig;
1244
+ }
1245
+
1246
+ var WebFrameEventBus = new eventemitter3();
1247
+ function emitAppDataChangeEvent(params) {
1248
+ var payload = __assign({}, params.data);
1249
+ var wxConfig = getWxConfig();
1250
+ var currPath = payload.options.path;
1251
+ var pages = wxConfig.windows.pages;
1252
+ if (pages != null && pages[currPath]) {
1253
+ payload.windowConfig = pages[currPath];
1254
+ }
1255
+ payload.pages = router.allPages;
1256
+ WebFrameEventBus.emit('appDataChange', payload);
1257
+ }
1258
+ function emitUpdateAppDataEvent() {
1259
+ var payload = {};
1260
+ var wxConfig = getWxConfig();
1261
+ var currPage = router.currPage;
1262
+ var currPath = currPage.pagePath.replace(/\.html$/, '');
1263
+ var pages = wxConfig.windows.pages;
1264
+ if (pages != null && pages[currPath]) {
1265
+ payload.windowConfig = pages[currPath];
1266
+ }
1267
+ payload.pages = router.allPages;
1268
+ payload.currPage = currPath;
1269
+ WebFrameEventBus.emit('updateAppData', payload);
1270
+ }
1271
+ function emitTabItemChangedEvent(pagePath) {
1272
+ var payload = {};
1273
+ var wxConfig = getWxConfig();
1274
+ var currPath = pagePath;
1275
+ var pages = wxConfig.windows.pages;
1276
+ if (pages != null && pages[currPath]) {
1277
+ payload.windowConfig = pages[currPath];
1278
+ }
1279
+ WebFrameEventBus.emit('tabItemChanged', payload);
1280
+ }
1281
+ function initWebFrame(config) {
1282
+ if (typeof window.__initWebFrame === 'undefined')
1283
+ return;
1284
+ WebFrameEventBus.on('NavigatorBarTools:onMore', function () {
1285
+ console.log('onMore');
1286
+ });
1287
+ WebFrameEventBus.on('NavigatorBarTools:onClose', function () {
1288
+ console.log('onClose');
1289
+ });
1290
+ WebFrameEventBus.on('NavigatorBar:onBack', function () {
1291
+ routeApis.navigateBack({ delta: 1 });
1292
+ console.log('onBack');
1293
+ });
1294
+ WebFrameEventBus.on('TabBar:change', function (data) {
1295
+ dispatchServiceEvent('onTabItemTap', {
1296
+ index: data.index,
1297
+ pagePath: data.item.pagePath,
1298
+ text: data.item.text
1299
+ });
1300
+ routeApis.switchTab({ url: data.item.pagePath }, -1);
1301
+ emitTabItemChangedEvent(data.item.pagePath);
1302
+ });
1303
+ WebFrameEventBus.on('invokeCallbackHandler', function (payload) {
1304
+ invokeServiceCallbackHandler(payload.callbackId, payload.data);
1305
+ });
1306
+ //
1307
+ window.__initWebFrame(config, WebFrameEventBus);
1308
+ }
1309
+
1310
+ var interactionApis = {
1311
+ hideToast: function (opts) {
1312
+ WebFrameEventBus.emit('hideToast', opts);
1313
+ return { errMsg: 'hideToast:ok' };
1314
+ },
1315
+ showToast: function (opts) {
1316
+ WebFrameEventBus.emit('showToast', opts);
1317
+ return { errMsg: 'showToast:ok' };
1318
+ },
1319
+ showLoading: function (opts) {
1320
+ WebFrameEventBus.emit('showLoading', opts);
1321
+ return { errMsg: 'showLoading:ok' };
1322
+ },
1323
+ hideLoading: function (opts) {
1324
+ WebFrameEventBus.emit('hideLoading', opts);
1325
+ return { errMsg: 'hideLoading:ok' };
1326
+ },
1327
+ showModal: function (opts, callbackId) {
1328
+ WebFrameEventBus.emit('showModal', opts, callbackId);
1329
+ },
1330
+ showActionSheet: function (opts, callbackId) {
1331
+ WebFrameEventBus.emit('showActionSheet', opts, callbackId);
1332
+ }
1333
+ };
1334
+
1335
+ var LoadSubPackageTaskManager = /** @class */ (function () {
1336
+ function LoadSubPackageTaskManager(opts) {
1337
+ this.taskId = opts.taskId;
1338
+ this.moduleName = opts.moduleName;
1339
+ this.projectType = opts.projectType;
1340
+ this.status = 'none';
1341
+ }
1342
+ LoadSubPackageTaskManager.prototype.notifyProgressUpdate = function (state, extra) {
1343
+ dispatchServiceEvent(onLoadSubPackageTaskStateChange, __assign({ moduleName: this.moduleName, state: state, taskId: this.taskId }, extra));
1344
+ };
1345
+ LoadSubPackageTaskManager.prototype.injectScript = function () { };
1346
+ LoadSubPackageTaskManager.prototype.getEntry = function () { };
1347
+ LoadSubPackageTaskManager.prototype.load = function () {
1348
+ return __awaiter(this, void 0, void 0, function () {
1349
+ return __generator(this, function (_a) {
1350
+ switch (_a.label) {
1351
+ case 0:
1352
+ this.notifyProgressUpdate('progressUpdate', { progress: 0 });
1353
+ return [4 /*yield*/, delay(15)
1354
+ // 这部分是解压的
1355
+ ];
1356
+ case 1:
1357
+ _a.sent();
1358
+ // 这部分是解压的
1359
+ this.notifyProgressUpdate('progressUpdate', { progress: 50 });
1360
+ return [4 /*yield*/, delay(30)
1361
+ // 这部分是插入脚本
1362
+ ];
1363
+ case 2:
1364
+ _a.sent();
1365
+ // 这部分是插入脚本
1366
+ this.injectScript();
1367
+ this.notifyProgressUpdate('progressUpdate', { progress: 100 });
1368
+ return [4 /*yield*/, delay(15)
1369
+ // 提示完成
1370
+ ];
1371
+ case 3:
1372
+ _a.sent();
1373
+ // 提示完成
1374
+ this.status = 'success';
1375
+ this.notifyProgressUpdate('success', {
1376
+ entryPath: this.getEntry()
1377
+ });
1378
+ return [2 /*return*/];
1379
+ }
1380
+ });
1381
+ });
1382
+ };
1383
+ return LoadSubPackageTaskManager;
1384
+ }());
1385
+
1386
+ function generateScriptContent(projectType, opts) {
1387
+ if (projectType === miniGame) {
1388
+ return "<script charset=\"utf-8\" src=\"" + opts.moduleName + "game.js\"></script>";
1389
+ }
1390
+ if (projectType === miniProgram) {
1391
+ return opts.content;
1392
+ }
1393
+ throw Error('unsupported projectType: ' + projectType);
1394
+ }
1395
+ function generateEntryPath(projectType, opts) {
1396
+ if (projectType === miniGame) {
1397
+ return opts.moduleName + "game.js";
1398
+ }
1399
+ return '';
1400
+ }
1401
+
1402
+ var LoadGameSubPackageTaskManager = /** @class */ (function (_super) {
1403
+ __extends(LoadGameSubPackageTaskManager, _super);
1404
+ function LoadGameSubPackageTaskManager(opts) {
1405
+ return _super.call(this, __assign(__assign({}, opts), { projectType: miniGame })) || this;
1406
+ }
1407
+ LoadGameSubPackageTaskManager.prototype.injectScript = function () {
1408
+ var serviceFrameManager = getIframeManager(serviceIframeId);
1409
+ var innerWindow = serviceFrameManager.getWindow();
1410
+ innerWindow.injectHtml(innerWindow.document.body, {
1411
+ content: generateScriptContent(this.projectType, {
1412
+ moduleName: this.moduleName
1413
+ })
1414
+ });
1415
+ };
1416
+ LoadGameSubPackageTaskManager.prototype.getEntry = function () {
1417
+ return generateEntryPath(this.projectType, {
1418
+ moduleName: this.moduleName
1419
+ });
1420
+ };
1421
+ return LoadGameSubPackageTaskManager;
1422
+ }(LoadSubPackageTaskManager));
1423
+
1424
+ var taskId = 0;
1425
+ var taskManagerMap = {};
1426
+ var loadSubpackageApis = {
1427
+ // 游戏分包特有的加载接口
1428
+ createLoadSubPackageTask: function (_a) {
1429
+ var moduleName = _a.moduleName;
1430
+ var manager = taskManagerMap[moduleName];
1431
+ if (manager && manager.status === 'success') {
1432
+ return {
1433
+ errMsg: 'createLoadSubPackageTask:fail sub package already loaded.'
1434
+ };
1435
+ }
1436
+ ++taskId;
1437
+ var taskIdStr = String(taskId);
1438
+ manager = new LoadGameSubPackageTaskManager({ taskId: taskIdStr, moduleName: moduleName });
1439
+ taskManagerMap[moduleName] = manager;
1440
+ manager.load();
1441
+ return {
1442
+ errMsg: 'createLoadSubPackageTask:ok',
1443
+ loadTaskId: taskIdStr
1444
+ };
1445
+ }
1446
+ };
1447
+
1448
+ var navApis = {
1449
+ showNavigationBarLoading: function () {
1450
+ WebFrameEventBus.emit('showNavigationBarLoading');
1451
+ return {
1452
+ errMsg: "showNavigationBarLoading:ok"
1453
+ };
1454
+ },
1455
+ setNavigationBarTitle: function (opts) {
1456
+ WebFrameEventBus.emit('setNavigationBarTitle', opts);
1457
+ return {
1458
+ errMsg: "setNavigationBarTitle:ok"
1459
+ };
1460
+ },
1461
+ setNavigationBarColor: function (opts) {
1462
+ WebFrameEventBus.emit('setNavigationBarColor', opts);
1463
+ return {
1464
+ errMsg: "setNavigationBarColor:ok"
1465
+ };
1466
+ },
1467
+ hideNavigationBarLoading: function () {
1468
+ WebFrameEventBus.emit('hideNavigationBarLoading');
1469
+ return {
1470
+ errMsg: "hideNavigationBarLoading:ok"
1471
+ };
1472
+ },
1473
+ hideHomeButton: function () {
1474
+ }
1475
+ };
1476
+
1477
+ // TODO: 已经加载的子包 不需要加载
1478
+ function ensureBundleLoaded(request, done) {
1479
+ var subPackageInfo = tryFindSubPackageInfo(request);
1480
+ if (subPackageInfo != null && !isLoadedPackage(subPackageInfo.root)) {
1481
+ loadSubPackage(subPackageInfo, done);
1482
+ }
1483
+ else {
1484
+ done();
1485
+ }
1486
+ }
1487
+ function tryFindSubPackageInfo(path) {
1488
+ path = path.replace(/\.html$/, '');
1489
+ var wxConfig = getWxConfig();
1490
+ var subPackages = wxConfig.subpackages;
1491
+ if (Array.isArray(subPackages) && subPackages.length > 0) {
1492
+ return subPackages.find(function (item) {
1493
+ return item.pageFullPath.includes(path);
1494
+ });
1495
+ }
1496
+ return null;
1497
+ }
1498
+ function loadSubPackage(subPackageInfo, done) {
1499
+ var service = getIframeManager(serviceIframeId);
1500
+ service.events.once(ServiceIframeManagerEventNames.onInjectHTMLCallback, done);
1501
+ service.loadSubBundle(subPackageInfo.root, subPackageInfo.packageName + '.js');
1502
+ }
1503
+ function getSlots(wxConfig) {
1504
+ var tabBarConfig = wxConfig.tabBar;
1505
+ if (tabBarConfig == null) {
1506
+ return [wxConfig.root];
1507
+ }
1508
+ else {
1509
+ var tabList = tabBarConfig.list || [];
1510
+ if (tabList.length === 0) {
1511
+ return [wxConfig.root];
1512
+ }
1513
+ return tabBarConfig.list.map(function (item) { return item.pagePath; });
1514
+ }
1515
+ }
1516
+ function initFirstPageByWxConfig(wxConfig) {
1517
+ var slots = getSlots(wxConfig);
1518
+ router.initFirstPage(slots, wxConfig.root);
1519
+ }
1520
+
1521
+ var routeApis = {
1522
+ navigateTo: function (_a, callbackId) {
1523
+ var url = _a.url;
1524
+ if (router.stack.length > 10) {
1525
+ return {
1526
+ errMsg: 'navigateTo:fail 已到达页面栈上限:10。'
1527
+ };
1528
+ }
1529
+ var _b = resolveUrl(url), path = _b.path, query = _b.query;
1530
+ ensureBundleLoaded(path, function () {
1531
+ var nextPage = router.go(path);
1532
+ getServiceIframeManager().events.once(ServiceIframeManagerEventNames.onViewDOMContentLoaded, function () {
1533
+ dispatchServiceEvent('onAppRoute', {
1534
+ path: path,
1535
+ openType: 'navigateTo',
1536
+ options: undefined,
1537
+ pipMode: '',
1538
+ query: query,
1539
+ webviewId: nextPage.webviewId
1540
+ }, nextPage.webviewId);
1541
+ });
1542
+ });
1543
+ return { errMsg: 'navigateTo:ok' };
1544
+ },
1545
+ navigateBack: function (_a) {
1546
+ var delta = _a.delta;
1547
+ try {
1548
+ router.back(delta);
1549
+ }
1550
+ catch (error) {
1551
+ return {
1552
+ errMsg: "navigateBack:fail " + error.message
1553
+ };
1554
+ }
1555
+ var currPage = router.currPage;
1556
+ dispatchServiceEvent('onAppRoute', {
1557
+ path: currPage.pagePath,
1558
+ openType: 'navigateBack',
1559
+ options: { delta: delta },
1560
+ pipMode: '',
1561
+ query: undefined,
1562
+ webviewId: currPage.webviewId
1563
+ }, currPage.webviewId);
1564
+ // 不是异步 可以直接返回结果
1565
+ return { errMsg: 'navigateBack:ok' };
1566
+ },
1567
+ reLaunch: function (_a, cbId) {
1568
+ var url = _a.url;
1569
+ var _b = resolveUrl(url), path = _b.path, query = _b.query;
1570
+ ensureBundleLoaded(path, function () {
1571
+ router.reLaunch(url);
1572
+ var currPage = router.currPage;
1573
+ getServiceIframeManager().events.once(ServiceIframeManagerEventNames.onViewDOMContentLoaded, function () {
1574
+ dispatchServiceEvent('onAppRoute', {
1575
+ path: path,
1576
+ openType: 'reLaunch',
1577
+ options: undefined,
1578
+ pipMode: '',
1579
+ query: query,
1580
+ webviewId: currPage.webviewId
1581
+ }, currPage.webviewId);
1582
+ invokeServiceCallbackHandler(cbId, {
1583
+ errMsg: 'reLaunch:ok'
1584
+ });
1585
+ });
1586
+ });
1587
+ },
1588
+ redirectTo: function (_a, callbackId) {
1589
+ var url = _a.url;
1590
+ // 不允许跳转到 tabbar 页面
1591
+ var _b = resolveUrl(url), path = _b.path, query = _b.query;
1592
+ ensureBundleLoaded(path, function () {
1593
+ try {
1594
+ router.redirectTo(path);
1595
+ }
1596
+ catch (error) {
1597
+ invokeServiceCallbackHandler(callbackId, {
1598
+ errMsg: "redirectTo:fail " + error.message
1599
+ });
1600
+ return;
1601
+ }
1602
+ var currPage = router.currPage;
1603
+ getServiceIframeManager().events.once(ServiceIframeManagerEventNames.onViewDOMContentLoaded, function () {
1604
+ dispatchServiceEvent('onAppRoute', {
1605
+ path: path,
1606
+ openType: 'redirectTo',
1607
+ options: undefined,
1608
+ pipMode: '',
1609
+ query: query,
1610
+ webviewId: currPage.webviewId
1611
+ }, currPage.webviewId);
1612
+ invokeServiceCallbackHandler(callbackId, {
1613
+ errMsg: 'redirectTo:ok'
1614
+ });
1615
+ });
1616
+ });
1617
+ },
1618
+ switchTab: function (_a, callbackId) {
1619
+ var url = _a.url;
1620
+ var _b = resolveUrl(url), path = _b.path, query = _b.query;
1621
+ ensureBundleLoaded(path, function () {
1622
+ try {
1623
+ router.switch(path);
1624
+ }
1625
+ catch (error) {
1626
+ invokeServiceCallbackHandler(callbackId, {
1627
+ errMsg: "switchTab:fail " + error.message
1628
+ });
1629
+ return;
1630
+ }
1631
+ var currPage = router.currPage;
1632
+ if (currPage.isReady) {
1633
+ dispatchServiceEvent('onAppRoute', {
1634
+ path: path,
1635
+ openType: 'switchTab',
1636
+ options: undefined,
1637
+ pipMode: '',
1638
+ query: query,
1639
+ webviewId: currPage.webviewId
1640
+ }, currPage.webviewId);
1641
+ invokeServiceCallbackHandler(callbackId, {
1642
+ errMsg: 'switchTab:ok'
1643
+ });
1644
+ }
1645
+ else {
1646
+ getServiceIframeManager().events.once(ServiceIframeManagerEventNames.onViewDOMContentLoaded, function () {
1647
+ dispatchServiceEvent('onAppRoute', {
1648
+ path: path,
1649
+ openType: 'switchTab',
1650
+ options: undefined,
1651
+ pipMode: '',
1652
+ query: query,
1653
+ webviewId: currPage.webviewId
1654
+ }, currPage.webviewId);
1655
+ invokeServiceCallbackHandler(callbackId, {
1656
+ errMsg: 'switchTab:ok'
1657
+ });
1658
+ });
1659
+ }
1660
+ });
1661
+ }
1662
+ };
1663
+
1664
+ var localStorageApis = {
1665
+ getStorageSync: function (opts) {
1666
+ var res = localStorage.getItem(opts.key);
1667
+ try {
1668
+ // @ts-expect-error
1669
+ return JSON.parse(res);
1670
+ }
1671
+ catch (error) {
1672
+ return res;
1673
+ }
1674
+ },
1675
+ setStorageSync: function (opts) {
1676
+ localStorage.setItem(opts.key, opts.data);
1677
+ return { errMsg: 'setStorageSync:ok' };
1678
+ },
1679
+ removeStorageSync: function (opts) {
1680
+ localStorage.removeItem(opts.key);
1681
+ return { errMsg: 'removeStorageSync:ok' };
1682
+ }
1683
+ };
1684
+
1685
+ function getCurrentDeviceOrientation() {
1686
+ var system = getSystem();
1687
+ if (system === 'Android' || system === 'IOS') {
1688
+ return window.matchMedia('(orientation: portrait)').matches
1689
+ ? 'portrait'
1690
+ : 'landscape';
1691
+ }
1692
+ // web
1693
+ return 'landscape';
1694
+ }
1695
+
1696
+ var system = {
1697
+ onMemoryWarning: function () {
1698
+ console.error('The onMemoryWarning api is not implement.');
1699
+ },
1700
+ showShareMenu: function () {
1701
+ console.error('The showShareMenu api is not implement.');
1702
+ },
1703
+ getSystemInfoSync: function () {
1704
+ var resolutionRatio = 750; // 这个要通过原生注入
1705
+ var statusBarHeight = 22; // 这个要通过原生注入
1706
+ var pixelRatio = resolutionRatio / window.innerWidth;
1707
+ return {
1708
+ deviceOrientation: getCurrentDeviceOrientation(),
1709
+ devicePixelRatio: pixelRatio,
1710
+ screenWidth: window.innerWidth,
1711
+ screenHeight: window.innerHeight,
1712
+ SDKVersion: '2.26.0',
1713
+ appVersion: '2.37.0',
1714
+ batteryLevel: 98,
1715
+ benchmarkLevel: 1,
1716
+ bluetoothEnabled: false,
1717
+ brand: 'devtools',
1718
+ cameraAuthorized: true,
1719
+ deviceId: '11D22B6D-B5D8-4C24-AF42-8C959C95A2E6',
1720
+ enableDebug: true,
1721
+ errMsg: 'getSystemInfoSync:ok',
1722
+ fontSizeSetting: 15,
1723
+ frameworkVersion: '3.1.7',
1724
+ inFinChat: true,
1725
+ language: 'zh_CN',
1726
+ locationAuthorized: true,
1727
+ locationEnabled: true,
1728
+ microphoneAuthorized: true,
1729
+ mode: 'default',
1730
+ model: 'iPhone 5',
1731
+ notificationAuthorized: true,
1732
+ pixelRatio: pixelRatio,
1733
+ platform: 'devtools',
1734
+ statusBarHeight: statusBarHeight,
1735
+ system: getSystem(),
1736
+ theme: undefined,
1737
+ version: '8.0.28 ',
1738
+ windowHeight: window.innerHeight,
1739
+ windowWidth: window.innerWidth,
1740
+ safeArea: {
1741
+ height: window.innerHeight - statusBarHeight,
1742
+ widows: window.innerWidth,
1743
+ top: statusBarHeight,
1744
+ left: 0,
1745
+ right: 0
1746
+ }
1747
+ };
1748
+ },
1749
+ };
1750
+
1751
+ var injectetSDK = false;
1752
+ function injectSDKScript() {
1753
+ if (injectetSDK)
1754
+ return;
1755
+ var query = resolveUrl(location.search).query;
1756
+ var tempUrl = window.__sdkUrlTemplate;
1757
+ if (tempUrl != null && query.extType != null) {
1758
+ var sdkUrl = tempUrl.replace('$1', query.extType);
1759
+ var script = document.createElement('script');
1760
+ script.setAttribute('charset', 'utf-8');
1761
+ script.src = sdkUrl;
1762
+ document.body.appendChild(script);
1763
+ console.log('inject sdk script:', sdkUrl);
1764
+ injectetSDK = true;
1765
+ }
1766
+ }
1767
+
1768
+ var customEventHanders = {
1769
+ // 通知 native
1770
+ serviceStart: function (e) {
1771
+ setWxConfig(e.params);
1772
+ var params = e.params;
1773
+ initFirstPageByWxConfig(params);
1774
+ initWebFrame(params);
1775
+ },
1776
+ // 通知 native
1777
+ serviceReady: function (e) {
1778
+ injectSDKScript();
1779
+ var params = e.params, webviewIds = e.webviewIds;
1780
+ var manager = getServiceIframeManager();
1781
+ var webviewId = webviewIds[0];
1782
+ if (manager.isReady)
1783
+ return;
1784
+ router.initSlotWebviewId(webviewId);
1785
+ manager.events.once(ServiceIframeManagerEventNames.onViewDOMContentLoaded, function () {
1786
+ dispatchServiceEvent('onAppRoute', {
1787
+ path: params.root,
1788
+ openType: 'appLaunch',
1789
+ options: undefined,
1790
+ pipMode: '',
1791
+ query: undefined,
1792
+ webviewId: webviewId
1793
+ }, webviewId);
1794
+ });
1795
+ dispatchServiceEvent('onServiceReadyDone', __assign(__assign({}, launchOption), { webviewId: webviewId }), webviewId);
1796
+ manager.isReady = true;
1797
+ },
1798
+ // view 事件
1799
+ DOMContentLoaded: function (e) {
1800
+ var params = e.params, from = e.from; e.webviewIds; var event = e.event, webviewId = e.webviewId;
1801
+ var manager = getIframeManager(serviceIframeId);
1802
+ if (from === Terminal.View) {
1803
+ dispatchServiceEvent(event, params, webviewId);
1804
+ manager.events.emit(ServiceIframeManagerEventNames.onViewDOMContentLoaded);
1805
+ }
1806
+ else {
1807
+ console.error('not implement for ' + from);
1808
+ }
1809
+ },
1810
+ // 通知 native
1811
+ onLaunchCalled: function (e) { },
1812
+ // 通知 native
1813
+ viewReady: function () {
1814
+ var page = router.currPage;
1815
+ if (page != null) {
1816
+ page.isReady = true;
1817
+ page.injectScript();
1818
+ page.show();
1819
+ }
1820
+ },
1821
+ // 通知 native
1822
+ DOMReady: function () { },
1823
+ // 通知 service 调 原生方法
1824
+ INVOKE_METHOD: function (e) {
1825
+ var params = e.params, from = e.from; e.webviewIds; var event = e.event, webviewId = e.webviewId;
1826
+ if (from === Terminal.View) {
1827
+ dispatchServiceEvent(event, params, webviewId);
1828
+ }
1829
+ else {
1830
+ console.error('not implement for ' + from);
1831
+ }
1832
+ },
1833
+ // 双向的
1834
+ vdSync: function (e) {
1835
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event, webviewId = e.webviewId;
1836
+ if (from === Terminal.View) {
1837
+ dispatchServiceEvent(event, params, webviewId);
1838
+ }
1839
+ else {
1840
+ dispatchViewEvent(event, params, webviewIds);
1841
+ }
1842
+ },
1843
+ // 双向的(待定)
1844
+ vdSyncBatch: function (e) {
1845
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event, webviewId = e.webviewId;
1846
+ if (from === Terminal.View) {
1847
+ dispatchServiceEvent(event, params, webviewId);
1848
+ }
1849
+ else {
1850
+ dispatchViewEvent(event, params, webviewIds);
1851
+ }
1852
+ },
1853
+ // 进入页面
1854
+ appDataChange: function (e) {
1855
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event; e.webviewId;
1856
+ if (from === Terminal.View) {
1857
+ console.error('not implement for ' + from);
1858
+ }
1859
+ else {
1860
+ emitAppDataChangeEvent(params);
1861
+ dispatchViewEvent(event, params, webviewIds);
1862
+ }
1863
+ },
1864
+ // 退出页面
1865
+ __updateAppData: function (e) {
1866
+ emitUpdateAppDataEvent();
1867
+ },
1868
+ pageonshow: function (e) {
1869
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event; e.webviewId;
1870
+ if (from === Terminal.View) {
1871
+ console.error('not implement for ' + from);
1872
+ }
1873
+ else {
1874
+ dispatchViewEvent(event, params, webviewIds);
1875
+ }
1876
+ },
1877
+ requestLoadFontFace: function (e) {
1878
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event; e.webviewId;
1879
+ if (from === Terminal.View) {
1880
+ console.error('not implement for ' + from);
1881
+ }
1882
+ else {
1883
+ dispatchViewEvent(event, params, webviewIds);
1884
+ }
1885
+ },
1886
+ requestLoadGlobalFontFaces: function (e) {
1887
+ var params = e.params, from = e.from; e.webviewIds; var event = e.event, webviewId = e.webviewId;
1888
+ if (from === Terminal.View) {
1889
+ dispatchServiceEvent(event, params, webviewId);
1890
+ }
1891
+ else {
1892
+ console.error('not implement for ' + from);
1893
+ }
1894
+ },
1895
+ responseLoadGlobalFontFaces: function (e) {
1896
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event; e.webviewId;
1897
+ if (from === Terminal.View) {
1898
+ console.error('not implement for ' + from);
1899
+ }
1900
+ else {
1901
+ dispatchViewEvent(event, params, webviewIds);
1902
+ }
1903
+ },
1904
+ PAGE_EVENT: function (e) {
1905
+ var params = e.params, from = e.from; e.webviewIds; var event = e.event, webviewId = e.webviewId;
1906
+ if (from === Terminal.View) {
1907
+ dispatchServiceEvent(event, params, webviewId);
1908
+ }
1909
+ else {
1910
+ console.error('not implement for ' + from);
1911
+ }
1912
+ },
1913
+ setKeyboardValue: function (e) {
1914
+ var params = e.params, from = e.from, webviewIds = e.webviewIds, event = e.event; e.webviewId;
1915
+ if (from === Terminal.View) {
1916
+ console.error('not implement for ' + from);
1917
+ }
1918
+ else {
1919
+ dispatchViewEvent(event, params, webviewIds);
1920
+ }
1921
+ },
1922
+ SPECIAL_PAGE_EVENT: function (e) {
1923
+ var params = e.params, from = e.from; e.webviewIds; var event = e.event, webviewId = e.webviewId;
1924
+ if (from === Terminal.View) {
1925
+ dispatchServiceEvent(event, params, webviewId);
1926
+ }
1927
+ else {
1928
+ console.error('not implement for ' + from);
1929
+ }
1930
+ },
1931
+ gameServiceReady: function () {
1932
+ injectSDKScript();
1933
+ },
1934
+ gameConfigUpdate: function (config) {
1935
+ var _a;
1936
+ var currentDeviceOrientation = getCurrentDeviceOrientation();
1937
+ if (config.deviceOrientation !== currentDeviceOrientation) {
1938
+ // 切换到游戏配置的设备方向
1939
+ (_a = getTarget()) === null || _a === void 0 ? void 0 : _a.invokeHandler('setDeviceOrientation', {
1940
+ value: config.deviceOrientation
1941
+ }, -1);
1942
+ }
1943
+ }
1944
+ };
1945
+
1946
+ var customEventPreifx = 'custom_event_';
1947
+ var APIS = __assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign({}, globalApis), fsUtilApis), loadSubpackageApis), routeApis), interactionApis), localStorageApis), system), navApis);
1948
+ var FinChatJSCore = {
1949
+ invokeHandler: function (data) {
1950
+ debug && console.log('invokeHander', data);
1951
+ var C = data.C, paramsString = data.paramsString; data.type; var from = data.from, callbackId = data.callbackId;
1952
+ var params = JSON.parse(paramsString);
1953
+ // @ts-expect-error
1954
+ var api = APIS[C];
1955
+ if (api != null) {
1956
+ var res = api(params, callbackId, from);
1957
+ return res;
1958
+ }
1959
+ else {
1960
+ var adapter = getTarget();
1961
+ if (adapter != null) {
1962
+ return adapter.invokeHandler(C, params, callbackId);
1963
+ }
1964
+ }
1965
+ },
1966
+ publishHandler: function (data) {
1967
+ debug && console.log('publishHandler', data);
1968
+ var event = data.event, from = data.from, paramsString = data.paramsString, webviewId = data.webviewId, webviewIds = data.webviewIds;
1969
+ var eventWithoutPrefix = event.replace(customEventPreifx, '');
1970
+ var params = JSON.parse(paramsString);
1971
+ var handler = customEventHanders[eventWithoutPrefix];
1972
+ if (handler != null) {
1973
+ // @ts-ignore
1974
+ handler({
1975
+ event: event,
1976
+ params: params,
1977
+ from: from,
1978
+ webviewId: webviewId,
1979
+ webviewIds: Terminal.Service === from && webviewIds ? JSON.parse(webviewIds) : undefined // 来自 service 事件存在
1980
+ });
1981
+ }
1982
+ else {
1983
+ var adapter = getTarget();
1984
+ if (adapter != null) {
1985
+ adapter.publishHandler(eventWithoutPrefix, params, from);
1986
+ }
1987
+ }
1988
+ },
1989
+ webInvokeHandler: function (data) {
1990
+ debug && console.log('webInvokeHander', data);
1991
+ },
1992
+ webPublishHandler: function (data) {
1993
+ debug && console.log('webPublishHandler', data);
1994
+ }
1995
+ };
1996
+ // @ts-ignore
1997
+ window.FinChatJSCore = FinChatJSCore;
1998
+
1999
+ }));