@wutiange/log-listener-plugin 2.0.2-alpha.5 → 2.0.2

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/dist/index.cjs.js CHANGED
@@ -1,7 +1,1462 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const tslib_1 = require("tslib");
5
- const logPlugin_1 = tslib_1.__importDefault(require("./src/logPlugin"));
6
- exports.default = logPlugin_1.default;
3
+ var XHRInterceptor = require('react-native/Libraries/Network/XHRInterceptor');
4
+ var BlobFileReader = require('react-native/Libraries/Blob/FileReader');
5
+
6
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
7
+
8
+ function getDefaultExportFromCjs (x) {
9
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
10
+ }
11
+
12
+ var requiresPort;
13
+ var hasRequiredRequiresPort;
14
+
15
+ function requireRequiresPort () {
16
+ if (hasRequiredRequiresPort) return requiresPort;
17
+ hasRequiredRequiresPort = 1;
18
+
19
+ /**
20
+ * Check if we're required to add a port number.
21
+ *
22
+ * @see https://url.spec.whatwg.org/#default-port
23
+ * @param {Number|String} port Port number we need to check
24
+ * @param {String} protocol Protocol we need to check against.
25
+ * @returns {Boolean} Is it a default port for the given protocol
26
+ * @api private
27
+ */
28
+ requiresPort = function required(port, protocol) {
29
+ protocol = protocol.split(':')[0];
30
+ port = +port;
31
+
32
+ if (!port) return false;
33
+
34
+ switch (protocol) {
35
+ case 'http':
36
+ case 'ws':
37
+ return port !== 80;
38
+
39
+ case 'https':
40
+ case 'wss':
41
+ return port !== 443;
42
+
43
+ case 'ftp':
44
+ return port !== 21;
45
+
46
+ case 'gopher':
47
+ return port !== 70;
48
+
49
+ case 'file':
50
+ return false;
51
+ }
52
+
53
+ return port !== 0;
54
+ };
55
+ return requiresPort;
56
+ }
57
+
58
+ var querystringify = {};
59
+
60
+ var hasRequiredQuerystringify;
61
+
62
+ function requireQuerystringify () {
63
+ if (hasRequiredQuerystringify) return querystringify;
64
+ hasRequiredQuerystringify = 1;
65
+
66
+ var has = Object.prototype.hasOwnProperty
67
+ , undef;
68
+
69
+ /**
70
+ * Decode a URI encoded string.
71
+ *
72
+ * @param {String} input The URI encoded string.
73
+ * @returns {String|Null} The decoded string.
74
+ * @api private
75
+ */
76
+ function decode(input) {
77
+ try {
78
+ return decodeURIComponent(input.replace(/\+/g, ' '));
79
+ } catch (e) {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Attempts to encode a given input.
86
+ *
87
+ * @param {String} input The string that needs to be encoded.
88
+ * @returns {String|Null} The encoded string.
89
+ * @api private
90
+ */
91
+ function encode(input) {
92
+ try {
93
+ return encodeURIComponent(input);
94
+ } catch (e) {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Simple query string parser.
101
+ *
102
+ * @param {String} query The query string that needs to be parsed.
103
+ * @returns {Object}
104
+ * @api public
105
+ */
106
+ function querystring(query) {
107
+ var parser = /([^=?#&]+)=?([^&]*)/g
108
+ , result = {}
109
+ , part;
110
+
111
+ while (part = parser.exec(query)) {
112
+ var key = decode(part[1])
113
+ , value = decode(part[2]);
114
+
115
+ //
116
+ // Prevent overriding of existing properties. This ensures that build-in
117
+ // methods like `toString` or __proto__ are not overriden by malicious
118
+ // querystrings.
119
+ //
120
+ // In the case if failed decoding, we want to omit the key/value pairs
121
+ // from the result.
122
+ //
123
+ if (key === null || value === null || key in result) continue;
124
+ result[key] = value;
125
+ }
126
+
127
+ return result;
128
+ }
129
+
130
+ /**
131
+ * Transform a query string to an object.
132
+ *
133
+ * @param {Object} obj Object that should be transformed.
134
+ * @param {String} prefix Optional prefix.
135
+ * @returns {String}
136
+ * @api public
137
+ */
138
+ function querystringify$1(obj, prefix) {
139
+ prefix = prefix || '';
140
+
141
+ var pairs = []
142
+ , value
143
+ , key;
144
+
145
+ //
146
+ // Optionally prefix with a '?' if needed
147
+ //
148
+ if ('string' !== typeof prefix) prefix = '?';
149
+
150
+ for (key in obj) {
151
+ if (has.call(obj, key)) {
152
+ value = obj[key];
153
+
154
+ //
155
+ // Edge cases where we actually want to encode the value to an empty
156
+ // string instead of the stringified value.
157
+ //
158
+ if (!value && (value === null || value === undef || isNaN(value))) {
159
+ value = '';
160
+ }
161
+
162
+ key = encode(key);
163
+ value = encode(value);
164
+
165
+ //
166
+ // If we failed to encode the strings, we should bail out as we don't
167
+ // want to add invalid strings to the query.
168
+ //
169
+ if (key === null || value === null) continue;
170
+ pairs.push(key +'='+ value);
171
+ }
172
+ }
173
+
174
+ return pairs.length ? prefix + pairs.join('&') : '';
175
+ }
176
+
177
+ //
178
+ // Expose the module.
179
+ //
180
+ querystringify.stringify = querystringify$1;
181
+ querystringify.parse = querystring;
182
+ return querystringify;
183
+ }
184
+
185
+ var urlParse;
186
+ var hasRequiredUrlParse;
187
+
188
+ function requireUrlParse () {
189
+ if (hasRequiredUrlParse) return urlParse;
190
+ hasRequiredUrlParse = 1;
191
+
192
+ var required = requireRequiresPort()
193
+ , qs = requireQuerystringify()
194
+ , controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
195
+ , CRHTLF = /[\n\r\t]/g
196
+ , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
197
+ , port = /:\d+$/
198
+ , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
199
+ , windowsDriveLetter = /^[a-zA-Z]:/;
200
+
201
+ /**
202
+ * Remove control characters and whitespace from the beginning of a string.
203
+ *
204
+ * @param {Object|String} str String to trim.
205
+ * @returns {String} A new string representing `str` stripped of control
206
+ * characters and whitespace from its beginning.
207
+ * @public
208
+ */
209
+ function trimLeft(str) {
210
+ return (str ? str : '').toString().replace(controlOrWhitespace, '');
211
+ }
212
+
213
+ /**
214
+ * These are the parse rules for the URL parser, it informs the parser
215
+ * about:
216
+ *
217
+ * 0. The char it Needs to parse, if it's a string it should be done using
218
+ * indexOf, RegExp using exec and NaN means set as current value.
219
+ * 1. The property we should set when parsing this value.
220
+ * 2. Indication if it's backwards or forward parsing, when set as number it's
221
+ * the value of extra chars that should be split off.
222
+ * 3. Inherit from location if non existing in the parser.
223
+ * 4. `toLowerCase` the resulting value.
224
+ */
225
+ var rules = [
226
+ ['#', 'hash'], // Extract from the back.
227
+ ['?', 'query'], // Extract from the back.
228
+ function sanitize(address, url) { // Sanitize what is left of the address
229
+ return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
230
+ },
231
+ ['/', 'pathname'], // Extract from the back.
232
+ ['@', 'auth', 1], // Extract from the front.
233
+ [NaN, 'host', undefined, 1, 1], // Set left over value.
234
+ [/:(\d*)$/, 'port', undefined, 1], // RegExp the back.
235
+ [NaN, 'hostname', undefined, 1, 1] // Set left over.
236
+ ];
237
+
238
+ /**
239
+ * These properties should not be copied or inherited from. This is only needed
240
+ * for all non blob URL's as a blob URL does not include a hash, only the
241
+ * origin.
242
+ *
243
+ * @type {Object}
244
+ * @private
245
+ */
246
+ var ignore = { hash: 1, query: 1 };
247
+
248
+ /**
249
+ * The location object differs when your code is loaded through a normal page,
250
+ * Worker or through a worker using a blob. And with the blobble begins the
251
+ * trouble as the location object will contain the URL of the blob, not the
252
+ * location of the page where our code is loaded in. The actual origin is
253
+ * encoded in the `pathname` so we can thankfully generate a good "default"
254
+ * location from it so we can generate proper relative URL's again.
255
+ *
256
+ * @param {Object|String} loc Optional default location object.
257
+ * @returns {Object} lolcation object.
258
+ * @public
259
+ */
260
+ function lolcation(loc) {
261
+ var globalVar;
262
+
263
+ if (typeof window !== 'undefined') globalVar = window;
264
+ else if (typeof commonjsGlobal !== 'undefined') globalVar = commonjsGlobal;
265
+ else if (typeof self !== 'undefined') globalVar = self;
266
+ else globalVar = {};
267
+
268
+ var location = globalVar.location || {};
269
+ loc = loc || location;
270
+
271
+ var finaldestination = {}
272
+ , type = typeof loc
273
+ , key;
274
+
275
+ if ('blob:' === loc.protocol) {
276
+ finaldestination = new Url(unescape(loc.pathname), {});
277
+ } else if ('string' === type) {
278
+ finaldestination = new Url(loc, {});
279
+ for (key in ignore) delete finaldestination[key];
280
+ } else if ('object' === type) {
281
+ for (key in loc) {
282
+ if (key in ignore) continue;
283
+ finaldestination[key] = loc[key];
284
+ }
285
+
286
+ if (finaldestination.slashes === undefined) {
287
+ finaldestination.slashes = slashes.test(loc.href);
288
+ }
289
+ }
290
+
291
+ return finaldestination;
292
+ }
293
+
294
+ /**
295
+ * Check whether a protocol scheme is special.
296
+ *
297
+ * @param {String} The protocol scheme of the URL
298
+ * @return {Boolean} `true` if the protocol scheme is special, else `false`
299
+ * @private
300
+ */
301
+ function isSpecial(scheme) {
302
+ return (
303
+ scheme === 'file:' ||
304
+ scheme === 'ftp:' ||
305
+ scheme === 'http:' ||
306
+ scheme === 'https:' ||
307
+ scheme === 'ws:' ||
308
+ scheme === 'wss:'
309
+ );
310
+ }
311
+
312
+ /**
313
+ * @typedef ProtocolExtract
314
+ * @type Object
315
+ * @property {String} protocol Protocol matched in the URL, in lowercase.
316
+ * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
317
+ * @property {String} rest Rest of the URL that is not part of the protocol.
318
+ */
319
+
320
+ /**
321
+ * Extract protocol information from a URL with/without double slash ("//").
322
+ *
323
+ * @param {String} address URL we want to extract from.
324
+ * @param {Object} location
325
+ * @return {ProtocolExtract} Extracted information.
326
+ * @private
327
+ */
328
+ function extractProtocol(address, location) {
329
+ address = trimLeft(address);
330
+ address = address.replace(CRHTLF, '');
331
+ location = location || {};
332
+
333
+ var match = protocolre.exec(address);
334
+ var protocol = match[1] ? match[1].toLowerCase() : '';
335
+ var forwardSlashes = !!match[2];
336
+ var otherSlashes = !!match[3];
337
+ var slashesCount = 0;
338
+ var rest;
339
+
340
+ if (forwardSlashes) {
341
+ if (otherSlashes) {
342
+ rest = match[2] + match[3] + match[4];
343
+ slashesCount = match[2].length + match[3].length;
344
+ } else {
345
+ rest = match[2] + match[4];
346
+ slashesCount = match[2].length;
347
+ }
348
+ } else {
349
+ if (otherSlashes) {
350
+ rest = match[3] + match[4];
351
+ slashesCount = match[3].length;
352
+ } else {
353
+ rest = match[4];
354
+ }
355
+ }
356
+
357
+ if (protocol === 'file:') {
358
+ if (slashesCount >= 2) {
359
+ rest = rest.slice(2);
360
+ }
361
+ } else if (isSpecial(protocol)) {
362
+ rest = match[4];
363
+ } else if (protocol) {
364
+ if (forwardSlashes) {
365
+ rest = rest.slice(2);
366
+ }
367
+ } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
368
+ rest = match[4];
369
+ }
370
+
371
+ return {
372
+ protocol: protocol,
373
+ slashes: forwardSlashes || isSpecial(protocol),
374
+ slashesCount: slashesCount,
375
+ rest: rest
376
+ };
377
+ }
378
+
379
+ /**
380
+ * Resolve a relative URL pathname against a base URL pathname.
381
+ *
382
+ * @param {String} relative Pathname of the relative URL.
383
+ * @param {String} base Pathname of the base URL.
384
+ * @return {String} Resolved pathname.
385
+ * @private
386
+ */
387
+ function resolve(relative, base) {
388
+ if (relative === '') return base;
389
+
390
+ var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
391
+ , i = path.length
392
+ , last = path[i - 1]
393
+ , unshift = false
394
+ , up = 0;
395
+
396
+ while (i--) {
397
+ if (path[i] === '.') {
398
+ path.splice(i, 1);
399
+ } else if (path[i] === '..') {
400
+ path.splice(i, 1);
401
+ up++;
402
+ } else if (up) {
403
+ if (i === 0) unshift = true;
404
+ path.splice(i, 1);
405
+ up--;
406
+ }
407
+ }
408
+
409
+ if (unshift) path.unshift('');
410
+ if (last === '.' || last === '..') path.push('');
411
+
412
+ return path.join('/');
413
+ }
414
+
415
+ /**
416
+ * The actual URL instance. Instead of returning an object we've opted-in to
417
+ * create an actual constructor as it's much more memory efficient and
418
+ * faster and it pleases my OCD.
419
+ *
420
+ * It is worth noting that we should not use `URL` as class name to prevent
421
+ * clashes with the global URL instance that got introduced in browsers.
422
+ *
423
+ * @constructor
424
+ * @param {String} address URL we want to parse.
425
+ * @param {Object|String} [location] Location defaults for relative paths.
426
+ * @param {Boolean|Function} [parser] Parser for the query string.
427
+ * @private
428
+ */
429
+ function Url(address, location, parser) {
430
+ address = trimLeft(address);
431
+ address = address.replace(CRHTLF, '');
432
+
433
+ if (!(this instanceof Url)) {
434
+ return new Url(address, location, parser);
435
+ }
436
+
437
+ var relative, extracted, parse, instruction, index, key
438
+ , instructions = rules.slice()
439
+ , type = typeof location
440
+ , url = this
441
+ , i = 0;
442
+
443
+ //
444
+ // The following if statements allows this module two have compatibility with
445
+ // 2 different API:
446
+ //
447
+ // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
448
+ // where the boolean indicates that the query string should also be parsed.
449
+ //
450
+ // 2. The `URL` interface of the browser which accepts a URL, object as
451
+ // arguments. The supplied object will be used as default values / fall-back
452
+ // for relative paths.
453
+ //
454
+ if ('object' !== type && 'string' !== type) {
455
+ parser = location;
456
+ location = null;
457
+ }
458
+
459
+ if (parser && 'function' !== typeof parser) parser = qs.parse;
460
+
461
+ location = lolcation(location);
462
+
463
+ //
464
+ // Extract protocol information before running the instructions.
465
+ //
466
+ extracted = extractProtocol(address || '', location);
467
+ relative = !extracted.protocol && !extracted.slashes;
468
+ url.slashes = extracted.slashes || relative && location.slashes;
469
+ url.protocol = extracted.protocol || location.protocol || '';
470
+ address = extracted.rest;
471
+
472
+ //
473
+ // When the authority component is absent the URL starts with a path
474
+ // component.
475
+ //
476
+ if (
477
+ extracted.protocol === 'file:' && (
478
+ extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
479
+ (!extracted.slashes &&
480
+ (extracted.protocol ||
481
+ extracted.slashesCount < 2 ||
482
+ !isSpecial(url.protocol)))
483
+ ) {
484
+ instructions[3] = [/(.*)/, 'pathname'];
485
+ }
486
+
487
+ for (; i < instructions.length; i++) {
488
+ instruction = instructions[i];
489
+
490
+ if (typeof instruction === 'function') {
491
+ address = instruction(address, url);
492
+ continue;
493
+ }
494
+
495
+ parse = instruction[0];
496
+ key = instruction[1];
497
+
498
+ if (parse !== parse) {
499
+ url[key] = address;
500
+ } else if ('string' === typeof parse) {
501
+ index = parse === '@'
502
+ ? address.lastIndexOf(parse)
503
+ : address.indexOf(parse);
504
+
505
+ if (~index) {
506
+ if ('number' === typeof instruction[2]) {
507
+ url[key] = address.slice(0, index);
508
+ address = address.slice(index + instruction[2]);
509
+ } else {
510
+ url[key] = address.slice(index);
511
+ address = address.slice(0, index);
512
+ }
513
+ }
514
+ } else if ((index = parse.exec(address))) {
515
+ url[key] = index[1];
516
+ address = address.slice(0, index.index);
517
+ }
518
+
519
+ url[key] = url[key] || (
520
+ relative && instruction[3] ? location[key] || '' : ''
521
+ );
522
+
523
+ //
524
+ // Hostname, host and protocol should be lowercased so they can be used to
525
+ // create a proper `origin`.
526
+ //
527
+ if (instruction[4]) url[key] = url[key].toLowerCase();
528
+ }
529
+
530
+ //
531
+ // Also parse the supplied query string in to an object. If we're supplied
532
+ // with a custom parser as function use that instead of the default build-in
533
+ // parser.
534
+ //
535
+ if (parser) url.query = parser(url.query);
536
+
537
+ //
538
+ // If the URL is relative, resolve the pathname against the base URL.
539
+ //
540
+ if (
541
+ relative
542
+ && location.slashes
543
+ && url.pathname.charAt(0) !== '/'
544
+ && (url.pathname !== '' || location.pathname !== '')
545
+ ) {
546
+ url.pathname = resolve(url.pathname, location.pathname);
547
+ }
548
+
549
+ //
550
+ // Default to a / for pathname if none exists. This normalizes the URL
551
+ // to always have a /
552
+ //
553
+ if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
554
+ url.pathname = '/' + url.pathname;
555
+ }
556
+
557
+ //
558
+ // We should not add port numbers if they are already the default port number
559
+ // for a given protocol. As the host also contains the port number we're going
560
+ // override it with the hostname which contains no port number.
561
+ //
562
+ if (!required(url.port, url.protocol)) {
563
+ url.host = url.hostname;
564
+ url.port = '';
565
+ }
566
+
567
+ //
568
+ // Parse down the `auth` for the username and password.
569
+ //
570
+ url.username = url.password = '';
571
+
572
+ if (url.auth) {
573
+ index = url.auth.indexOf(':');
574
+
575
+ if (~index) {
576
+ url.username = url.auth.slice(0, index);
577
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
578
+
579
+ url.password = url.auth.slice(index + 1);
580
+ url.password = encodeURIComponent(decodeURIComponent(url.password));
581
+ } else {
582
+ url.username = encodeURIComponent(decodeURIComponent(url.auth));
583
+ }
584
+
585
+ url.auth = url.password ? url.username +':'+ url.password : url.username;
586
+ }
587
+
588
+ url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
589
+ ? url.protocol +'//'+ url.host
590
+ : 'null';
591
+
592
+ //
593
+ // The href is just the compiled result.
594
+ //
595
+ url.href = url.toString();
596
+ }
597
+
598
+ /**
599
+ * This is convenience method for changing properties in the URL instance to
600
+ * insure that they all propagate correctly.
601
+ *
602
+ * @param {String} part Property we need to adjust.
603
+ * @param {Mixed} value The newly assigned value.
604
+ * @param {Boolean|Function} fn When setting the query, it will be the function
605
+ * used to parse the query.
606
+ * When setting the protocol, double slash will be
607
+ * removed from the final url if it is true.
608
+ * @returns {URL} URL instance for chaining.
609
+ * @public
610
+ */
611
+ function set(part, value, fn) {
612
+ var url = this;
613
+
614
+ switch (part) {
615
+ case 'query':
616
+ if ('string' === typeof value && value.length) {
617
+ value = (fn || qs.parse)(value);
618
+ }
619
+
620
+ url[part] = value;
621
+ break;
622
+
623
+ case 'port':
624
+ url[part] = value;
625
+
626
+ if (!required(value, url.protocol)) {
627
+ url.host = url.hostname;
628
+ url[part] = '';
629
+ } else if (value) {
630
+ url.host = url.hostname +':'+ value;
631
+ }
632
+
633
+ break;
634
+
635
+ case 'hostname':
636
+ url[part] = value;
637
+
638
+ if (url.port) value += ':'+ url.port;
639
+ url.host = value;
640
+ break;
641
+
642
+ case 'host':
643
+ url[part] = value;
644
+
645
+ if (port.test(value)) {
646
+ value = value.split(':');
647
+ url.port = value.pop();
648
+ url.hostname = value.join(':');
649
+ } else {
650
+ url.hostname = value;
651
+ url.port = '';
652
+ }
653
+
654
+ break;
655
+
656
+ case 'protocol':
657
+ url.protocol = value.toLowerCase();
658
+ url.slashes = !fn;
659
+ break;
660
+
661
+ case 'pathname':
662
+ case 'hash':
663
+ if (value) {
664
+ var char = part === 'pathname' ? '/' : '#';
665
+ url[part] = value.charAt(0) !== char ? char + value : value;
666
+ } else {
667
+ url[part] = value;
668
+ }
669
+ break;
670
+
671
+ case 'username':
672
+ case 'password':
673
+ url[part] = encodeURIComponent(value);
674
+ break;
675
+
676
+ case 'auth':
677
+ var index = value.indexOf(':');
678
+
679
+ if (~index) {
680
+ url.username = value.slice(0, index);
681
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
682
+
683
+ url.password = value.slice(index + 1);
684
+ url.password = encodeURIComponent(decodeURIComponent(url.password));
685
+ } else {
686
+ url.username = encodeURIComponent(decodeURIComponent(value));
687
+ }
688
+ }
689
+
690
+ for (var i = 0; i < rules.length; i++) {
691
+ var ins = rules[i];
692
+
693
+ if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
694
+ }
695
+
696
+ url.auth = url.password ? url.username +':'+ url.password : url.username;
697
+
698
+ url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
699
+ ? url.protocol +'//'+ url.host
700
+ : 'null';
701
+
702
+ url.href = url.toString();
703
+
704
+ return url;
705
+ }
706
+
707
+ /**
708
+ * Transform the properties back in to a valid and full URL string.
709
+ *
710
+ * @param {Function} stringify Optional query stringify function.
711
+ * @returns {String} Compiled version of the URL.
712
+ * @public
713
+ */
714
+ function toString(stringify) {
715
+ if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
716
+
717
+ var query
718
+ , url = this
719
+ , host = url.host
720
+ , protocol = url.protocol;
721
+
722
+ if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
723
+
724
+ var result =
725
+ protocol +
726
+ ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');
727
+
728
+ if (url.username) {
729
+ result += url.username;
730
+ if (url.password) result += ':'+ url.password;
731
+ result += '@';
732
+ } else if (url.password) {
733
+ result += ':'+ url.password;
734
+ result += '@';
735
+ } else if (
736
+ url.protocol !== 'file:' &&
737
+ isSpecial(url.protocol) &&
738
+ !host &&
739
+ url.pathname !== '/'
740
+ ) {
741
+ //
742
+ // Add back the empty userinfo, otherwise the original invalid URL
743
+ // might be transformed into a valid one with `url.pathname` as host.
744
+ //
745
+ result += '@';
746
+ }
747
+
748
+ //
749
+ // Trailing colon is removed from `url.host` when it is parsed. If it still
750
+ // ends with a colon, then add back the trailing colon that was removed. This
751
+ // prevents an invalid URL from being transformed into a valid one.
752
+ //
753
+ if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
754
+ host += ':';
755
+ }
756
+
757
+ result += host + url.pathname;
758
+
759
+ query = 'object' === typeof url.query ? stringify(url.query) : url.query;
760
+ if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
761
+
762
+ if (url.hash) result += url.hash;
763
+
764
+ return result;
765
+ }
766
+
767
+ Url.prototype = { set: set, toString: toString };
768
+
769
+ //
770
+ // Expose the URL parser and some additional properties that might be useful for
771
+ // others or testing.
772
+ //
773
+ Url.extractProtocol = extractProtocol;
774
+ Url.location = lolcation;
775
+ Url.trimLeft = trimLeft;
776
+ Url.qs = qs;
777
+
778
+ urlParse = Url;
779
+ return urlParse;
780
+ }
781
+
782
+ var urlParseExports = requireUrlParse();
783
+ var URL = /*@__PURE__*/getDefaultExportFromCjs(urlParseExports);
784
+
785
+ function sleep(ms, isReject = false) {
786
+ return new Promise((resolve, reject) => {
787
+ setTimeout(isReject
788
+ ? () => reject({
789
+ code: 11001,
790
+ key: '@wutiange/log-listener-plugin%%timeout',
791
+ message: 'Timeout',
792
+ })
793
+ : resolve, ms);
794
+ });
795
+ }
796
+ function hasPort(url) {
797
+ if (!url || typeof url !== 'string') {
798
+ return false;
799
+ }
800
+ const parsedUrl = new URL(url);
801
+ return parsedUrl.port !== '';
802
+ }
803
+ function formDataToString(formData) {
804
+ const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substr(2);
805
+ let result = '';
806
+ const parts = formData.getParts();
807
+ for (const part of parts) {
808
+ result += `--${boundary}\r\n`;
809
+ result += `Content-Disposition: ${part.headers['content-disposition']}\r\n`;
810
+ if (part.headers['content-type']) {
811
+ result += `Content-Type: ${part.headers['content-type']}\r\n`;
812
+ }
813
+ const value = 'string' in part ? part.string : part.uri;
814
+ result += `Content-Length: ${value.length}\r\n\r\n`;
815
+ result += `${value}\r\n`;
816
+ }
817
+ result += `--${boundary}--\r\n`;
818
+ return result;
819
+ }
820
+ function typeReplacer(key, val) {
821
+ if (val instanceof Error) {
822
+ return val.toString();
823
+ }
824
+ else if (val instanceof Function) {
825
+ return Function.prototype.toString.call(val);
826
+ }
827
+ else if (typeof val === 'symbol') {
828
+ return val.toString();
829
+ }
830
+ else if (typeof val === 'bigint') {
831
+ return val.toString();
832
+ }
833
+ else if (val instanceof RegExp) {
834
+ return val.toString();
835
+ }
836
+ else if (val instanceof Set) {
837
+ return Array.from(val);
838
+ }
839
+ else if (val instanceof Map) {
840
+ return Object.fromEntries(val);
841
+ }
842
+ return val;
843
+ }
844
+
845
+ const [log, warn, error] = [console.log, console.warn, console.error];
846
+ const logger = {
847
+ log: (...data) => {
848
+ log(...data);
849
+ },
850
+ warn: (...data) => {
851
+ warn(...data);
852
+ },
853
+ error: (...data) => {
854
+ error(...data);
855
+ },
856
+ };
857
+
858
+ const URLS_KEY = 'log-listener-plugin-urls$$SetKey';
859
+ const DEFAULT_TIMEOUT = 3000;
860
+ const LOG_KEY = '[@wutiange/log-listener-plugin 日志]';
861
+ var Level;
862
+ (function (Level) {
863
+ Level["LOG"] = "log";
864
+ Level["WARN"] = "warn";
865
+ Level["ERROR"] = "error";
866
+ })(Level || (Level = {}));
867
+ var Tag;
868
+ (function (Tag) {
869
+ Tag["LOG_PLUGIN_INTERNAL_ERROR"] = "log-plugin-internal-error";
870
+ Tag["DEFAULT"] = "default";
871
+ })(Tag || (Tag = {}));
872
+ const getDefaultDeviceINfo = () => {
873
+ try {
874
+ const { Platform } = require('react-native');
875
+ return {
876
+ SystemName: Platform.OS,
877
+ Version: Platform.Version,
878
+ ...Platform.constants
879
+ };
880
+ }
881
+ catch (error) {
882
+ logger.warn(LOG_KEY, '这个插件只能在 react-native 中使用');
883
+ return {};
884
+ }
885
+ };
886
+ const getBaseData = () => {
887
+ var _a;
888
+ try {
889
+ const DeviceInfo = (_a = require("react-native-device-info")) === null || _a === void 0 ? void 0 : _a.default;
890
+ return {
891
+ Brand: DeviceInfo.getBrand(),
892
+ Model: DeviceInfo.getModel(),
893
+ AppVersion: DeviceInfo.getVersion(),
894
+ Carrier: DeviceInfo.getCarrierSync(),
895
+ Manufacturer: DeviceInfo.getManufacturerSync(),
896
+ SystemName: DeviceInfo.getSystemName(),
897
+ ...getDefaultDeviceINfo()
898
+ };
899
+ }
900
+ catch (error) {
901
+ return getDefaultDeviceINfo();
902
+ }
903
+ };
904
+ const getDefaultStorage = () => {
905
+ var _a;
906
+ try {
907
+ const AsyncStorage = (_a = require("@react-native-async-storage/async-storage")) === null || _a === void 0 ? void 0 : _a.default;
908
+ return AsyncStorage;
909
+ }
910
+ catch (error) {
911
+ return null;
912
+ }
913
+ };
914
+
915
+ const DEFAULT_PORT = 27751;
916
+ class Server {
917
+ constructor(url, timeout = 30000) {
918
+ this.baseUrlArr = new Set();
919
+ this.urlsObj = new Map();
920
+ this.baseData = {};
921
+ this.urlsListener = () => { };
922
+ this.innerBaseData = {};
923
+ this.addUrlsListener = (onNewUrlCallback) => {
924
+ this.urlsListener = onNewUrlCallback;
925
+ };
926
+ this.requestJoin = async (url, token) => {
927
+ var _a;
928
+ const response = await fetch(url, {
929
+ method: 'POST',
930
+ headers: {
931
+ 'Content-Type': 'application/json;charset=utf-8',
932
+ },
933
+ body: JSON.stringify({
934
+ token,
935
+ model: (_a = this.innerBaseData.Model) !== null && _a !== void 0 ? _a : `${this.innerBaseData.systemName}v${this.innerBaseData.osVersion}`,
936
+ }),
937
+ });
938
+ if (response.status !== 200) {
939
+ return false;
940
+ }
941
+ const json = await response.json();
942
+ if (json.code !== 0) {
943
+ return false;
944
+ }
945
+ return true;
946
+ };
947
+ this.send = async (path, data) => {
948
+ const request = async (url, _data) => {
949
+ await Promise.race([
950
+ fetch(`${url}/${path}`, {
951
+ method: 'POST',
952
+ headers: {
953
+ 'Content-Type': 'application/json;charset=utf-8',
954
+ },
955
+ body: JSON.stringify({ ...this.innerBaseData, ...this.baseData, ..._data }, typeReplacer),
956
+ }),
957
+ sleep(this.timeout, true),
958
+ ]);
959
+ };
960
+ if (this.baseUrlArr.size === 0) {
961
+ return;
962
+ }
963
+ this.baseUrlArr.forEach(async (e) => {
964
+ var _a, _b;
965
+ try {
966
+ await request(e, data);
967
+ }
968
+ catch (error) {
969
+ if (((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes('Network request failed')) ||
970
+ ((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.includes('Timeout'))) {
971
+ return;
972
+ }
973
+ logger.warn(LOG_KEY, '上报日志失败', error);
974
+ }
975
+ });
976
+ };
977
+ this.log = async (data) => {
978
+ return this.send('log', data);
979
+ };
980
+ this.network = async (data) => {
981
+ return this.send('network', data);
982
+ };
983
+ if (typeof url === 'string') {
984
+ this.updateUrl(url);
985
+ }
986
+ else {
987
+ this.setBaseUrlArr(url !== null && url !== void 0 ? url : new Set());
988
+ }
989
+ this.timeout = timeout;
990
+ this.innerBaseData = getBaseData();
991
+ this.handleZeroConf();
992
+ }
993
+ async handleZeroConf() {
994
+ var _a;
995
+ try {
996
+ const ZeroConf = (_a = require('react-native-zeroconf')) === null || _a === void 0 ? void 0 : _a.default;
997
+ if (!ZeroConf) {
998
+ return;
999
+ }
1000
+ const zeroConf = new ZeroConf();
1001
+ zeroConf.on('resolved', async (service) => {
1002
+ var _a;
1003
+ try {
1004
+ const { path, token } = (_a = service.txt) !== null && _a !== void 0 ? _a : {};
1005
+ const url = `http://${service.host}:${service.port}`;
1006
+ if (!(path && token)) {
1007
+ return;
1008
+ }
1009
+ if (!(await this.requestJoin(`${url}${path}`, token))) {
1010
+ return;
1011
+ }
1012
+ this.baseUrlArr.add(url);
1013
+ this.urlsObj.set(service.name, url);
1014
+ if (this.urlsListener) {
1015
+ this.urlsListener(this.baseUrlArr);
1016
+ }
1017
+ }
1018
+ catch (error) {
1019
+ logger.warn(LOG_KEY, '加入日志系统失败---', error);
1020
+ }
1021
+ });
1022
+ zeroConf.on('remove', (name) => {
1023
+ const currentUrl = this.urlsObj.get(name);
1024
+ if (currentUrl === undefined) {
1025
+ return;
1026
+ }
1027
+ const isExistSomeUrl = Array.from(this.urlsObj.values()).some((url) => url === currentUrl);
1028
+ this.urlsObj.delete(name);
1029
+ if (isExistSomeUrl) {
1030
+ return;
1031
+ }
1032
+ this.baseUrlArr.delete(currentUrl);
1033
+ if (this.urlsListener) {
1034
+ this.urlsListener(this.baseUrlArr);
1035
+ }
1036
+ });
1037
+ zeroConf.on('error', (err) => {
1038
+ logger.warn(LOG_KEY, 'zeroconf出现错误', err);
1039
+ });
1040
+ zeroConf.scan('http', 'tcp');
1041
+ }
1042
+ catch (error) {
1043
+ logger.warn(LOG_KEY, 'zeroconf扫描或处理相关逻辑失败或者您根本就没有安装 react-native-zeroconf ,如果您没有安装,那么您将无法使用发现功能', error);
1044
+ }
1045
+ }
1046
+ updateTimeout(timeout = 3000) {
1047
+ this.timeout = timeout;
1048
+ }
1049
+ updateUrl(url = '') {
1050
+ const tempUrl = url.includes('http') ? url : `http://${url}`;
1051
+ if (!url) {
1052
+ const currentUrl = this.urlsObj.get('Default');
1053
+ if (!currentUrl) {
1054
+ return;
1055
+ }
1056
+ const isExistSomeUrl = Array.from(this.urlsObj.values()).some((url) => url === currentUrl);
1057
+ this.urlsObj.delete('Default');
1058
+ if (isExistSomeUrl) {
1059
+ return;
1060
+ }
1061
+ this.baseUrlArr.delete(currentUrl);
1062
+ }
1063
+ else if (!hasPort(tempUrl)) {
1064
+ this.updateUrl(`${tempUrl}:${DEFAULT_PORT}`);
1065
+ }
1066
+ else {
1067
+ const defaultUrl = this.urlsObj.get('Default');
1068
+ if (defaultUrl) {
1069
+ this.baseUrlArr.delete(defaultUrl);
1070
+ }
1071
+ this.baseUrlArr.add(tempUrl);
1072
+ this.urlsObj.set('Default', tempUrl);
1073
+ }
1074
+ }
1075
+ setBaseUrlArr(urlArr = new Set()) {
1076
+ this.baseUrlArr = urlArr;
1077
+ }
1078
+ getBaseUrlArr() {
1079
+ return this.baseUrlArr;
1080
+ }
1081
+ updateBaseData(data = {}) {
1082
+ this.baseData = data;
1083
+ }
1084
+ }
1085
+
1086
+ const extractHost = (url) => {
1087
+ var _a, _b;
1088
+ const host = ((_b = (_a = url.split('//')[1]) === null || _a === void 0 ? void 0 : _a.split(':')[0]) === null || _b === void 0 ? void 0 : _b.split('/')[0]) || undefined;
1089
+ return host;
1090
+ };
1091
+ const generateUniqueId = () => {
1092
+ return Date.now().toString(36) + Math.random().toString(36).substr(2);
1093
+ };
1094
+ const parseResponseBlob = async (response) => {
1095
+ const blobReader = new BlobFileReader();
1096
+ blobReader.readAsText(response);
1097
+ return await new Promise((resolve, reject) => {
1098
+ const handleError = () => reject(blobReader.error);
1099
+ blobReader.addEventListener('load', () => {
1100
+ var _a;
1101
+ resolve((_a = blobReader.result) !== null && _a !== void 0 ? _a : '');
1102
+ });
1103
+ blobReader.addEventListener('error', handleError);
1104
+ blobReader.addEventListener('abort', handleError);
1105
+ });
1106
+ };
1107
+ const getResponseBody = async (responseType, response) => {
1108
+ try {
1109
+ if (responseType === 'blob' && response) {
1110
+ return await parseResponseBlob(response);
1111
+ }
1112
+ return response !== null && response !== void 0 ? response : null;
1113
+ }
1114
+ catch (error) {
1115
+ logger.warn('getResponseBody---error---', error);
1116
+ return null;
1117
+ }
1118
+ };
1119
+ class HTTPInterceptor {
1120
+ constructor() {
1121
+ this.allRequests = new Map();
1122
+ this.userListeners = [];
1123
+ this.enabled = false;
1124
+ this.addListener = (eventName, listener) => {
1125
+ if (this.userListeners.find(([name, tempListener]) => name === eventName && tempListener === listener)) {
1126
+ return;
1127
+ }
1128
+ this.userListeners.push([eventName, listener]);
1129
+ return () => {
1130
+ this.userListeners = this.userListeners.filter(([name, tempListener]) => name !== eventName || tempListener !== listener);
1131
+ };
1132
+ };
1133
+ this.removeListener = (eventName, listener) => {
1134
+ this.userListeners = this.userListeners.filter(([name, tempListener]) => name !== eventName || tempListener !== listener);
1135
+ };
1136
+ this.listenerHandle = (eventName, data) => {
1137
+ this.userListeners.forEach(async ([name, listener]) => {
1138
+ try {
1139
+ if (name === eventName) {
1140
+ await listener(data);
1141
+ }
1142
+ }
1143
+ catch (error) {
1144
+ console.warn(`eventName=${eventName}, error=${error === null || error === void 0 ? void 0 : error.message}`);
1145
+ }
1146
+ });
1147
+ };
1148
+ this.openHandle = (method, url, xhr) => {
1149
+ if (this.ignoredHosts) {
1150
+ const host = extractHost(url);
1151
+ if (host && this.ignoredHosts.has(host)) {
1152
+ return;
1153
+ }
1154
+ }
1155
+ if (this.ignoredUrls && this.ignoredUrls.has(url)) {
1156
+ return;
1157
+ }
1158
+ if (this.ignoredPatterns) {
1159
+ if (this.ignoredPatterns.some((pattern) => pattern.test(`${method} ${url}`))) {
1160
+ return;
1161
+ }
1162
+ }
1163
+ xhr.uniqueId = HTTPInterceptor._index + generateUniqueId();
1164
+ const newRequest = {
1165
+ id: xhr.uniqueId,
1166
+ method,
1167
+ url,
1168
+ };
1169
+ this.allRequests.set(xhr.uniqueId, newRequest);
1170
+ this.listenerHandle('open', newRequest);
1171
+ };
1172
+ this.requestHeaderHandle = (header, value, xhr) => {
1173
+ const currentRequest = this.allRequests.get(xhr.uniqueId);
1174
+ if (!currentRequest) {
1175
+ return;
1176
+ }
1177
+ if (!currentRequest.requestHeaders) {
1178
+ currentRequest.requestHeaders = {};
1179
+ }
1180
+ currentRequest.requestHeaders[header] = value;
1181
+ this.listenerHandle('requestHeader', currentRequest);
1182
+ };
1183
+ this.headerReceivedHandle = (responseContentType, responseSize, responseHeaders, xhr) => {
1184
+ const currentRequest = this.allRequests.get(xhr.uniqueId);
1185
+ if (!currentRequest) {
1186
+ return;
1187
+ }
1188
+ currentRequest.responseContentType = responseContentType;
1189
+ currentRequest.responseSize = responseSize;
1190
+ currentRequest.responseHeaders = xhr.responseHeaders;
1191
+ this.listenerHandle('headerReceived', currentRequest);
1192
+ };
1193
+ this.responseHandle = async (status, timeout, response, responseURL, responseType, xhr) => {
1194
+ var _a;
1195
+ const currentRequest = this.allRequests.get(xhr.uniqueId);
1196
+ if (!currentRequest) {
1197
+ return;
1198
+ }
1199
+ currentRequest.endTime = Date.now();
1200
+ currentRequest.status = status;
1201
+ currentRequest.timeout = timeout;
1202
+ currentRequest.responseData = await getResponseBody(responseType, response);
1203
+ currentRequest.responseURL = responseURL;
1204
+ currentRequest.responseType = responseType;
1205
+ currentRequest.duration =
1206
+ currentRequest.endTime - ((_a = currentRequest.startTime) !== null && _a !== void 0 ? _a : 0);
1207
+ this.listenerHandle('response', currentRequest);
1208
+ this.allRequests.delete(xhr.uniqueId);
1209
+ };
1210
+ this.sendHandle = (data, xhr) => {
1211
+ const currentRequest = this.allRequests.get(xhr.uniqueId);
1212
+ if (!currentRequest) {
1213
+ return;
1214
+ }
1215
+ try {
1216
+ if (data && typeof data === 'object' && data instanceof FormData) {
1217
+ currentRequest.requestData = formDataToString(data);
1218
+ }
1219
+ else {
1220
+ currentRequest.requestData = JSON.parse(data);
1221
+ }
1222
+ }
1223
+ catch (error) {
1224
+ currentRequest.requestData = null;
1225
+ }
1226
+ currentRequest.startTime = Date.now();
1227
+ this.listenerHandle('send', currentRequest);
1228
+ };
1229
+ this.setIgnoredUrls = (ignoredUrls) => {
1230
+ if (!Array.isArray(ignoredUrls) ||
1231
+ (ignoredUrls[0] && typeof ignoredUrls[0] !== 'string')) {
1232
+ console.warn('ignoredUrls must be an array of strings. The logger has not been started.');
1233
+ return;
1234
+ }
1235
+ this.ignoredUrls = new Set(ignoredUrls);
1236
+ };
1237
+ this.enable = (options) => {
1238
+ var _a;
1239
+ try {
1240
+ if (this.enabled ||
1241
+ (XHRInterceptor.isInterceptorEnabled() && !(options === null || options === void 0 ? void 0 : options.forceEnable))) {
1242
+ if (!this.enabled) {
1243
+ console.warn('network interceptor has not been enabled as another interceptor is already running (e.g. another debugging program). Use option `forceEnable: true` to override this behaviour.');
1244
+ }
1245
+ return;
1246
+ }
1247
+ if (options === null || options === void 0 ? void 0 : options.ignoredHosts) {
1248
+ if (!Array.isArray(options.ignoredHosts) ||
1249
+ typeof options.ignoredHosts[0] !== 'string') {
1250
+ console.warn('ignoredHosts must be an array of strings. The logger has not been started.');
1251
+ return;
1252
+ }
1253
+ this.ignoredHosts = new Set(options.ignoredHosts);
1254
+ }
1255
+ if (options === null || options === void 0 ? void 0 : options.ignoredPatterns) {
1256
+ this.ignoredPatterns = options.ignoredPatterns;
1257
+ }
1258
+ this.setIgnoredUrls((_a = options === null || options === void 0 ? void 0 : options.ignoredUrls) !== null && _a !== void 0 ? _a : []);
1259
+ XHRInterceptor.setOpenCallback(this.openHandle);
1260
+ XHRInterceptor.setRequestHeaderCallback(this.requestHeaderHandle);
1261
+ XHRInterceptor.setHeaderReceivedCallback(this.headerReceivedHandle);
1262
+ XHRInterceptor.setSendCallback(this.sendHandle);
1263
+ XHRInterceptor.setResponseCallback(this.responseHandle);
1264
+ XHRInterceptor.enableInterception();
1265
+ this.enabled = true;
1266
+ }
1267
+ catch (error) { }
1268
+ };
1269
+ this.disable = () => {
1270
+ if (!this.enabled) {
1271
+ return;
1272
+ }
1273
+ XHRInterceptor.disableInterception();
1274
+ this.enabled = false;
1275
+ };
1276
+ this.reset = () => {
1277
+ this.disable();
1278
+ this.removeAllListener();
1279
+ this.ignoredHosts = undefined;
1280
+ this.ignoredUrls = undefined;
1281
+ this.ignoredPatterns = undefined;
1282
+ this.allRequests.clear();
1283
+ };
1284
+ }
1285
+ removeAllListener() {
1286
+ this.userListeners = [];
1287
+ }
1288
+ }
1289
+ HTTPInterceptor._index = 0;
1290
+ const httpInterceptor = new HTTPInterceptor();
1291
+
1292
+ class LogPlugin {
1293
+ constructor() {
1294
+ this.server = null;
1295
+ this.timeout = null;
1296
+ this.isAuto = false;
1297
+ this.storage = getDefaultStorage();
1298
+ this.init = async () => {
1299
+ this.server = new Server();
1300
+ if (this.storage) {
1301
+ const urlsStr = await this.storage.getItem(URLS_KEY);
1302
+ if (urlsStr) {
1303
+ const urls = JSON.parse(urlsStr);
1304
+ if (Array.isArray(urls)) {
1305
+ this.server.setBaseUrlArr(new Set(urls));
1306
+ httpInterceptor.setIgnoredUrls(this.handleIgnoredUrls());
1307
+ }
1308
+ }
1309
+ }
1310
+ this.server.addUrlsListener((urlArr) => {
1311
+ if (this.storage) {
1312
+ this.storage.setItem(URLS_KEY, JSON.stringify(urlArr));
1313
+ }
1314
+ httpInterceptor.setIgnoredUrls(this.handleIgnoredUrls());
1315
+ });
1316
+ };
1317
+ this.config = ({ storage, timeout, testUrl, isAuto, baseData = {} }) => {
1318
+ if (isAuto) {
1319
+ this.auto();
1320
+ }
1321
+ else {
1322
+ this.unAuto();
1323
+ }
1324
+ this.storage = storage !== null && storage !== void 0 ? storage : getDefaultStorage();
1325
+ this.setTimeout(timeout !== null && timeout !== void 0 ? timeout : DEFAULT_TIMEOUT);
1326
+ this.setBaseUrl(testUrl);
1327
+ this.setBaseData(baseData);
1328
+ };
1329
+ this.auto = () => {
1330
+ this.startRecordNetwork();
1331
+ this.startRecordLog();
1332
+ this.isAuto = true;
1333
+ };
1334
+ this.unAuto = () => {
1335
+ this.stopRecordLog();
1336
+ httpInterceptor.disable();
1337
+ httpInterceptor.removeAllListener();
1338
+ this.isAuto = false;
1339
+ };
1340
+ this.startRecordLog = () => {
1341
+ console.log = (...data) => {
1342
+ this.log(...data);
1343
+ if (!__DEV__) {
1344
+ return;
1345
+ }
1346
+ logger.log(...data);
1347
+ };
1348
+ console.warn = (...data) => {
1349
+ this.warn(...data);
1350
+ if (!__DEV__) {
1351
+ return;
1352
+ }
1353
+ logger.warn(...data);
1354
+ };
1355
+ console.error = (...data) => {
1356
+ this.error(...data);
1357
+ if (!__DEV__) {
1358
+ return;
1359
+ }
1360
+ logger.error(...data);
1361
+ };
1362
+ };
1363
+ this.stopRecordLog = () => {
1364
+ console.log = logger.log;
1365
+ console.warn = logger.warn;
1366
+ console.error = logger.error;
1367
+ };
1368
+ this.handleIgnoredUrls = () => {
1369
+ var _a, _b;
1370
+ const urls = (_b = (_a = this.server) === null || _a === void 0 ? void 0 : _a.getBaseUrlArr) === null || _b === void 0 ? void 0 : _b.call(_a);
1371
+ const ignoredUrls = [];
1372
+ if (urls === null || urls === void 0 ? void 0 : urls.size) {
1373
+ urls.forEach((url) => {
1374
+ ignoredUrls.push(`${url}/log`, `${url}/network`, `${url}/join`);
1375
+ });
1376
+ }
1377
+ return ignoredUrls;
1378
+ };
1379
+ this.startRecordNetwork = () => {
1380
+ httpInterceptor.addListener('send', (data) => {
1381
+ var _a;
1382
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.network({
1383
+ url: data.url,
1384
+ id: data.id,
1385
+ method: data.method,
1386
+ headers: data.requestHeaders,
1387
+ body: data.requestData,
1388
+ createTime: data.startTime,
1389
+ });
1390
+ });
1391
+ httpInterceptor.addListener('response', (data) => {
1392
+ var _a;
1393
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.network({
1394
+ headers: data.responseHeaders,
1395
+ body: data.responseData,
1396
+ requestId: data.id,
1397
+ statusCode: data.status,
1398
+ endTime: data.endTime,
1399
+ });
1400
+ });
1401
+ httpInterceptor.enable({ ignoredUrls: this.handleIgnoredUrls() });
1402
+ };
1403
+ this.setBaseUrl = (url) => {
1404
+ const tempUrl = url === null || url === void 0 ? void 0 : url.trim();
1405
+ if (this.server) {
1406
+ this.server.updateUrl(tempUrl);
1407
+ }
1408
+ else {
1409
+ this.server = new Server(tempUrl);
1410
+ }
1411
+ httpInterceptor.setIgnoredUrls(this.handleIgnoredUrls());
1412
+ if (this.isAuto) {
1413
+ this.startRecordNetwork();
1414
+ this.startRecordLog();
1415
+ }
1416
+ };
1417
+ this.setTimeout = (timeout) => {
1418
+ var _a;
1419
+ if (typeof timeout === 'number') {
1420
+ this.timeout = timeout;
1421
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.updateTimeout(this.timeout);
1422
+ }
1423
+ };
1424
+ this.getTimeout = () => {
1425
+ if (typeof this.timeout === 'number') {
1426
+ return this.timeout;
1427
+ }
1428
+ return null;
1429
+ };
1430
+ this.setBaseData = (data = {}) => {
1431
+ var _a;
1432
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.updateBaseData(data);
1433
+ };
1434
+ this._log = (level, tag, ...data) => {
1435
+ var _a;
1436
+ const sendData = {
1437
+ message: data,
1438
+ tag,
1439
+ level: level !== null && level !== void 0 ? level : 'log',
1440
+ createTime: Date.now(),
1441
+ };
1442
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.log(sendData);
1443
+ };
1444
+ this.tag = (tag, ...data) => {
1445
+ this._log(Level.LOG, tag, ...data);
1446
+ };
1447
+ this.log = (...data) => {
1448
+ this._log(Level.LOG, Tag.DEFAULT, ...data);
1449
+ };
1450
+ this.warn = (...data) => {
1451
+ this._log(Level.WARN, Tag.DEFAULT, ...data);
1452
+ };
1453
+ this.error = (...data) => {
1454
+ this._log(Level.ERROR, Tag.DEFAULT, ...data);
1455
+ };
1456
+ this.init();
1457
+ }
1458
+ }
1459
+ const logPlugin = new LogPlugin();
1460
+
1461
+ module.exports = logPlugin;
7
1462
  //# sourceMappingURL=index.cjs.js.map