@oox/client 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/browser.js CHANGED
@@ -1,1144 +1,1104 @@
1
1
  var oox = (function (exports) {
2
- 'use strict';
3
-
4
- function getDefaultExportFromCjs (x) {
5
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
6
- }
7
-
8
- var events = {exports: {}};
9
-
10
- var hasRequiredEvents;
11
-
12
- function requireEvents () {
13
- if (hasRequiredEvents) return events.exports;
14
- hasRequiredEvents = 1;
15
-
16
- var R = typeof Reflect === 'object' ? Reflect : null;
17
- var ReflectApply = R && typeof R.apply === 'function'
18
- ? R.apply
19
- : function ReflectApply(target, receiver, args) {
20
- return Function.prototype.apply.call(target, receiver, args);
21
- };
22
-
23
- var ReflectOwnKeys;
24
- if (R && typeof R.ownKeys === 'function') {
25
- ReflectOwnKeys = R.ownKeys;
26
- } else if (Object.getOwnPropertySymbols) {
27
- ReflectOwnKeys = function ReflectOwnKeys(target) {
28
- return Object.getOwnPropertyNames(target)
29
- .concat(Object.getOwnPropertySymbols(target));
30
- };
31
- } else {
32
- ReflectOwnKeys = function ReflectOwnKeys(target) {
33
- return Object.getOwnPropertyNames(target);
34
- };
35
- }
36
-
37
- function ProcessEmitWarning(warning) {
38
- if (console && console.warn) console.warn(warning);
39
- }
40
-
41
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
42
- return value !== value;
43
- };
44
-
45
- function EventEmitter() {
46
- EventEmitter.init.call(this);
47
- }
48
- events.exports = EventEmitter;
49
- events.exports.once = once;
50
-
51
- // Backwards-compat with node 0.10.x
52
- EventEmitter.EventEmitter = EventEmitter;
53
-
54
- EventEmitter.prototype._events = undefined;
55
- EventEmitter.prototype._eventsCount = 0;
56
- EventEmitter.prototype._maxListeners = undefined;
57
-
58
- // By default EventEmitters will print a warning if more than 10 listeners are
59
- // added to it. This is a useful default which helps finding memory leaks.
60
- var defaultMaxListeners = 10;
61
-
62
- function checkListener(listener) {
63
- if (typeof listener !== 'function') {
64
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
65
- }
66
- }
67
-
68
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
69
- enumerable: true,
70
- get: function() {
71
- return defaultMaxListeners;
72
- },
73
- set: function(arg) {
74
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
75
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
76
- }
77
- defaultMaxListeners = arg;
78
- }
79
- });
80
-
81
- EventEmitter.init = function() {
82
-
83
- if (this._events === undefined ||
84
- this._events === Object.getPrototypeOf(this)._events) {
85
- this._events = Object.create(null);
86
- this._eventsCount = 0;
87
- }
88
-
89
- this._maxListeners = this._maxListeners || undefined;
90
- };
91
-
92
- // Obviously not all Emitters should be limited to 10. This function allows
93
- // that to be increased. Set to zero for unlimited.
94
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
95
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
96
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
97
- }
98
- this._maxListeners = n;
99
- return this;
100
- };
101
-
102
- function _getMaxListeners(that) {
103
- if (that._maxListeners === undefined)
104
- return EventEmitter.defaultMaxListeners;
105
- return that._maxListeners;
106
- }
107
-
108
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
109
- return _getMaxListeners(this);
110
- };
111
-
112
- EventEmitter.prototype.emit = function emit(type) {
113
- var args = [];
114
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
115
- var doError = (type === 'error');
116
-
117
- var events = this._events;
118
- if (events !== undefined)
119
- doError = (doError && events.error === undefined);
120
- else if (!doError)
121
- return false;
122
-
123
- // If there is no 'error' event listener then throw.
124
- if (doError) {
125
- var er;
126
- if (args.length > 0)
127
- er = args[0];
128
- if (er instanceof Error) {
129
- // Note: The comments on the `throw` lines are intentional, they show
130
- // up in Node's output if this results in an unhandled exception.
131
- throw er; // Unhandled 'error' event
132
- }
133
- // At least give some kind of context to the user
134
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
135
- err.context = er;
136
- throw err; // Unhandled 'error' event
137
- }
138
-
139
- var handler = events[type];
140
-
141
- if (handler === undefined)
142
- return false;
143
-
144
- if (typeof handler === 'function') {
145
- ReflectApply(handler, this, args);
146
- } else {
147
- var len = handler.length;
148
- var listeners = arrayClone(handler, len);
149
- for (var i = 0; i < len; ++i)
150
- ReflectApply(listeners[i], this, args);
151
- }
152
-
153
- return true;
154
- };
155
-
156
- function _addListener(target, type, listener, prepend) {
157
- var m;
158
- var events;
159
- var existing;
160
-
161
- checkListener(listener);
162
-
163
- events = target._events;
164
- if (events === undefined) {
165
- events = target._events = Object.create(null);
166
- target._eventsCount = 0;
167
- } else {
168
- // To avoid recursion in the case that type === "newListener"! Before
169
- // adding it to the listeners, first emit "newListener".
170
- if (events.newListener !== undefined) {
171
- target.emit('newListener', type,
172
- listener.listener ? listener.listener : listener);
173
-
174
- // Re-assign `events` because a newListener handler could have caused the
175
- // this._events to be assigned to a new object
176
- events = target._events;
177
- }
178
- existing = events[type];
179
- }
180
-
181
- if (existing === undefined) {
182
- // Optimize the case of one listener. Don't need the extra array object.
183
- existing = events[type] = listener;
184
- ++target._eventsCount;
185
- } else {
186
- if (typeof existing === 'function') {
187
- // Adding the second element, need to change to array.
188
- existing = events[type] =
189
- prepend ? [listener, existing] : [existing, listener];
190
- // If we've already got an array, just append.
191
- } else if (prepend) {
192
- existing.unshift(listener);
193
- } else {
194
- existing.push(listener);
195
- }
196
-
197
- // Check for listener leak
198
- m = _getMaxListeners(target);
199
- if (m > 0 && existing.length > m && !existing.warned) {
200
- existing.warned = true;
201
- // No error code for this since it is a Warning
202
- // eslint-disable-next-line no-restricted-syntax
203
- var w = new Error('Possible EventEmitter memory leak detected. ' +
204
- existing.length + ' ' + String(type) + ' listeners ' +
205
- 'added. Use emitter.setMaxListeners() to ' +
206
- 'increase limit');
207
- w.name = 'MaxListenersExceededWarning';
208
- w.emitter = target;
209
- w.type = type;
210
- w.count = existing.length;
211
- ProcessEmitWarning(w);
212
- }
213
- }
214
-
215
- return target;
216
- }
217
-
218
- EventEmitter.prototype.addListener = function addListener(type, listener) {
219
- return _addListener(this, type, listener, false);
220
- };
221
-
222
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
223
-
224
- EventEmitter.prototype.prependListener =
225
- function prependListener(type, listener) {
226
- return _addListener(this, type, listener, true);
227
- };
228
-
229
- function onceWrapper() {
230
- if (!this.fired) {
231
- this.target.removeListener(this.type, this.wrapFn);
232
- this.fired = true;
233
- if (arguments.length === 0)
234
- return this.listener.call(this.target);
235
- return this.listener.apply(this.target, arguments);
236
- }
237
- }
238
-
239
- function _onceWrap(target, type, listener) {
240
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
241
- var wrapped = onceWrapper.bind(state);
242
- wrapped.listener = listener;
243
- state.wrapFn = wrapped;
244
- return wrapped;
245
- }
246
-
247
- EventEmitter.prototype.once = function once(type, listener) {
248
- checkListener(listener);
249
- this.on(type, _onceWrap(this, type, listener));
250
- return this;
251
- };
252
-
253
- EventEmitter.prototype.prependOnceListener =
254
- function prependOnceListener(type, listener) {
255
- checkListener(listener);
256
- this.prependListener(type, _onceWrap(this, type, listener));
257
- return this;
258
- };
259
-
260
- // Emits a 'removeListener' event if and only if the listener was removed.
261
- EventEmitter.prototype.removeListener =
262
- function removeListener(type, listener) {
263
- var list, events, position, i, originalListener;
264
-
265
- checkListener(listener);
266
-
267
- events = this._events;
268
- if (events === undefined)
269
- return this;
270
-
271
- list = events[type];
272
- if (list === undefined)
273
- return this;
274
-
275
- if (list === listener || list.listener === listener) {
276
- if (--this._eventsCount === 0)
277
- this._events = Object.create(null);
278
- else {
279
- delete events[type];
280
- if (events.removeListener)
281
- this.emit('removeListener', type, list.listener || listener);
282
- }
283
- } else if (typeof list !== 'function') {
284
- position = -1;
285
-
286
- for (i = list.length - 1; i >= 0; i--) {
287
- if (list[i] === listener || list[i].listener === listener) {
288
- originalListener = list[i].listener;
289
- position = i;
290
- break;
291
- }
292
- }
293
-
294
- if (position < 0)
295
- return this;
296
-
297
- if (position === 0)
298
- list.shift();
299
- else {
300
- spliceOne(list, position);
301
- }
302
-
303
- if (list.length === 1)
304
- events[type] = list[0];
305
-
306
- if (events.removeListener !== undefined)
307
- this.emit('removeListener', type, originalListener || listener);
308
- }
309
-
310
- return this;
311
- };
312
-
313
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
314
-
315
- EventEmitter.prototype.removeAllListeners =
316
- function removeAllListeners(type) {
317
- var listeners, events, i;
318
-
319
- events = this._events;
320
- if (events === undefined)
321
- return this;
322
-
323
- // not listening for removeListener, no need to emit
324
- if (events.removeListener === undefined) {
325
- if (arguments.length === 0) {
326
- this._events = Object.create(null);
327
- this._eventsCount = 0;
328
- } else if (events[type] !== undefined) {
329
- if (--this._eventsCount === 0)
330
- this._events = Object.create(null);
331
- else
332
- delete events[type];
333
- }
334
- return this;
335
- }
336
-
337
- // emit removeListener for all listeners on all events
338
- if (arguments.length === 0) {
339
- var keys = Object.keys(events);
340
- var key;
341
- for (i = 0; i < keys.length; ++i) {
342
- key = keys[i];
343
- if (key === 'removeListener') continue;
344
- this.removeAllListeners(key);
345
- }
346
- this.removeAllListeners('removeListener');
347
- this._events = Object.create(null);
348
- this._eventsCount = 0;
349
- return this;
350
- }
351
-
352
- listeners = events[type];
353
-
354
- if (typeof listeners === 'function') {
355
- this.removeListener(type, listeners);
356
- } else if (listeners !== undefined) {
357
- // LIFO order
358
- for (i = listeners.length - 1; i >= 0; i--) {
359
- this.removeListener(type, listeners[i]);
360
- }
361
- }
362
-
363
- return this;
364
- };
365
-
366
- function _listeners(target, type, unwrap) {
367
- var events = target._events;
368
-
369
- if (events === undefined)
370
- return [];
371
-
372
- var evlistener = events[type];
373
- if (evlistener === undefined)
374
- return [];
375
-
376
- if (typeof evlistener === 'function')
377
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
378
-
379
- return unwrap ?
380
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
381
- }
382
-
383
- EventEmitter.prototype.listeners = function listeners(type) {
384
- return _listeners(this, type, true);
385
- };
386
-
387
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
388
- return _listeners(this, type, false);
389
- };
390
-
391
- EventEmitter.listenerCount = function(emitter, type) {
392
- if (typeof emitter.listenerCount === 'function') {
393
- return emitter.listenerCount(type);
394
- } else {
395
- return listenerCount.call(emitter, type);
396
- }
397
- };
398
-
399
- EventEmitter.prototype.listenerCount = listenerCount;
400
- function listenerCount(type) {
401
- var events = this._events;
402
-
403
- if (events !== undefined) {
404
- var evlistener = events[type];
405
-
406
- if (typeof evlistener === 'function') {
407
- return 1;
408
- } else if (evlistener !== undefined) {
409
- return evlistener.length;
410
- }
411
- }
412
-
413
- return 0;
414
- }
415
-
416
- EventEmitter.prototype.eventNames = function eventNames() {
417
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
418
- };
419
-
420
- function arrayClone(arr, n) {
421
- var copy = new Array(n);
422
- for (var i = 0; i < n; ++i)
423
- copy[i] = arr[i];
424
- return copy;
425
- }
426
-
427
- function spliceOne(list, index) {
428
- for (; index + 1 < list.length; index++)
429
- list[index] = list[index + 1];
430
- list.pop();
431
- }
432
-
433
- function unwrapListeners(arr) {
434
- var ret = new Array(arr.length);
435
- for (var i = 0; i < ret.length; ++i) {
436
- ret[i] = arr[i].listener || arr[i];
437
- }
438
- return ret;
439
- }
440
-
441
- function once(emitter, name) {
442
- return new Promise(function (resolve, reject) {
443
- function errorListener(err) {
444
- emitter.removeListener(name, resolver);
445
- reject(err);
446
- }
447
-
448
- function resolver() {
449
- if (typeof emitter.removeListener === 'function') {
450
- emitter.removeListener('error', errorListener);
451
- }
452
- resolve([].slice.call(arguments));
453
- }
454
- eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
455
- if (name !== 'error') {
456
- addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
457
- }
458
- });
459
- }
460
-
461
- function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
462
- if (typeof emitter.on === 'function') {
463
- eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
464
- }
465
- }
466
-
467
- function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
468
- if (typeof emitter.on === 'function') {
469
- if (flags.once) {
470
- emitter.once(name, listener);
471
- } else {
472
- emitter.on(name, listener);
473
- }
474
- } else if (typeof emitter.addEventListener === 'function') {
475
- // EventTarget does not have `error` event semantics like Node
476
- // EventEmitters, we do not listen for `error` events here.
477
- emitter.addEventListener(name, function wrapListener(arg) {
478
- // IE does not have builtin `{ once: true }` support so we
479
- // have to do it manually.
480
- if (flags.once) {
481
- emitter.removeEventListener(name, wrapListener);
482
- }
483
- listener(arg);
484
- });
485
- } else {
486
- throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
487
- }
488
- }
489
- return events.exports;
490
- }
491
-
492
- var eventsExports = requireEvents();
493
- var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
494
-
495
- function getAllCallablePropertyNames(obj) {
496
- if (!obj)
497
- return [];
498
- let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
499
- const bans = ["constructor", "__defineGetter__", "__defineSetter__",
500
- "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
501
- "isPrototypeOf", "propertyIsEnumerable", "toString",
502
- "valueOf", "__proto__", "toLocaleString"];
503
- do {
504
- tmpProps = Object.getOwnPropertyNames(obj);
505
- index = -1, size = tmpProps.length;
506
- while (++index < size) {
507
- tmpProp = tmpProps[index];
508
- if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
509
- props.push(tmpProp);
510
- }
511
- }
512
- } while (obj = Object.getPrototypeOf(obj));
513
- return props;
514
- }
515
- function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
516
- let keys = getAllCallablePropertyNames(methods);
517
- for (const key of keys) {
518
- /**
519
- * @type {Function}
520
- */
521
- let val = methods[key];
522
- if ('function' === typeof val) {
523
- const action = nameStack.concat(key).join('.');
524
- // 原函数绑定
525
- sourceKVMethods.set(action, val);
526
- // 壳函数绑定
527
- kvMethods.set(action, val.bind(methods));
528
- }
529
- else {
530
- genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
531
- }
532
- }
533
- return { kvMethods, sourceKVMethods };
534
- }
535
-
536
- const contexts = {};
537
- function parseTraceIdByStack(stack) {
538
- const [traceRow] = stack.split('/').filter(row => row.includes('OOX_TRACER.<computed>'));
539
- if (traceRow) {
540
- return traceRow.match(/(?<=as\s).*?(?=\s|\])/g)?.[0] || null;
541
- }
542
- else {
543
- return null;
544
- }
545
- }
546
- function enterWith(context) {
547
- const traceId = context.traceId || '';
548
- contexts[traceId] = context;
549
- }
550
- function exitWith(context) {
551
- const traceId = context.traceId || '';
552
- delete contexts[traceId];
553
- }
554
- function getContext$1() {
555
- const traceId = parseTraceIdByStack(new Error().stack || '') || '';
556
- return contexts[traceId] || null;
557
- }
558
-
559
- const eventHub = new eventsExports.EventEmitter();
560
- /**
561
- * sourceMethods => methods
562
- */
563
- let sourceMethods = {};
564
- /**
565
- * the kvMethods is all actions refs [has bind this]
566
- */
567
- const kvMethods = new Map();
568
- const sourceKVMethods = new Map();
569
- function setMethods(methods) {
570
- sourceMethods = methods;
571
- kvMethods.clear();
572
- sourceKVMethods.clear();
573
- genKVMethods(methods, kvMethods, sourceKVMethods);
574
- }
575
- function getMethods() {
576
- return sourceMethods;
577
- }
578
- function on(event, listener) {
579
- eventHub.on(event, listener);
580
- }
581
- function once(event, listener) {
582
- eventHub.once(event, listener);
583
- }
584
- function off(event, listener) {
585
- eventHub.off(event, listener);
586
- }
587
- function emit(event, ...args) {
588
- return eventHub.emit(event, ...args);
589
- }
590
- /**
591
- * Call an Function on RPC server
592
- * @param action
593
- * @param params
594
- * @param context
595
- * @returns
596
- */
597
- async function call(action, params = [], context) {
598
- if (!Array.isArray(params))
599
- params = [params];
600
- const { traceId } = context;
601
- emit('call:start', Date.now(), action, params, context);
602
- const returns = {
603
- traceId,
604
- success: true
605
- };
606
- const OOX_TRACER = {};
607
- OOX_TRACER[traceId] = async (action, [...params], context) => {
608
- return await execute(action, [...params], context);
609
- };
610
- enterWith(context);
611
- try {
612
- const result = await OOX_TRACER[traceId](action, [...params], context);
613
- returns.body = result;
614
- emit('call:success', Date.now(), action, params, context, result);
615
- }
616
- catch (error) {
617
- returns.success = false;
618
- returns.error = {
619
- message: error.message,
620
- stack: error.stack
621
- };
622
- emit('call:fail', Date.now(), action, params, context, error);
623
- }
624
- finally {
625
- exitWith(context);
626
- return returns;
627
- }
628
- }
629
- async function execute(action, params, context) {
630
- const __proxy = '__proxy', _proxy = '_proxy';
631
- if (__proxy === action || _proxy === action || action.endsWith(_proxy))
632
- throw new Error('Invalid Action[' + action + ']');
633
- const methods = kvMethods;
634
- // 目标函数
635
- const target = methods.get(action);
636
- // 目标代理函数
637
- const targetProxy = methods.get(action + _proxy);
638
- // 即不存在目标也不存在目标代理时, 报错函数不存在
639
- if (!target && !targetProxy)
640
- throw new Error('Unknown Action [' + action + ']');
641
- // ============================ PROXY BEGIN ============================
642
- // 最顶层代理
643
- const topProxy = methods.get(__proxy);
644
- if (topProxy) {
645
- const proxyReturns = await topProxy(action, params, context);
646
- if (proxyReturns !== undefined)
647
- return proxyReturns;
648
- }
649
- // 'x.y.z' => [ 'x', 'y', 'z' ]
650
- const nameStack = action.split('.'), size = nameStack.length - 1;
651
- let index = -1, proxyPrefix = '';
652
- // 根代理遍历
653
- while (++index < size) {
654
- // x.
655
- // x.y.
656
- proxyPrefix += nameStack[index] + '.';
657
- // x.__proxy
658
- // x.y.__proxy
659
- const rootProxy = methods.get(proxyPrefix + __proxy);
660
- // x.__proxy ( 'y.z', ... )
661
- // x.y.__proxy ( 'z', ... )
662
- if (rootProxy) {
663
- const proxyReturns = await rootProxy(nameStack.slice(index).join('.'), params, context);
664
- if (proxyReturns !== undefined)
665
- return proxyReturns;
666
- }
667
- }
668
- // 同级代理
669
- const layerProxy = methods.get(proxyPrefix + _proxy);
670
- if (layerProxy) {
671
- const proxyReturns = await layerProxy(nameStack[index], params, context);
672
- if (proxyReturns !== undefined)
673
- return proxyReturns;
674
- }
675
- if (targetProxy) {
676
- const proxyReturns = await targetProxy(params, context);
677
- if (proxyReturns !== undefined)
678
- return proxyReturns;
679
- }
680
- // ============================= PROXY END =============================
681
- // make sure target action execute after all proxies
682
- if (target) {
683
- return await target(...params);
684
- }
685
- }
686
-
687
- class Config {
688
- id = '';
689
- name = 'DEFAULT_NAME';
690
- }
691
- const config = new Config();
692
-
693
- class AppContext {
694
- // 请求溯源ID
695
- traceId = '';
696
- }
697
- class Context extends AppContext {
698
- // 请求溯源IP
699
- sourceIP = '';
700
- // 请求者IP
701
- ip = '';
702
- // 请求者名称
703
- caller = 'anonymous';
704
- // 请求者ID (长连接专用)
705
- callerId = '';
706
- // 请求者连接把柄
707
- connection;
708
- constructor(context) {
709
- super();
710
- if (context) {
711
- if ('toJSON' in context && typeof context.toJSON !== 'function') {
712
- throw new Error('Context.toJSON must be a function');
713
- }
714
- Object.assign(this, context);
715
- }
716
- }
717
- toJSON() {
718
- const context = Object.assign({}, this);
719
- delete context.connection;
720
- return context;
721
- }
722
- }
723
- let genTraceIdFunction = () => crypto.randomUUID();
724
- function setGenTraceIdFunction(fn) {
725
- genTraceIdFunction = fn;
726
- }
727
- /**
728
- * 生成随机不重复id
729
- */
730
- function genTraceId() {
731
- return genTraceIdFunction();
732
- }
733
- function genContext(context) {
734
- const newContext = new Context(context);
735
- if (!newContext.traceId)
736
- newContext.traceId = genTraceId();
737
- if (!newContext.sourceIP)
738
- newContext.sourceIP = newContext.ip;
739
- return newContext;
740
- }
741
- function getContext() {
742
- return getContext$1() || genContext();
743
- }
744
-
745
- class KeepAliveConnectionError extends Error {
746
- connection;
747
- constructor(message, connection) {
748
- super(message);
749
- this.connection = connection;
750
- }
751
- }
752
- class KeepAliveConnection extends EventEmitter {
753
- // 是否为注册服务连接
754
- isRegistry = false;
755
- // 连接是否可用
756
- #enabled = false;
757
- data;
758
- nativeConnection;
759
- adapter;
760
- constructor(adapter, nativeConnection, data) {
761
- super();
762
- this.adapter = adapter;
763
- this.nativeConnection = nativeConnection;
764
- this.data = Object.assign(data, {
765
- adapter: adapter.name,
766
- });
767
- this.on('connect', () => {
768
- emit('keepalive:connect', this);
769
- });
770
- this.on('disconnect', () => {
771
- emit('keepalive:disconnect', this);
772
- });
773
- }
774
- /**
775
- * 设置连接是否可用,并自动触发enabled或disabled事件
776
- * @param enabled 是否可用
777
- */
778
- set enabled(enabled) {
779
- if (enabled !== this.#enabled) {
780
- this.#enabled = enabled;
781
- this.emit(enabled ? 'enabled' : 'disabled');
782
- if (enabled) {
783
- enabledKeepAliveConnections.add(this);
784
- }
785
- else {
786
- enabledKeepAliveConnections.remove(this);
787
- }
788
- }
789
- }
790
- get enabled() {
791
- return this.#enabled;
792
- }
793
- /**
794
- * enable & mount connection
795
- * @param params
796
- * @returns
797
- */
798
- ready(params) {
799
- // 连接已就绪,不允许重复就绪
800
- if (this.enabled)
801
- return;
802
- const { id, name } = params;
803
- keepAliveConnections.remove(this);
804
- // 更新连接数据
805
- this.data.id = id;
806
- this.data.name = name;
807
- keepAliveConnections.add(this);
808
- this.enabled = true;
809
- }
810
- disconnect() {
811
- this.enabled = false;
812
- this.nativeConnection.disconnect();
813
- }
814
- }
815
- class KeepAliveConnectionStore {
816
- #map = new Map();
817
- entries() {
818
- return this.#map.entries();
819
- }
820
- getConnectionsOfService(name) {
821
- return this.#map.get(name) || new Map();
822
- }
823
- has(name, id) {
824
- const connections = this.#map.get(name);
825
- if (!connections)
826
- return false;
827
- return connections.has(id);
828
- }
829
- get(name, id) {
830
- const connections = this.#map.get(name);
831
- if (!connections)
832
- return null;
833
- return connections.get(id) || null;
834
- }
835
- add(connection) {
836
- const { name, id } = connection.data;
837
- const connections = this.#map.get(name);
838
- if (connections) {
839
- connections.set(id, connection);
840
- }
841
- else {
842
- this.#map.set(name, new Map([[id, connection]]));
843
- }
844
- }
845
- remove(name, id) {
846
- if (name instanceof KeepAliveConnection) {
847
- id = name.data.id;
848
- name = name.data.name;
849
- }
850
- const connections = this.#map.get(name);
851
- if (connections && id !== undefined) {
852
- connections.delete(id);
853
- }
854
- }
855
- }
856
- const keepAliveConnectionAdapters = new Map();
857
- const keepAliveConnections = new KeepAliveConnectionStore();
858
- const enabledKeepAliveConnections = new KeepAliveConnectionStore();
859
- function addKeepAliveConnection(connection) {
860
- if (keepAliveConnections.has(connection.data.name, connection.data.id)) {
861
- connection.disconnect();
862
- throw new KeepAliveConnectionError('Connection already exists', connection);
863
- }
864
- keepAliveConnections.add(connection);
865
- }
866
- function removeKeepAliveConnection(arg1, arg2) {
867
- if (typeof arg1 === 'string') {
868
- const connection = keepAliveConnections.get(arg1, arg2);
869
- if (connection)
870
- connection.disconnect();
871
- keepAliveConnections.remove(arg1, arg2);
872
- enabledKeepAliveConnections.remove(arg1, arg2);
873
- }
874
- else {
875
- arg1.disconnect();
876
- keepAliveConnections.remove(arg1);
877
- enabledKeepAliveConnections.remove(arg1);
878
- }
879
- }
880
- /**
881
- * random connection select for default load balance policy
882
- * @param name service name
883
- * @returns selected connection
884
- */
885
- let loadBalancePolicy = (name) => {
886
- const connections = enabledKeepAliveConnections.getConnectionsOfService(name);
887
- if (!connections || !connections.size)
888
- return null;
889
- const arrayConnections = Array.from(connections.values());
890
- const index = Math.floor(Math.random() * arrayConnections.length);
891
- return arrayConnections[index];
892
- };
893
- function setLoadBalancePolicy(policy) {
894
- loadBalancePolicy = policy;
895
- }
896
- async function rpc(arg1, action, params, context) {
897
- if (!context || !context.traceId) {
898
- context = getContext();
899
- }
900
- let connection = null;
901
- if (arg1 instanceof KeepAliveConnection) {
902
- connection = arg1;
903
- }
904
- else if ('string' === typeof arg1) {
905
- connection = loadBalancePolicy(arg1);
906
- }
907
- else
908
- throw new Error(`Unknown rpc arg1<${arg1}>`);
909
- if (!connection)
910
- throw new Error(`Connection<${arg1}> not found`);
911
- return connection.adapter.rpc(connection, action, params, context);
912
- }
913
-
914
- class SampleKeepAliveConnectionAdapter {
915
- /**
916
- * 通知连接列表
917
- */
918
- ['registry:notify'](connection, datas) {
919
- connection.nativeConnection.emit(this.OOXEvent.REGISTRY_NOTIFY, datas);
920
- }
921
- /**
922
- * 订阅连接列表
923
- */
924
- ['registry:subscribe'](connection, query) {
925
- connection.nativeConnection.emit(this.OOXEvent.REGISTRY_SUBSCRIBE, query);
926
- }
927
- bindConnectionEvents(connection) {
928
- const socket = connection.nativeConnection;
929
- socket.on(this.OOXEvent.READY, (params) => {
930
- connection.ready(params);
931
- });
932
- socket.on(this.OOXEvent.ENABLED, () => {
933
- connection.enabled = true;
934
- });
935
- socket.on(this.OOXEvent.DISABLED, () => {
936
- connection.enabled = false;
937
- });
938
- socket.on(this.OOXEvent.DISCONNECT, () => {
939
- socket.removeAllListeners();
940
- removeKeepAliveConnection(connection);
941
- connection.emit('disconnect');
942
- });
943
- socket.on(this.OOXEvent.CONNECT, () => {
944
- connection.emit('connect');
945
- });
946
- socket.on(this.OOXEvent.ERROR, (error) => {
947
- socket.removeAllListeners();
948
- removeKeepAliveConnection(connection);
949
- connection.emit('error', new KeepAliveConnectionError(error.message, connection));
950
- });
951
- }
952
- async open(identify) {
953
- const connection = this.newConnection(identify);
954
- addKeepAliveConnection(connection);
955
- this.bindConnectionEvents(connection);
956
- this.bindCall(connection);
957
- try {
958
- await new Promise((resolve, reject) => {
959
- connection.once('enabled', resolve);
960
- connection.once('error', reject);
961
- connection.once('disconnect', () => {
962
- reject(new Error('disconnect'));
963
- });
964
- if (connection.nativeConnection.connect) {
965
- connection.nativeConnection.connect();
966
- }
967
- });
968
- }
969
- catch (error) {
970
- connection.removeAllListeners();
971
- removeKeepAliveConnection(connection);
972
- throw error;
973
- }
974
- return connection;
975
- }
976
- async close(connection) {
977
- connection.nativeConnection.disconnect();
978
- return Promise.resolve();
979
- }
980
- /**
981
- * 发送事件
982
- * @param socket
983
- * @param event
984
- * @param params
985
- */
986
- async emit(socket, event, params) {
987
- if (!socket.connected)
988
- throw new Error('Socket not connected');
989
- return await new Promise((resolve, reject) => {
990
- const onError = (reason) => {
991
- const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
992
- reject(new Error(message));
993
- };
994
- // RPC 执行时中断连接
995
- socket.once(this.OOXEvent.DISCONNECT, onError);
996
- socket.emit(event, ...params, (returns) => {
997
- socket.off(this.OOXEvent.DISCONNECT, onError);
998
- resolve(returns);
999
- });
1000
- });
1001
- }
1002
- /**
1003
- * RPC
1004
- */
1005
- async rpc(connection, action, params, context) {
1006
- if (!context)
1007
- context = getContext();
1008
- const miniContext = {
1009
- sourceIP: context.sourceIP,
1010
- traceId: context.traceId,
1011
- };
1012
- const { success, error, body } = await this.emit(connection.nativeConnection, this.OOXEvent.CALL, [action, params, miniContext]);
1013
- if (success)
1014
- return body;
1015
- else if (error)
1016
- throw new Error(error.message);
1017
- else
1018
- throw new Error('[RPC] Unknown Error');
1019
- }
1020
- /**
1021
- * 绑定 call 事件
1022
- * @param connection
1023
- */
1024
- bindCall(connection) {
1025
- const { id, name, ip } = connection.data;
1026
- connection.nativeConnection.on(this.OOXEvent.CALL, async (action, params, context, callback) => {
1027
- const validContext = new Context({
1028
- ...context,
1029
- ip: ip,
1030
- caller: name,
1031
- callerId: id,
1032
- connection
1033
- });
1034
- this.call(action, params, validContext, callback);
1035
- });
1036
- }
1037
- async call(action, params, context, callback) {
1038
- const returns = await call(action, params, context);
1039
- 'function' === typeof callback && callback(returns);
1040
- return returns;
1041
- }
1042
- }
1043
-
1044
- function info(...content) {
1045
- const context = getContext$1() || null;
1046
- emit('log', Date.now(), context, 'info', content);
1047
- }
1048
- function warn(...content) {
1049
- const context = getContext$1() || null;
1050
- emit('log', Date.now(), context, 'warn', content);
1051
- }
1052
- function error(...content) {
1053
- const context = getContext$1() || null;
1054
- emit('log', Date.now(), context, 'error', content);
1055
- }
1056
- function tag(name) {
1057
- const context = getContext$1() || null;
1058
- emit('log', Date.now(), context, 'tag', name);
1059
- }
1060
- function trace(name) {
1061
- const context = getContext$1() || null;
1062
- const trace = { stack: '' };
1063
- Error.captureStackTrace(trace);
1064
- const stack = trace.stack
1065
- .replace(/.*\n.*logger.js.*\n/, name || 'Untitle\n');
1066
- emit('log', Date.now(), context, 'trace', stack);
1067
- }
1068
-
1069
- var logger = /*#__PURE__*/Object.freeze({
1070
- __proto__: null,
1071
- error: error,
1072
- info: info,
1073
- tag: tag,
1074
- trace: trace,
1075
- warn: warn
1076
- });
1077
-
1078
- /**
1079
- * 为了不重复创建Proxy,这个对象用于保存各个RPC服务的各个属性Proxy
1080
- */
1081
- const rpcServiceAttrMap = Object.create(null);
1082
- function proxy(name, action = '') {
1083
- return new Proxy(function () { }, {
1084
- get(target, key) {
1085
- if (typeof key !== 'string')
1086
- return undefined;
1087
- const attrKey = action ? action + '.' + key : key;
1088
- const attrKeyPath = name + '.' + attrKey;
1089
- if (attrKeyPath in rpcServiceAttrMap) {
1090
- // 不重复创建Proxy
1091
- return rpcServiceAttrMap[attrKeyPath];
1092
- }
1093
- const attrProxy = proxy(name, attrKey);
1094
- rpcServiceAttrMap[attrKeyPath] = attrProxy;
1095
- return attrProxy;
1096
- },
1097
- has(target, key) {
1098
- if (typeof key !== 'string')
1099
- return false;
1100
- return true;
1101
- },
1102
- apply(target, thisArg, args) {
1103
- return rpc(name, action, args);
1104
- }
1105
- });
1106
- }
1107
-
1108
- exports.AppContext = AppContext;
1109
- exports.Config = Config;
1110
- exports.Context = Context;
1111
- exports.KeepAliveConnection = KeepAliveConnection;
1112
- exports.KeepAliveConnectionError = KeepAliveConnectionError;
1113
- exports.KeepAliveConnectionStore = KeepAliveConnectionStore;
1114
- exports.SampleKeepAliveConnectionAdapter = SampleKeepAliveConnectionAdapter;
1115
- exports.addKeepAliveConnection = addKeepAliveConnection;
1116
- exports.call = call;
1117
- exports.config = config;
1118
- exports.emit = emit;
1119
- exports.enabledKeepAliveConnections = enabledKeepAliveConnections;
1120
- exports.eventHub = eventHub;
1121
- exports.execute = execute;
1122
- exports.genContext = genContext;
1123
- exports.genTraceId = genTraceId;
1124
- exports.getContext = getContext;
1125
- exports.getMethods = getMethods;
1126
- exports.keepAliveConnectionAdapters = keepAliveConnectionAdapters;
1127
- exports.keepAliveConnections = keepAliveConnections;
1128
- exports.kvMethods = kvMethods;
1129
- exports.logger = logger;
1130
- exports.off = off;
1131
- exports.on = on;
1132
- exports.once = once;
1133
- exports.proxy = proxy;
1134
- exports.removeKeepAliveConnection = removeKeepAliveConnection;
1135
- exports.rpc = rpc;
1136
- exports.setGenTraceIdFunction = setGenTraceIdFunction;
1137
- exports.setLoadBalancePolicy = setLoadBalancePolicy;
1138
- exports.setMethods = setMethods;
1139
- exports.sourceKVMethods = sourceKVMethods;
1140
-
1141
- return exports;
2
+ 'use strict';
3
+
4
+ var events = {exports: {}};
5
+
6
+ var hasRequiredEvents;
7
+
8
+ function requireEvents () {
9
+ if (hasRequiredEvents) return events.exports;
10
+ hasRequiredEvents = 1;
11
+
12
+ var R = typeof Reflect === 'object' ? Reflect : null;
13
+ var ReflectApply = R && typeof R.apply === 'function'
14
+ ? R.apply
15
+ : function ReflectApply(target, receiver, args) {
16
+ return Function.prototype.apply.call(target, receiver, args);
17
+ };
18
+
19
+ var ReflectOwnKeys;
20
+ if (R && typeof R.ownKeys === 'function') {
21
+ ReflectOwnKeys = R.ownKeys;
22
+ } else if (Object.getOwnPropertySymbols) {
23
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
24
+ return Object.getOwnPropertyNames(target)
25
+ .concat(Object.getOwnPropertySymbols(target));
26
+ };
27
+ } else {
28
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
29
+ return Object.getOwnPropertyNames(target);
30
+ };
31
+ }
32
+
33
+ function ProcessEmitWarning(warning) {
34
+ if (console && console.warn) console.warn(warning);
35
+ }
36
+
37
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
38
+ return value !== value;
39
+ };
40
+
41
+ function EventEmitter() {
42
+ EventEmitter.init.call(this);
43
+ }
44
+ events.exports = EventEmitter;
45
+ events.exports.once = once;
46
+
47
+ // Backwards-compat with node 0.10.x
48
+ EventEmitter.EventEmitter = EventEmitter;
49
+
50
+ EventEmitter.prototype._events = undefined;
51
+ EventEmitter.prototype._eventsCount = 0;
52
+ EventEmitter.prototype._maxListeners = undefined;
53
+
54
+ // By default EventEmitters will print a warning if more than 10 listeners are
55
+ // added to it. This is a useful default which helps finding memory leaks.
56
+ var defaultMaxListeners = 10;
57
+
58
+ function checkListener(listener) {
59
+ if (typeof listener !== 'function') {
60
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
61
+ }
62
+ }
63
+
64
+ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
65
+ enumerable: true,
66
+ get: function() {
67
+ return defaultMaxListeners;
68
+ },
69
+ set: function(arg) {
70
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
71
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
72
+ }
73
+ defaultMaxListeners = arg;
74
+ }
75
+ });
76
+
77
+ EventEmitter.init = function() {
78
+
79
+ if (this._events === undefined ||
80
+ this._events === Object.getPrototypeOf(this)._events) {
81
+ this._events = Object.create(null);
82
+ this._eventsCount = 0;
83
+ }
84
+
85
+ this._maxListeners = this._maxListeners || undefined;
86
+ };
87
+
88
+ // Obviously not all Emitters should be limited to 10. This function allows
89
+ // that to be increased. Set to zero for unlimited.
90
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
91
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
92
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
93
+ }
94
+ this._maxListeners = n;
95
+ return this;
96
+ };
97
+
98
+ function _getMaxListeners(that) {
99
+ if (that._maxListeners === undefined)
100
+ return EventEmitter.defaultMaxListeners;
101
+ return that._maxListeners;
102
+ }
103
+
104
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
105
+ return _getMaxListeners(this);
106
+ };
107
+
108
+ EventEmitter.prototype.emit = function emit(type) {
109
+ var args = [];
110
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
111
+ var doError = (type === 'error');
112
+
113
+ var events = this._events;
114
+ if (events !== undefined)
115
+ doError = (doError && events.error === undefined);
116
+ else if (!doError)
117
+ return false;
118
+
119
+ // If there is no 'error' event listener then throw.
120
+ if (doError) {
121
+ var er;
122
+ if (args.length > 0)
123
+ er = args[0];
124
+ if (er instanceof Error) {
125
+ // Note: The comments on the `throw` lines are intentional, they show
126
+ // up in Node's output if this results in an unhandled exception.
127
+ throw er; // Unhandled 'error' event
128
+ }
129
+ // At least give some kind of context to the user
130
+ var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
131
+ err.context = er;
132
+ throw err; // Unhandled 'error' event
133
+ }
134
+
135
+ var handler = events[type];
136
+
137
+ if (handler === undefined)
138
+ return false;
139
+
140
+ if (typeof handler === 'function') {
141
+ ReflectApply(handler, this, args);
142
+ } else {
143
+ var len = handler.length;
144
+ var listeners = arrayClone(handler, len);
145
+ for (var i = 0; i < len; ++i)
146
+ ReflectApply(listeners[i], this, args);
147
+ }
148
+
149
+ return true;
150
+ };
151
+
152
+ function _addListener(target, type, listener, prepend) {
153
+ var m;
154
+ var events;
155
+ var existing;
156
+
157
+ checkListener(listener);
158
+
159
+ events = target._events;
160
+ if (events === undefined) {
161
+ events = target._events = Object.create(null);
162
+ target._eventsCount = 0;
163
+ } else {
164
+ // To avoid recursion in the case that type === "newListener"! Before
165
+ // adding it to the listeners, first emit "newListener".
166
+ if (events.newListener !== undefined) {
167
+ target.emit('newListener', type,
168
+ listener.listener ? listener.listener : listener);
169
+
170
+ // Re-assign `events` because a newListener handler could have caused the
171
+ // this._events to be assigned to a new object
172
+ events = target._events;
173
+ }
174
+ existing = events[type];
175
+ }
176
+
177
+ if (existing === undefined) {
178
+ // Optimize the case of one listener. Don't need the extra array object.
179
+ existing = events[type] = listener;
180
+ ++target._eventsCount;
181
+ } else {
182
+ if (typeof existing === 'function') {
183
+ // Adding the second element, need to change to array.
184
+ existing = events[type] =
185
+ prepend ? [listener, existing] : [existing, listener];
186
+ // If we've already got an array, just append.
187
+ } else if (prepend) {
188
+ existing.unshift(listener);
189
+ } else {
190
+ existing.push(listener);
191
+ }
192
+
193
+ // Check for listener leak
194
+ m = _getMaxListeners(target);
195
+ if (m > 0 && existing.length > m && !existing.warned) {
196
+ existing.warned = true;
197
+ // No error code for this since it is a Warning
198
+ // eslint-disable-next-line no-restricted-syntax
199
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
200
+ existing.length + ' ' + String(type) + ' listeners ' +
201
+ 'added. Use emitter.setMaxListeners() to ' +
202
+ 'increase limit');
203
+ w.name = 'MaxListenersExceededWarning';
204
+ w.emitter = target;
205
+ w.type = type;
206
+ w.count = existing.length;
207
+ ProcessEmitWarning(w);
208
+ }
209
+ }
210
+
211
+ return target;
212
+ }
213
+
214
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
215
+ return _addListener(this, type, listener, false);
216
+ };
217
+
218
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
219
+
220
+ EventEmitter.prototype.prependListener =
221
+ function prependListener(type, listener) {
222
+ return _addListener(this, type, listener, true);
223
+ };
224
+
225
+ function onceWrapper() {
226
+ if (!this.fired) {
227
+ this.target.removeListener(this.type, this.wrapFn);
228
+ this.fired = true;
229
+ if (arguments.length === 0)
230
+ return this.listener.call(this.target);
231
+ return this.listener.apply(this.target, arguments);
232
+ }
233
+ }
234
+
235
+ function _onceWrap(target, type, listener) {
236
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
237
+ var wrapped = onceWrapper.bind(state);
238
+ wrapped.listener = listener;
239
+ state.wrapFn = wrapped;
240
+ return wrapped;
241
+ }
242
+
243
+ EventEmitter.prototype.once = function once(type, listener) {
244
+ checkListener(listener);
245
+ this.on(type, _onceWrap(this, type, listener));
246
+ return this;
247
+ };
248
+
249
+ EventEmitter.prototype.prependOnceListener =
250
+ function prependOnceListener(type, listener) {
251
+ checkListener(listener);
252
+ this.prependListener(type, _onceWrap(this, type, listener));
253
+ return this;
254
+ };
255
+
256
+ // Emits a 'removeListener' event if and only if the listener was removed.
257
+ EventEmitter.prototype.removeListener =
258
+ function removeListener(type, listener) {
259
+ var list, events, position, i, originalListener;
260
+
261
+ checkListener(listener);
262
+
263
+ events = this._events;
264
+ if (events === undefined)
265
+ return this;
266
+
267
+ list = events[type];
268
+ if (list === undefined)
269
+ return this;
270
+
271
+ if (list === listener || list.listener === listener) {
272
+ if (--this._eventsCount === 0)
273
+ this._events = Object.create(null);
274
+ else {
275
+ delete events[type];
276
+ if (events.removeListener)
277
+ this.emit('removeListener', type, list.listener || listener);
278
+ }
279
+ } else if (typeof list !== 'function') {
280
+ position = -1;
281
+
282
+ for (i = list.length - 1; i >= 0; i--) {
283
+ if (list[i] === listener || list[i].listener === listener) {
284
+ originalListener = list[i].listener;
285
+ position = i;
286
+ break;
287
+ }
288
+ }
289
+
290
+ if (position < 0)
291
+ return this;
292
+
293
+ if (position === 0)
294
+ list.shift();
295
+ else {
296
+ spliceOne(list, position);
297
+ }
298
+
299
+ if (list.length === 1)
300
+ events[type] = list[0];
301
+
302
+ if (events.removeListener !== undefined)
303
+ this.emit('removeListener', type, originalListener || listener);
304
+ }
305
+
306
+ return this;
307
+ };
308
+
309
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
310
+
311
+ EventEmitter.prototype.removeAllListeners =
312
+ function removeAllListeners(type) {
313
+ var listeners, events, i;
314
+
315
+ events = this._events;
316
+ if (events === undefined)
317
+ return this;
318
+
319
+ // not listening for removeListener, no need to emit
320
+ if (events.removeListener === undefined) {
321
+ if (arguments.length === 0) {
322
+ this._events = Object.create(null);
323
+ this._eventsCount = 0;
324
+ } else if (events[type] !== undefined) {
325
+ if (--this._eventsCount === 0)
326
+ this._events = Object.create(null);
327
+ else
328
+ delete events[type];
329
+ }
330
+ return this;
331
+ }
332
+
333
+ // emit removeListener for all listeners on all events
334
+ if (arguments.length === 0) {
335
+ var keys = Object.keys(events);
336
+ var key;
337
+ for (i = 0; i < keys.length; ++i) {
338
+ key = keys[i];
339
+ if (key === 'removeListener') continue;
340
+ this.removeAllListeners(key);
341
+ }
342
+ this.removeAllListeners('removeListener');
343
+ this._events = Object.create(null);
344
+ this._eventsCount = 0;
345
+ return this;
346
+ }
347
+
348
+ listeners = events[type];
349
+
350
+ if (typeof listeners === 'function') {
351
+ this.removeListener(type, listeners);
352
+ } else if (listeners !== undefined) {
353
+ // LIFO order
354
+ for (i = listeners.length - 1; i >= 0; i--) {
355
+ this.removeListener(type, listeners[i]);
356
+ }
357
+ }
358
+
359
+ return this;
360
+ };
361
+
362
+ function _listeners(target, type, unwrap) {
363
+ var events = target._events;
364
+
365
+ if (events === undefined)
366
+ return [];
367
+
368
+ var evlistener = events[type];
369
+ if (evlistener === undefined)
370
+ return [];
371
+
372
+ if (typeof evlistener === 'function')
373
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
374
+
375
+ return unwrap ?
376
+ unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
377
+ }
378
+
379
+ EventEmitter.prototype.listeners = function listeners(type) {
380
+ return _listeners(this, type, true);
381
+ };
382
+
383
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
384
+ return _listeners(this, type, false);
385
+ };
386
+
387
+ EventEmitter.listenerCount = function(emitter, type) {
388
+ if (typeof emitter.listenerCount === 'function') {
389
+ return emitter.listenerCount(type);
390
+ } else {
391
+ return listenerCount.call(emitter, type);
392
+ }
393
+ };
394
+
395
+ EventEmitter.prototype.listenerCount = listenerCount;
396
+ function listenerCount(type) {
397
+ var events = this._events;
398
+
399
+ if (events !== undefined) {
400
+ var evlistener = events[type];
401
+
402
+ if (typeof evlistener === 'function') {
403
+ return 1;
404
+ } else if (evlistener !== undefined) {
405
+ return evlistener.length;
406
+ }
407
+ }
408
+
409
+ return 0;
410
+ }
411
+
412
+ EventEmitter.prototype.eventNames = function eventNames() {
413
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
414
+ };
415
+
416
+ function arrayClone(arr, n) {
417
+ var copy = new Array(n);
418
+ for (var i = 0; i < n; ++i)
419
+ copy[i] = arr[i];
420
+ return copy;
421
+ }
422
+
423
+ function spliceOne(list, index) {
424
+ for (; index + 1 < list.length; index++)
425
+ list[index] = list[index + 1];
426
+ list.pop();
427
+ }
428
+
429
+ function unwrapListeners(arr) {
430
+ var ret = new Array(arr.length);
431
+ for (var i = 0; i < ret.length; ++i) {
432
+ ret[i] = arr[i].listener || arr[i];
433
+ }
434
+ return ret;
435
+ }
436
+
437
+ function once(emitter, name) {
438
+ return new Promise(function (resolve, reject) {
439
+ function errorListener(err) {
440
+ emitter.removeListener(name, resolver);
441
+ reject(err);
442
+ }
443
+
444
+ function resolver() {
445
+ if (typeof emitter.removeListener === 'function') {
446
+ emitter.removeListener('error', errorListener);
447
+ }
448
+ resolve([].slice.call(arguments));
449
+ }
450
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
451
+ if (name !== 'error') {
452
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
453
+ }
454
+ });
455
+ }
456
+
457
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
458
+ if (typeof emitter.on === 'function') {
459
+ eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
460
+ }
461
+ }
462
+
463
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
464
+ if (typeof emitter.on === 'function') {
465
+ if (flags.once) {
466
+ emitter.once(name, listener);
467
+ } else {
468
+ emitter.on(name, listener);
469
+ }
470
+ } else if (typeof emitter.addEventListener === 'function') {
471
+ // EventTarget does not have `error` event semantics like Node
472
+ // EventEmitters, we do not listen for `error` events here.
473
+ emitter.addEventListener(name, function wrapListener(arg) {
474
+ // IE does not have builtin `{ once: true }` support so we
475
+ // have to do it manually.
476
+ if (flags.once) {
477
+ emitter.removeEventListener(name, wrapListener);
478
+ }
479
+ listener(arg);
480
+ });
481
+ } else {
482
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
483
+ }
484
+ }
485
+ return events.exports;
486
+ }
487
+
488
+ var eventsExports = requireEvents();
489
+
490
+ function getAllCallablePropertyNames(obj) {
491
+ if (!obj)
492
+ return [];
493
+ let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
494
+ const bans = ["constructor", "__defineGetter__", "__defineSetter__",
495
+ "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
496
+ "isPrototypeOf", "propertyIsEnumerable", "toString",
497
+ "valueOf", "__proto__", "toLocaleString"];
498
+ do {
499
+ tmpProps = Object.getOwnPropertyNames(obj);
500
+ index = -1, size = tmpProps.length;
501
+ while (++index < size) {
502
+ tmpProp = tmpProps[index];
503
+ if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
504
+ props.push(tmpProp);
505
+ }
506
+ }
507
+ } while (obj = Object.getPrototypeOf(obj));
508
+ return props;
509
+ }
510
+ function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
511
+ let keys = getAllCallablePropertyNames(methods);
512
+ for (const key of keys) {
513
+ /**
514
+ * @type {Function}
515
+ */
516
+ let val = methods[key];
517
+ if ('function' === typeof val) {
518
+ const action = nameStack.concat(key).join('.');
519
+ // 原函数绑定
520
+ sourceKVMethods.set(action, val);
521
+ // 壳函数绑定
522
+ kvMethods.set(action, val.bind(methods));
523
+ }
524
+ else {
525
+ genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
526
+ }
527
+ }
528
+ return { kvMethods, sourceKVMethods };
529
+ }
530
+
531
+ const contexts = {};
532
+ function parseTraceIdByStack(stack) {
533
+ const [traceRow] = stack.split('/').filter(row => row.includes('OOX_TRACER.<computed>'));
534
+ if (traceRow) {
535
+ return traceRow.match(/(?<=as\s).*?(?=\s|\])/g)?.[0] || null;
536
+ }
537
+ else {
538
+ return null;
539
+ }
540
+ }
541
+ function enterWith(context) {
542
+ const traceId = context.traceId || '';
543
+ contexts[traceId] = context;
544
+ }
545
+ function exitWith(context) {
546
+ const traceId = context.traceId || '';
547
+ delete contexts[traceId];
548
+ }
549
+ function getContext$1() {
550
+ const traceId = parseTraceIdByStack(new Error().stack || '') || '';
551
+ return contexts[traceId] || null;
552
+ }
553
+
554
+ const eventHub = new eventsExports.EventEmitter();
555
+ /**
556
+ * sourceMethods => methods
557
+ */
558
+ let sourceMethods = {};
559
+ /**
560
+ * the kvMethods is all actions refs [has bind this]
561
+ */
562
+ const kvMethods = new Map();
563
+ const sourceKVMethods = new Map();
564
+ function setMethods(methods) {
565
+ sourceMethods = methods;
566
+ kvMethods.clear();
567
+ sourceKVMethods.clear();
568
+ genKVMethods(methods, kvMethods, sourceKVMethods);
569
+ }
570
+ function getMethods() {
571
+ return sourceMethods;
572
+ }
573
+ function on(event, listener) {
574
+ eventHub.on(event, listener);
575
+ }
576
+ function once(event, listener) {
577
+ eventHub.once(event, listener);
578
+ }
579
+ function off(event, listener) {
580
+ eventHub.off(event, listener);
581
+ }
582
+ function emit(event, ...args) {
583
+ return eventHub.emit(event, ...args);
584
+ }
585
+ /**
586
+ * Call an Function on RPC server
587
+ * @param action
588
+ * @param params
589
+ * @param context
590
+ * @returns
591
+ */
592
+ async function call(action, params = [], context) {
593
+ if (!Array.isArray(params))
594
+ params = [params];
595
+ const { traceId } = context;
596
+ emit('call:start', Date.now(), action, params, context);
597
+ const returns = {
598
+ traceId,
599
+ success: true
600
+ };
601
+ const OOX_TRACER = {};
602
+ OOX_TRACER[traceId] = async (action, [...params], context) => {
603
+ return await execute(action, [...params], context);
604
+ };
605
+ enterWith(context);
606
+ try {
607
+ const result = await OOX_TRACER[traceId](action, [...params], context);
608
+ returns.body = result;
609
+ emit('call:success', Date.now(), action, params, context, result);
610
+ }
611
+ catch (error) {
612
+ returns.success = false;
613
+ returns.error = {
614
+ message: error.message,
615
+ stack: error.stack
616
+ };
617
+ emit('call:fail', Date.now(), action, params, context, error);
618
+ }
619
+ finally {
620
+ exitWith(context);
621
+ return returns;
622
+ }
623
+ }
624
+ async function execute(action, params, context) {
625
+ const __proxy = '__proxy', _proxy = '_proxy';
626
+ if (__proxy === action || _proxy === action || action.endsWith(_proxy))
627
+ throw new Error('Invalid Action[' + action + ']');
628
+ const methods = kvMethods;
629
+ // 目标函数
630
+ const target = methods.get(action);
631
+ // 目标代理函数
632
+ const targetProxy = methods.get(action + _proxy);
633
+ // 即不存在目标也不存在目标代理时, 报错函数不存在
634
+ if (!target && !targetProxy)
635
+ throw new Error('Unknown Action [' + action + ']');
636
+ // ============================ PROXY BEGIN ============================
637
+ // 最顶层代理
638
+ const topProxy = methods.get(__proxy);
639
+ if (topProxy) {
640
+ const proxyReturns = await topProxy(action, params, context);
641
+ if (proxyReturns !== undefined)
642
+ return proxyReturns;
643
+ }
644
+ // 'x.y.z' => [ 'x', 'y', 'z' ]
645
+ const nameStack = action.split('.'), size = nameStack.length - 1;
646
+ let index = -1, proxyPrefix = '';
647
+ // 根代理遍历
648
+ while (++index < size) {
649
+ // x.
650
+ // x.y.
651
+ proxyPrefix += nameStack[index] + '.';
652
+ // x.__proxy
653
+ // x.y.__proxy
654
+ const rootProxy = methods.get(proxyPrefix + __proxy);
655
+ // x.__proxy ( 'y.z', ... )
656
+ // x.y.__proxy ( 'z', ... )
657
+ if (rootProxy) {
658
+ const proxyReturns = await rootProxy(nameStack.slice(index).join('.'), params, context);
659
+ if (proxyReturns !== undefined)
660
+ return proxyReturns;
661
+ }
662
+ }
663
+ // 同级代理
664
+ const layerProxy = methods.get(proxyPrefix + _proxy);
665
+ if (layerProxy) {
666
+ const proxyReturns = await layerProxy(nameStack[index], params, context);
667
+ if (proxyReturns !== undefined)
668
+ return proxyReturns;
669
+ }
670
+ if (targetProxy) {
671
+ const proxyReturns = await targetProxy(params, context);
672
+ if (proxyReturns !== undefined)
673
+ return proxyReturns;
674
+ }
675
+ // ============================= PROXY END =============================
676
+ // make sure target action execute after all proxies
677
+ if (target) {
678
+ return await target(...params);
679
+ }
680
+ }
681
+
682
+ class Config {
683
+ id = '';
684
+ name = 'DEFAULT_NAME';
685
+ }
686
+ const config = new Config();
687
+
688
+ class AppContext {
689
+ // 请求溯源ID
690
+ traceId = '';
691
+ }
692
+ class Context extends AppContext {
693
+ // 请求溯源IP
694
+ sourceIP = '';
695
+ // 请求者IP
696
+ ip = '';
697
+ // 请求者名称
698
+ caller = 'anonymous';
699
+ // 请求者ID (长连接专用)
700
+ callerId = '';
701
+ // 请求者连接把柄
702
+ connection;
703
+ constructor(context) {
704
+ super();
705
+ if (context) {
706
+ if ('toJSON' in context && typeof context.toJSON !== 'function') {
707
+ throw new Error('Context.toJSON must be a function');
708
+ }
709
+ Object.assign(this, context);
710
+ }
711
+ }
712
+ toJSON() {
713
+ const context = Object.assign({}, this);
714
+ delete context.connection;
715
+ return context;
716
+ }
717
+ }
718
+ let genTraceIdFunction = () => crypto.randomUUID();
719
+ function setGenTraceIdFunction(fn) {
720
+ genTraceIdFunction = fn;
721
+ }
722
+ /**
723
+ * 生成随机不重复id
724
+ */
725
+ function genTraceId() {
726
+ return genTraceIdFunction();
727
+ }
728
+ function genContext(context) {
729
+ const newContext = new Context(context);
730
+ if (!newContext.traceId)
731
+ newContext.traceId = genTraceId();
732
+ if (!newContext.sourceIP)
733
+ newContext.sourceIP = newContext.ip;
734
+ return newContext;
735
+ }
736
+ function getContext() {
737
+ return getContext$1() || genContext();
738
+ }
739
+
740
+ class KeepAliveConnectionError extends Error {
741
+ connection;
742
+ constructor(message, connection) {
743
+ super(message);
744
+ this.connection = connection;
745
+ }
746
+ }
747
+ class KeepAliveConnection extends eventsExports.EventEmitter {
748
+ // 是否为注册服务连接
749
+ isRegistry = false;
750
+ // 连接是否可用
751
+ #enabled = false;
752
+ data;
753
+ nativeConnection;
754
+ adapter;
755
+ constructor(adapter, nativeConnection, data) {
756
+ super();
757
+ this.adapter = adapter;
758
+ this.nativeConnection = nativeConnection;
759
+ this.data = Object.assign(data, {
760
+ adapter: adapter.name,
761
+ });
762
+ this.on('connect', () => {
763
+ emit('keepalive:connect', this);
764
+ });
765
+ this.on('disconnect', () => {
766
+ emit('keepalive:disconnect', this);
767
+ });
768
+ }
769
+ /**
770
+ * 设置连接是否可用,并自动触发enabled或disabled事件
771
+ * @param enabled 是否可用
772
+ */
773
+ set enabled(enabled) {
774
+ if (enabled !== this.#enabled) {
775
+ this.#enabled = enabled;
776
+ this.emit(enabled ? 'enabled' : 'disabled');
777
+ if (enabled) {
778
+ enabledKeepAliveConnections.add(this);
779
+ }
780
+ else {
781
+ enabledKeepAliveConnections.remove(this);
782
+ }
783
+ }
784
+ }
785
+ get enabled() {
786
+ return this.#enabled;
787
+ }
788
+ /**
789
+ * enable & mount connection
790
+ * @param params
791
+ * @returns
792
+ */
793
+ ready(params) {
794
+ // 连接已就绪,不允许重复就绪
795
+ if (this.enabled)
796
+ return;
797
+ const { id, name } = params;
798
+ keepAliveConnections.remove(this);
799
+ // 更新连接数据
800
+ this.data.id = id;
801
+ this.data.name = name;
802
+ keepAliveConnections.add(this);
803
+ this.enabled = true;
804
+ }
805
+ disconnect() {
806
+ this.enabled = false;
807
+ this.nativeConnection.disconnect();
808
+ }
809
+ }
810
+ class KeepAliveConnectionStore {
811
+ #map = new Map();
812
+ entries() {
813
+ return this.#map.entries();
814
+ }
815
+ getConnectionsOfService(name) {
816
+ return this.#map.get(name) || new Map();
817
+ }
818
+ has(name, id) {
819
+ const connections = this.#map.get(name);
820
+ if (!connections)
821
+ return false;
822
+ return connections.has(id);
823
+ }
824
+ get(name, id) {
825
+ const connections = this.#map.get(name);
826
+ if (!connections)
827
+ return null;
828
+ return connections.get(id) || null;
829
+ }
830
+ add(connection) {
831
+ const { name, id } = connection.data;
832
+ const connections = this.#map.get(name);
833
+ if (connections) {
834
+ connections.set(id, connection);
835
+ }
836
+ else {
837
+ this.#map.set(name, new Map([[id, connection]]));
838
+ }
839
+ }
840
+ remove(name, id) {
841
+ if (name instanceof KeepAliveConnection) {
842
+ id = name.data.id;
843
+ name = name.data.name;
844
+ }
845
+ const connections = this.#map.get(name);
846
+ if (connections && id !== undefined) {
847
+ connections.delete(id);
848
+ }
849
+ }
850
+ }
851
+ const keepAliveConnectionAdapters = new Map();
852
+ const keepAliveConnections = new KeepAliveConnectionStore();
853
+ const enabledKeepAliveConnections = new KeepAliveConnectionStore();
854
+ function addKeepAliveConnection(connection) {
855
+ if (keepAliveConnections.has(connection.data.name, connection.data.id)) {
856
+ connection.disconnect();
857
+ throw new KeepAliveConnectionError('Connection already exists', connection);
858
+ }
859
+ keepAliveConnections.add(connection);
860
+ }
861
+ function removeKeepAliveConnection(arg1, arg2) {
862
+ if (typeof arg1 === 'string') {
863
+ const connection = keepAliveConnections.get(arg1, arg2);
864
+ if (connection)
865
+ connection.disconnect();
866
+ keepAliveConnections.remove(arg1, arg2);
867
+ enabledKeepAliveConnections.remove(arg1, arg2);
868
+ }
869
+ else {
870
+ arg1.disconnect();
871
+ keepAliveConnections.remove(arg1);
872
+ enabledKeepAliveConnections.remove(arg1);
873
+ }
874
+ }
875
+ /**
876
+ * random connection select for default load balance policy
877
+ * @param name service name
878
+ * @returns selected connection
879
+ */
880
+ let loadBalancePolicy = (name) => {
881
+ const connections = enabledKeepAliveConnections.getConnectionsOfService(name);
882
+ if (!connections || !connections.size)
883
+ return null;
884
+ const arrayConnections = Array.from(connections.values());
885
+ const index = Math.floor(Math.random() * arrayConnections.length);
886
+ return arrayConnections[index];
887
+ };
888
+ function setLoadBalancePolicy(policy) {
889
+ loadBalancePolicy = policy;
890
+ }
891
+ async function rpc(arg1, action, params, context) {
892
+ if (!context || !context.traceId) {
893
+ context = getContext();
894
+ }
895
+ let connection = null;
896
+ if (arg1 instanceof KeepAliveConnection) {
897
+ connection = arg1;
898
+ }
899
+ else if ('string' === typeof arg1) {
900
+ connection = loadBalancePolicy(arg1);
901
+ }
902
+ else
903
+ throw new Error(`Unknown rpc arg1<${arg1}>`);
904
+ if (!connection)
905
+ throw new Error(`Connection<${arg1}> not found`);
906
+ return connection.adapter.rpc(connection, action, params, context);
907
+ }
908
+
909
+ class SampleKeepAliveConnectionAdapter {
910
+ /**
911
+ * 通知连接列表
912
+ */
913
+ ['registry:notify'](connection, datas) {
914
+ connection.nativeConnection.emit(this.OOXEvent.REGISTRY_NOTIFY, datas);
915
+ }
916
+ /**
917
+ * 订阅连接列表
918
+ */
919
+ ['registry:subscribe'](connection, query) {
920
+ connection.nativeConnection.emit(this.OOXEvent.REGISTRY_SUBSCRIBE, query);
921
+ }
922
+ bindConnectionEvents(connection) {
923
+ const socket = connection.nativeConnection;
924
+ socket.on(this.OOXEvent.READY, (params) => {
925
+ connection.ready(params);
926
+ });
927
+ socket.on(this.OOXEvent.ENABLED, () => {
928
+ connection.enabled = true;
929
+ });
930
+ socket.on(this.OOXEvent.DISABLED, () => {
931
+ connection.enabled = false;
932
+ });
933
+ socket.on(this.OOXEvent.DISCONNECT, () => {
934
+ socket.removeAllListeners();
935
+ removeKeepAliveConnection(connection);
936
+ connection.emit('disconnect');
937
+ });
938
+ socket.on(this.OOXEvent.CONNECT, () => {
939
+ connection.emit('connect');
940
+ });
941
+ socket.on(this.OOXEvent.ERROR, (error) => {
942
+ socket.removeAllListeners();
943
+ removeKeepAliveConnection(connection);
944
+ connection.emit('error', new KeepAliveConnectionError(error.message, connection));
945
+ });
946
+ }
947
+ async open(identify) {
948
+ const connection = this.newConnection(identify);
949
+ addKeepAliveConnection(connection);
950
+ this.bindConnectionEvents(connection);
951
+ this.bindCall(connection);
952
+ try {
953
+ await new Promise((resolve, reject) => {
954
+ connection.once('enabled', resolve);
955
+ connection.once('error', reject);
956
+ connection.once('disconnect', () => {
957
+ reject(new Error('disconnect'));
958
+ });
959
+ if (connection.nativeConnection.connect) {
960
+ connection.nativeConnection.connect();
961
+ }
962
+ });
963
+ }
964
+ catch (error) {
965
+ connection.removeAllListeners();
966
+ removeKeepAliveConnection(connection);
967
+ throw error;
968
+ }
969
+ return connection;
970
+ }
971
+ async close(connection) {
972
+ connection.nativeConnection.disconnect();
973
+ return Promise.resolve();
974
+ }
975
+ /**
976
+ * 发送事件
977
+ * @param socket
978
+ * @param event
979
+ * @param params
980
+ */
981
+ async emit(socket, event, params) {
982
+ if (!socket.connected)
983
+ throw new Error('Socket not connected');
984
+ return await new Promise((resolve, reject) => {
985
+ const onError = (reason) => {
986
+ const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
987
+ reject(new Error(message));
988
+ };
989
+ // RPC 执行时中断连接
990
+ socket.once(this.OOXEvent.DISCONNECT, onError);
991
+ socket.emit(event, ...params, (returns) => {
992
+ socket.off(this.OOXEvent.DISCONNECT, onError);
993
+ resolve(returns);
994
+ });
995
+ });
996
+ }
997
+ /**
998
+ * RPC
999
+ */
1000
+ async rpc(connection, action, params, context) {
1001
+ if (!context)
1002
+ context = getContext();
1003
+ const miniContext = {
1004
+ sourceIP: context.sourceIP,
1005
+ traceId: context.traceId,
1006
+ };
1007
+ const { success, error, body } = await this.emit(connection.nativeConnection, this.OOXEvent.CALL, [action, params, miniContext]);
1008
+ if (success)
1009
+ return body;
1010
+ else if (error)
1011
+ throw new Error(error.message);
1012
+ else
1013
+ throw new Error('[RPC] Unknown Error');
1014
+ }
1015
+ /**
1016
+ * 绑定 call 事件
1017
+ * @param connection
1018
+ */
1019
+ bindCall(connection) {
1020
+ const { id, name, ip } = connection.data;
1021
+ connection.nativeConnection.on(this.OOXEvent.CALL, async (action, params, context, callback) => {
1022
+ const validContext = new Context({
1023
+ ...context,
1024
+ ip: ip,
1025
+ caller: name,
1026
+ callerId: id,
1027
+ connection
1028
+ });
1029
+ this.call(action, params, validContext, callback);
1030
+ });
1031
+ }
1032
+ async call(action, params, context, callback) {
1033
+ const returns = await call(action, params, context);
1034
+ 'function' === typeof callback && callback(returns);
1035
+ return returns;
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * 为了不重复创建Proxy,这个对象用于保存各个RPC服务的各个属性Proxy
1041
+ */
1042
+ const rpcServiceAttrMap = Object.create(null);
1043
+ function proxy(name, action = '') {
1044
+ return new Proxy(function () { }, {
1045
+ get(target, key) {
1046
+ if (typeof key !== 'string')
1047
+ return undefined;
1048
+ const attrKey = action ? action + '.' + key : key;
1049
+ const attrKeyPath = name + '.' + attrKey;
1050
+ if (attrKeyPath in rpcServiceAttrMap) {
1051
+ // 不重复创建Proxy
1052
+ return rpcServiceAttrMap[attrKeyPath];
1053
+ }
1054
+ const attrProxy = proxy(name, attrKey);
1055
+ rpcServiceAttrMap[attrKeyPath] = attrProxy;
1056
+ return attrProxy;
1057
+ },
1058
+ has(target, key) {
1059
+ if (typeof key !== 'string')
1060
+ return false;
1061
+ return true;
1062
+ },
1063
+ apply(target, thisArg, args) {
1064
+ return rpc(name, action, args);
1065
+ }
1066
+ });
1067
+ }
1068
+
1069
+ exports.AppContext = AppContext;
1070
+ exports.Config = Config;
1071
+ exports.Context = Context;
1072
+ exports.KeepAliveConnection = KeepAliveConnection;
1073
+ exports.KeepAliveConnectionError = KeepAliveConnectionError;
1074
+ exports.KeepAliveConnectionStore = KeepAliveConnectionStore;
1075
+ exports.SampleKeepAliveConnectionAdapter = SampleKeepAliveConnectionAdapter;
1076
+ exports.addKeepAliveConnection = addKeepAliveConnection;
1077
+ exports.call = call;
1078
+ exports.config = config;
1079
+ exports.emit = emit;
1080
+ exports.enabledKeepAliveConnections = enabledKeepAliveConnections;
1081
+ exports.eventHub = eventHub;
1082
+ exports.execute = execute;
1083
+ exports.genContext = genContext;
1084
+ exports.genTraceId = genTraceId;
1085
+ exports.getContext = getContext;
1086
+ exports.getMethods = getMethods;
1087
+ exports.keepAliveConnectionAdapters = keepAliveConnectionAdapters;
1088
+ exports.keepAliveConnections = keepAliveConnections;
1089
+ exports.kvMethods = kvMethods;
1090
+ exports.off = off;
1091
+ exports.on = on;
1092
+ exports.once = once;
1093
+ exports.proxy = proxy;
1094
+ exports.removeKeepAliveConnection = removeKeepAliveConnection;
1095
+ exports.rpc = rpc;
1096
+ exports.setGenTraceIdFunction = setGenTraceIdFunction;
1097
+ exports.setLoadBalancePolicy = setLoadBalancePolicy;
1098
+ exports.setMethods = setMethods;
1099
+ exports.sourceKVMethods = sourceKVMethods;
1100
+
1101
+ return exports;
1142
1102
 
1143
1103
  })({});
1144
1104
  //# sourceMappingURL=browser.js.map