forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspect.js
2432 lines (2282 loc) · 79.8 KB
/
inspect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const {
Array,
ArrayIsArray,
ArrayPrototypeFilter,
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePop,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeSlice,
ArrayPrototypeSort,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
BigIntPrototypeValueOf,
BooleanPrototypeValueOf,
DatePrototypeGetTime,
DatePrototypeToISOString,
DatePrototypeToString,
ErrorPrototypeToString,
FunctionPrototypeBind,
FunctionPrototypeCall,
FunctionPrototypeToString,
JSONStringify,
MapPrototypeEntries,
MapPrototypeGetSize,
MathFloor,
MathMax,
MathMin,
MathRound,
MathSqrt,
MathTrunc,
Number,
NumberIsFinite,
NumberIsNaN,
NumberParseFloat,
NumberParseInt,
NumberPrototypeToString,
NumberPrototypeValueOf,
Object,
ObjectAssign,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
ObjectGetOwnPropertyNames,
ObjectGetOwnPropertySymbols,
ObjectGetPrototypeOf,
ObjectIs,
ObjectKeys,
ObjectPrototypeHasOwnProperty,
ObjectPrototypePropertyIsEnumerable,
ObjectSeal,
ObjectSetPrototypeOf,
ReflectApply,
ReflectOwnKeys,
RegExp,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
RegExpPrototypeSymbolSplit,
RegExpPrototypeToString,
SafeMap,
SafeSet,
SafeStringIterator,
SetPrototypeGetSize,
SetPrototypeValues,
String,
StringPrototypeCharCodeAt,
StringPrototypeCodePointAt,
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeIndexOf,
StringPrototypeLastIndexOf,
StringPrototypeNormalize,
StringPrototypePadEnd,
StringPrototypePadStart,
StringPrototypeRepeat,
StringPrototypeReplaceAll,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
StringPrototypeToLowerCase,
StringPrototypeTrim,
StringPrototypeValueOf,
SymbolIterator,
SymbolPrototypeToString,
SymbolPrototypeValueOf,
SymbolToPrimitive,
SymbolToStringTag,
TypedArrayPrototypeGetLength,
TypedArrayPrototypeGetSymbolToStringTag,
Uint8Array,
globalThis,
uncurryThis,
} = primordials;
const {
constants: {
ALL_PROPERTIES,
ONLY_ENUMERABLE,
kPending,
kRejected,
},
getOwnNonIndexProperties,
getPromiseDetails,
getProxyDetails,
previewEntries,
getConstructorName: internalGetConstructorName,
getExternalValue,
} = internalBinding('util');
const {
customInspectSymbol,
isError,
join,
removeColors,
} = require('internal/util');
const {
isStackOverflowError,
} = require('internal/errors');
const {
isAsyncFunction,
isGeneratorFunction,
isAnyArrayBuffer,
isArrayBuffer,
isArgumentsObject,
isBoxedPrimitive,
isDataView,
isExternal,
isMap,
isMapIterator,
isModuleNamespaceObject,
isNativeError,
isPromise,
isSet,
isSetIterator,
isWeakMap,
isWeakSet,
isRegExp,
isDate,
isTypedArray,
isStringObject,
isNumberObject,
isBooleanObject,
isBigIntObject,
} = require('internal/util/types');
const assert = require('internal/assert');
const { BuiltinModule } = require('internal/bootstrap/realm');
const {
validateObject,
validateString,
kValidateObjectAllowArray,
} = require('internal/validators');
let hexSlice;
let internalUrl;
function pathToFileUrlHref(filepath) {
internalUrl ??= require('internal/url');
return internalUrl.pathToFileURL(filepath).href;
}
const builtInObjects = new SafeSet(
ArrayPrototypeFilter(
ObjectGetOwnPropertyNames(globalThis),
(e) => RegExpPrototypeExec(/^[A-Z][a-zA-Z0-9]+$/, e) !== null,
),
);
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
const isUndetectableObject = (v) => typeof v === 'undefined' && v !== undefined;
// These options must stay in sync with `getUserOptions`. So if any option will
// be added or removed, `getUserOptions` must also be updated accordingly.
const inspectDefaultOptions = ObjectSeal({
showHidden: false,
depth: 2,
colors: false,
customInspect: true,
showProxy: false,
maxArrayLength: 100,
maxStringLength: 10000,
breakLength: 80,
compact: 3,
sorted: false,
getters: false,
numericSeparator: false,
});
const kObjectType = 0;
const kArrayType = 1;
const kArrayExtrasType = 2;
/* eslint-disable no-control-regex */
const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
const strEscapeSequencesRegExpSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
const strEscapeSequencesReplacerSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
/* eslint-enable no-control-regex */
const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
const numberRegExp = /^(0|[1-9][0-9]*)$/;
const coreModuleRegExp = /^ {4}at (?:[^/\\(]+ \(|)node:(.+):\d+:\d+\)?$/;
const nodeModulesRegExp = /[/\\]node_modules[/\\](.+?)(?=[/\\])/g;
const classRegExp = /^(\s+[^(]*?)\s*{/;
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
const stripCommentsRegExp = /(\/\/.*?\n)|(\/\*(.|\n)*?\*\/)/g;
const kMinLineLength = 16;
// Constants to map the iterator state.
const kWeak = 0;
const kIterator = 1;
const kMapEntries = 2;
// Escaped control characters (plus the single quote and the backslash). Use
// empty strings to fill up unused entries.
const meta = [
'\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07', // x07
'\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F', // x0F
'\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17', // x17
'\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F', // x1F
'', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '', // x2F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x3F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x4F
'', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', // x5F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', // x6F
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F', // x7F
'\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87', // x87
'\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F', // x8F
'\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97', // x97
'\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F', // x9F
];
// Regex used for ansi escape code splitting
// Adopted from https://github.com/chalk/ansi-regex/blob/HEAD/index.js
// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore
// Matches all ansi escape code sequences in a string
const ansiPattern = '[\\u001B\\u009B][[\\]()#;?]*' +
'(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*' +
'|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' +
'|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))';
const ansi = new RegExp(ansiPattern, 'g');
let getStringWidth;
function getUserOptions(ctx, isCrossContext) {
const ret = {
stylize: ctx.stylize,
showHidden: ctx.showHidden,
depth: ctx.depth,
colors: ctx.colors,
customInspect: ctx.customInspect,
showProxy: ctx.showProxy,
maxArrayLength: ctx.maxArrayLength,
maxStringLength: ctx.maxStringLength,
breakLength: ctx.breakLength,
compact: ctx.compact,
sorted: ctx.sorted,
getters: ctx.getters,
numericSeparator: ctx.numericSeparator,
...ctx.userOptions,
};
// Typically, the target value will be an instance of `Object`. If that is
// *not* the case, the object may come from another vm.Context, and we want
// to avoid passing it objects from this Context in that case, so we remove
// the prototype from the returned object itself + the `stylize()` function,
// and remove all other non-primitives, including non-primitive user options.
if (isCrossContext) {
ObjectSetPrototypeOf(ret, null);
for (const key of ObjectKeys(ret)) {
if ((typeof ret[key] === 'object' || typeof ret[key] === 'function') &&
ret[key] !== null) {
delete ret[key];
}
}
ret.stylize = ObjectSetPrototypeOf((value, flavour) => {
let stylized;
try {
stylized = `${ctx.stylize(value, flavour)}`;
} catch {
// Continue regardless of error.
}
if (typeof stylized !== 'string') return value;
// `stylized` is a string as it should be, which is safe to pass along.
return stylized;
}, null);
}
return ret;
}
/**
* Echos the value of any input. Tries to print the value out
* in the best way possible given the different types.
* @param {any} value The value to print out.
* @param {object} opts Optional options object that alters the output.
*/
/* Legacy: value, showHidden, depth, colors */
function inspect(value, opts) {
// Default options
const ctx = {
budget: {},
indentationLvl: 0,
seen: [],
currentDepth: 0,
stylize: stylizeNoColor,
showHidden: inspectDefaultOptions.showHidden,
depth: inspectDefaultOptions.depth,
colors: inspectDefaultOptions.colors,
customInspect: inspectDefaultOptions.customInspect,
showProxy: inspectDefaultOptions.showProxy,
maxArrayLength: inspectDefaultOptions.maxArrayLength,
maxStringLength: inspectDefaultOptions.maxStringLength,
breakLength: inspectDefaultOptions.breakLength,
compact: inspectDefaultOptions.compact,
sorted: inspectDefaultOptions.sorted,
getters: inspectDefaultOptions.getters,
numericSeparator: inspectDefaultOptions.numericSeparator,
};
if (arguments.length > 1) {
// Legacy...
if (arguments.length > 2) {
if (arguments[2] !== undefined) {
ctx.depth = arguments[2];
}
if (arguments.length > 3 && arguments[3] !== undefined) {
ctx.colors = arguments[3];
}
}
// Set user-specified options
if (typeof opts === 'boolean') {
ctx.showHidden = opts;
} else if (opts) {
const optKeys = ObjectKeys(opts);
for (let i = 0; i < optKeys.length; ++i) {
const key = optKeys[i];
// TODO(BridgeAR): Find a solution what to do about stylize. Either make
// this function public or add a new API with a similar or better
// functionality.
if (
ObjectPrototypeHasOwnProperty(inspectDefaultOptions, key) ||
key === 'stylize') {
ctx[key] = opts[key];
} else if (ctx.userOptions === undefined) {
// This is required to pass through the actual user input.
ctx.userOptions = opts;
}
}
}
}
if (ctx.colors) ctx.stylize = stylizeWithColor;
if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
if (ctx.maxStringLength === null) ctx.maxStringLength = Infinity;
return formatValue(ctx, value, 0);
}
inspect.custom = customInspectSymbol;
ObjectDefineProperty(inspect, 'defaultOptions', {
__proto__: null,
get() {
return inspectDefaultOptions;
},
set(options) {
validateObject(options, 'options');
return ObjectAssign(inspectDefaultOptions, options);
},
});
// Set Graphics Rendition https://en.wikipedia.org/wiki/ANSI_escape_code#graphics
// Each color consists of an array with the color code as first entry and the
// reset code as second entry.
const defaultFG = 39;
const defaultBG = 49;
inspect.colors = {
__proto__: null,
reset: [0, 0],
bold: [1, 22],
dim: [2, 22], // Alias: faint
italic: [3, 23],
underline: [4, 24],
blink: [5, 25],
// Swap foreground and background colors
inverse: [7, 27], // Alias: swapcolors, swapColors
hidden: [8, 28], // Alias: conceal
strikethrough: [9, 29], // Alias: strikeThrough, crossedout, crossedOut
doubleunderline: [21, 24], // Alias: doubleUnderline
black: [30, defaultFG],
red: [31, defaultFG],
green: [32, defaultFG],
yellow: [33, defaultFG],
blue: [34, defaultFG],
magenta: [35, defaultFG],
cyan: [36, defaultFG],
white: [37, defaultFG],
bgBlack: [40, defaultBG],
bgRed: [41, defaultBG],
bgGreen: [42, defaultBG],
bgYellow: [43, defaultBG],
bgBlue: [44, defaultBG],
bgMagenta: [45, defaultBG],
bgCyan: [46, defaultBG],
bgWhite: [47, defaultBG],
framed: [51, 54],
overlined: [53, 55],
gray: [90, defaultFG], // Alias: grey, blackBright
redBright: [91, defaultFG],
greenBright: [92, defaultFG],
yellowBright: [93, defaultFG],
blueBright: [94, defaultFG],
magentaBright: [95, defaultFG],
cyanBright: [96, defaultFG],
whiteBright: [97, defaultFG],
bgGray: [100, defaultBG], // Alias: bgGrey, bgBlackBright
bgRedBright: [101, defaultBG],
bgGreenBright: [102, defaultBG],
bgYellowBright: [103, defaultBG],
bgBlueBright: [104, defaultBG],
bgMagentaBright: [105, defaultBG],
bgCyanBright: [106, defaultBG],
bgWhiteBright: [107, defaultBG],
};
function defineColorAlias(target, alias) {
ObjectDefineProperty(inspect.colors, alias, {
__proto__: null,
get() {
return this[target];
},
set(value) {
this[target] = value;
},
configurable: true,
enumerable: false,
});
}
defineColorAlias('gray', 'grey');
defineColorAlias('gray', 'blackBright');
defineColorAlias('bgGray', 'bgGrey');
defineColorAlias('bgGray', 'bgBlackBright');
defineColorAlias('dim', 'faint');
defineColorAlias('strikethrough', 'crossedout');
defineColorAlias('strikethrough', 'strikeThrough');
defineColorAlias('strikethrough', 'crossedOut');
defineColorAlias('hidden', 'conceal');
defineColorAlias('inverse', 'swapColors');
defineColorAlias('inverse', 'swapcolors');
defineColorAlias('doubleunderline', 'doubleUnderline');
// TODO(BridgeAR): Add function style support for more complex styles.
// Don't use 'blue' not visible on cmd.exe
inspect.styles = ObjectAssign({ __proto__: null }, {
special: 'cyan',
number: 'yellow',
bigint: 'yellow',
boolean: 'yellow',
undefined: 'grey',
null: 'bold',
string: 'green',
symbol: 'green',
date: 'magenta',
// "name": intentionally not styling
// TODO(BridgeAR): Highlight regular expressions properly.
regexp: 'red',
module: 'underline',
});
function addQuotes(str, quotes) {
if (quotes === -1) {
return `"${str}"`;
}
if (quotes === -2) {
return `\`${str}\``;
}
return `'${str}'`;
}
function escapeFn(str) {
const charCode = StringPrototypeCharCodeAt(str);
return meta.length > charCode ? meta[charCode] : `\\u${NumberPrototypeToString(charCode, 16)}`;
}
// Escape control characters, single quotes and the backslash.
// This is similar to JSON stringify escaping.
function strEscape(str) {
let escapeTest = strEscapeSequencesRegExp;
let escapeReplace = strEscapeSequencesReplacer;
let singleQuote = 39;
// Check for double quotes. If not present, do not escape single quotes and
// instead wrap the text in double quotes. If double quotes exist, check for
// backticks. If they do not exist, use those as fallback instead of the
// double quotes.
if (StringPrototypeIncludes(str, "'")) {
// This invalidates the charCode and therefore can not be matched for
// anymore.
if (!StringPrototypeIncludes(str, '"')) {
singleQuote = -1;
} else if (!StringPrototypeIncludes(str, '`') &&
!StringPrototypeIncludes(str, '${')) {
singleQuote = -2;
}
if (singleQuote !== 39) {
escapeTest = strEscapeSequencesRegExpSingle;
escapeReplace = strEscapeSequencesReplacerSingle;
}
}
// Some magic numbers that worked out fine while benchmarking with v8 6.0
if (str.length < 5000 && RegExpPrototypeExec(escapeTest, str) === null)
return addQuotes(str, singleQuote);
if (str.length > 100) {
str = RegExpPrototypeSymbolReplace(escapeReplace, str, escapeFn);
return addQuotes(str, singleQuote);
}
let result = '';
let last = 0;
for (let i = 0; i < str.length; i++) {
const point = StringPrototypeCharCodeAt(str, i);
if (point === singleQuote ||
point === 92 ||
point < 32 ||
(point > 126 && point < 160)) {
if (last === i) {
result += meta[point];
} else {
result += `${StringPrototypeSlice(str, last, i)}${meta[point]}`;
}
last = i + 1;
} else if (point >= 0xd800 && point <= 0xdfff) {
if (point <= 0xdbff && i + 1 < str.length) {
const point = StringPrototypeCharCodeAt(str, i + 1);
if (point >= 0xdc00 && point <= 0xdfff) {
i++;
continue;
}
}
result += `${StringPrototypeSlice(str, last, i)}\\u${NumberPrototypeToString(point, 16)}`;
last = i + 1;
}
}
if (last !== str.length) {
result += StringPrototypeSlice(str, last);
}
return addQuotes(result, singleQuote);
}
function stylizeWithColor(str, styleType) {
const style = inspect.styles[styleType];
if (style !== undefined) {
const color = inspect.colors[style];
if (color !== undefined)
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
}
return str;
}
function stylizeNoColor(str) {
return str;
}
// Return a new empty array to push in the results of the default formatter.
function getEmptyFormatArray() {
return [];
}
function isInstanceof(object, proto) {
try {
return object instanceof proto;
} catch {
return false;
}
}
function getConstructorName(obj, ctx, recurseTimes, protoProps) {
let firstProto;
const tmp = obj;
while (obj || isUndetectableObject(obj)) {
const descriptor = ObjectGetOwnPropertyDescriptor(obj, 'constructor');
if (descriptor !== undefined &&
typeof descriptor.value === 'function' &&
descriptor.value.name !== '' &&
isInstanceof(tmp, descriptor.value)) {
if (protoProps !== undefined &&
(firstProto !== obj ||
!builtInObjects.has(descriptor.value.name))) {
addPrototypeProperties(
ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
}
return String(descriptor.value.name);
}
obj = ObjectGetPrototypeOf(obj);
if (firstProto === undefined) {
firstProto = obj;
}
}
if (firstProto === null) {
return null;
}
const res = internalGetConstructorName(tmp);
if (recurseTimes > ctx.depth && ctx.depth !== null) {
return `${res} <Complex prototype>`;
}
const protoConstr = getConstructorName(
firstProto, ctx, recurseTimes + 1, protoProps);
if (protoConstr === null) {
return `${res} <${inspect(firstProto, {
...ctx,
customInspect: false,
depth: -1,
})}>`;
}
return `${res} <${protoConstr}>`;
}
// This function has the side effect of adding prototype properties to the
// `output` argument (which is an array). This is intended to highlight user
// defined prototype properties.
function addPrototypeProperties(ctx, main, obj, recurseTimes, output) {
let depth = 0;
let keys;
let keySet;
do {
if (depth !== 0 || main === obj) {
obj = ObjectGetPrototypeOf(obj);
// Stop as soon as a null prototype is encountered.
if (obj === null) {
return;
}
// Stop as soon as a built-in object type is detected.
const descriptor = ObjectGetOwnPropertyDescriptor(obj, 'constructor');
if (descriptor !== undefined &&
typeof descriptor.value === 'function' &&
builtInObjects.has(descriptor.value.name)) {
return;
}
}
if (depth === 0) {
keySet = new SafeSet();
} else {
ArrayPrototypeForEach(keys, (key) => keySet.add(key));
}
// Get all own property names and symbols.
keys = ReflectOwnKeys(obj);
ArrayPrototypePush(ctx.seen, main);
for (const key of keys) {
// Ignore the `constructor` property and keys that exist on layers above.
if (key === 'constructor' ||
ObjectPrototypeHasOwnProperty(main, key) ||
(depth !== 0 && keySet.has(key))) {
continue;
}
const desc = ObjectGetOwnPropertyDescriptor(obj, key);
if (typeof desc.value === 'function') {
continue;
}
const value = formatProperty(
ctx, obj, recurseTimes, key, kObjectType, desc, main);
if (ctx.colors) {
// Faint!
ArrayPrototypePush(output, `\u001b[2m${value}\u001b[22m`);
} else {
ArrayPrototypePush(output, value);
}
}
ArrayPrototypePop(ctx.seen);
// Limit the inspection to up to three prototype layers. Using `recurseTimes`
// is not a good choice here, because it's as if the properties are declared
// on the current object from the users perspective.
} while (++depth !== 3);
}
function getPrefix(constructor, tag, fallback, size = '') {
if (constructor === null) {
if (tag !== '' && fallback !== tag) {
return `[${fallback}${size}: null prototype] [${tag}] `;
}
return `[${fallback}${size}: null prototype] `;
}
if (tag !== '' && constructor !== tag) {
return `${constructor}${size} [${tag}] `;
}
return `${constructor}${size} `;
}
// Look up the keys of the object.
function getKeys(value, showHidden) {
let keys;
const symbols = ObjectGetOwnPropertySymbols(value);
if (showHidden) {
keys = ObjectGetOwnPropertyNames(value);
if (symbols.length !== 0)
ArrayPrototypePushApply(keys, symbols);
} else {
// This might throw if `value` is a Module Namespace Object from an
// unevaluated module, but we don't want to perform the actual type
// check because it's expensive.
// TODO(devsnek): track https://github.com/tc39/ecma262/issues/1209
// and modify this logic as needed.
try {
keys = ObjectKeys(value);
} catch (err) {
assert(isNativeError(err) && err.name === 'ReferenceError' &&
isModuleNamespaceObject(value));
keys = ObjectGetOwnPropertyNames(value);
}
if (symbols.length !== 0) {
const filter = (key) => ObjectPrototypePropertyIsEnumerable(value, key);
ArrayPrototypePushApply(keys, ArrayPrototypeFilter(symbols, filter));
}
}
return keys;
}
function getCtxStyle(value, constructor, tag) {
let fallback = '';
if (constructor === null) {
fallback = internalGetConstructorName(value);
if (fallback === tag) {
fallback = 'Object';
}
}
return getPrefix(constructor, tag, fallback);
}
function formatProxy(ctx, proxy, recurseTimes) {
if (recurseTimes > ctx.depth && ctx.depth !== null) {
return ctx.stylize('Proxy [Array]', 'special');
}
recurseTimes += 1;
ctx.indentationLvl += 2;
const res = [
formatValue(ctx, proxy[0], recurseTimes),
formatValue(ctx, proxy[1], recurseTimes),
];
ctx.indentationLvl -= 2;
return reduceToSingleString(
ctx, res, '', ['Proxy [', ']'], kArrayExtrasType, recurseTimes);
}
// Note: using `formatValue` directly requires the indentation level to be
// corrected by setting `ctx.indentationLvL += diff` and then to decrease the
// value afterwards again.
function formatValue(ctx, value, recurseTimes, typedArray) {
// Primitive types cannot have properties.
if (typeof value !== 'object' &&
typeof value !== 'function' &&
!isUndetectableObject(value)) {
return formatPrimitive(ctx.stylize, value, ctx);
}
if (value === null) {
return ctx.stylize('null', 'null');
}
// Memorize the context for custom inspection on proxies.
const context = value;
// Always check for proxies to prevent side effects and to prevent triggering
// any proxy handlers.
const proxy = getProxyDetails(value, !!ctx.showProxy);
if (proxy !== undefined) {
if (proxy === null || proxy[0] === null) {
return ctx.stylize('<Revoked Proxy>', 'special');
}
if (ctx.showProxy) {
return formatProxy(ctx, proxy, recurseTimes);
}
value = proxy;
}
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it.
if (ctx.customInspect) {
const maybeCustom = value[customInspectSymbol];
if (typeof maybeCustom === 'function' &&
// Filter out the util module, its inspect function is special.
maybeCustom !== inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
// This makes sure the recurseTimes are reported as before while using
// a counter internally.
const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
const isCrossContext =
proxy !== undefined || !(context instanceof Object);
const ret = FunctionPrototypeCall(
maybeCustom,
context,
depth,
getUserOptions(ctx, isCrossContext),
inspect,
);
// If the custom inspection method returned `this`, don't go into
// infinite recursion.
if (ret !== context) {
if (typeof ret !== 'string') {
return formatValue(ctx, ret, recurseTimes);
}
return StringPrototypeReplaceAll(ret, '\n', `\n${StringPrototypeRepeat(' ', ctx.indentationLvl)}`);
}
}
}
// Using an array here is actually better for the average case than using
// a Set. `seen` will only check for the depth and will never grow too large.
if (ctx.seen.includes(value)) {
let index = 1;
if (ctx.circular === undefined) {
ctx.circular = new SafeMap();
ctx.circular.set(value, index);
} else {
index = ctx.circular.get(value);
if (index === undefined) {
index = ctx.circular.size + 1;
ctx.circular.set(value, index);
}
}
return ctx.stylize(`[Circular *${index}]`, 'special');
}
return formatRaw(ctx, value, recurseTimes, typedArray);
}
function formatRaw(ctx, value, recurseTimes, typedArray) {
let keys;
let protoProps;
if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) {
protoProps = [];
}
const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
// Reset the variable to check for this later on.
if (protoProps !== undefined && protoProps.length === 0) {
protoProps = undefined;
}
let tag = value[SymbolToStringTag];
// Only list the tag in case it's non-enumerable / not an own property.
// Otherwise we'd print this twice.
if (typeof tag !== 'string' ||
(tag !== '' &&
(ctx.showHidden ?
ObjectPrototypeHasOwnProperty :
ObjectPrototypePropertyIsEnumerable)(
value, SymbolToStringTag,
))) {
tag = '';
}
let base = '';
let formatter = getEmptyFormatArray;
let braces;
let noIterator = true;
let i = 0;
const filter = ctx.showHidden ? ALL_PROPERTIES : ONLY_ENUMERABLE;
let extrasType = kObjectType;
// Iterators and the rest are split to reduce checks.
// We have to check all values in case the constructor is set to null.
// Otherwise it would not possible to identify all types properly.
if (SymbolIterator in value || constructor === null) {
noIterator = false;
if (ArrayIsArray(value)) {
// Only set the constructor for non ordinary ("Array [...]") arrays.
const prefix = (constructor !== 'Array' || tag !== '') ?
getPrefix(constructor, tag, 'Array', `(${value.length})`) :
'';
keys = getOwnNonIndexProperties(value, filter);
braces = [`${prefix}[`, ']'];
if (value.length === 0 && keys.length === 0 && protoProps === undefined)
return `${braces[0]}]`;
extrasType = kArrayExtrasType;
formatter = formatArray;
} else if (isSet(value)) {
const size = SetPrototypeGetSize(value);
const prefix = getPrefix(constructor, tag, 'Set', `(${size})`);
keys = getKeys(value, ctx.showHidden);
formatter = constructor !== null ?
FunctionPrototypeBind(formatSet, null, value) :
FunctionPrototypeBind(formatSet, null, SetPrototypeValues(value));
if (size === 0 && keys.length === 0 && protoProps === undefined)
return `${prefix}{}`;
braces = [`${prefix}{`, '}'];
} else if (isMap(value)) {
const size = MapPrototypeGetSize(value);
const prefix = getPrefix(constructor, tag, 'Map', `(${size})`);
keys = getKeys(value, ctx.showHidden);
formatter = constructor !== null ?
FunctionPrototypeBind(formatMap, null, value) :
FunctionPrototypeBind(formatMap, null, MapPrototypeEntries(value));
if (size === 0 && keys.length === 0 && protoProps === undefined)
return `${prefix}{}`;
braces = [`${prefix}{`, '}'];
} else if (isTypedArray(value)) {
keys = getOwnNonIndexProperties(value, filter);
let bound = value;
let fallback = '';
if (constructor === null) {
fallback = TypedArrayPrototypeGetSymbolToStringTag(value);
// Reconstruct the array information.
bound = new primordials[fallback](value);
}
const size = TypedArrayPrototypeGetLength(value);
const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
braces = [`${prefix}[`, ']'];
if (value.length === 0 && keys.length === 0 && !ctx.showHidden)
return `${braces[0]}]`;
// Special handle the value. The original value is required below. The
// bound function is required to reconstruct missing information.
formatter = FunctionPrototypeBind(formatTypedArray, null, bound, size);
extrasType = kArrayExtrasType;
} else if (isMapIterator(value)) {
keys = getKeys(value, ctx.showHidden);
braces = getIteratorBraces('Map', tag);
// Add braces to the formatter parameters.
formatter = FunctionPrototypeBind(formatIterator, null, braces);
} else if (isSetIterator(value)) {
keys = getKeys(value, ctx.showHidden);
braces = getIteratorBraces('Set', tag);
// Add braces to the formatter parameters.
formatter = FunctionPrototypeBind(formatIterator, null, braces);
} else {
noIterator = true;
}
}
if (noIterator) {
keys = getKeys(value, ctx.showHidden);
braces = ['{', '}'];
if (constructor === 'Object') {
if (isArgumentsObject(value)) {
braces[0] = '[Arguments] {';
} else if (tag !== '') {
braces[0] = `${getPrefix(constructor, tag, 'Object')}{`;
}
if (keys.length === 0 && protoProps === undefined) {
return `${braces[0]}}`;
}
} else if (typeof value === 'function') {
base = getFunctionBase(value, constructor, tag);
if (keys.length === 0 && protoProps === undefined)
return ctx.stylize(base, 'special');
} else if (isRegExp(value)) {
// Make RegExps say that they are RegExps
base = RegExpPrototypeToString(
constructor !== null ? value : new RegExp(value),
);
const prefix = getPrefix(constructor, tag, 'RegExp');
if (prefix !== 'RegExp ')
base = `${prefix}${base}`;
if ((keys.length === 0 && protoProps === undefined) ||
(recurseTimes > ctx.depth && ctx.depth !== null)) {
return ctx.stylize(base, 'regexp');
}
} else if (isDate(value)) {
// Make dates with properties first say the date
base = NumberIsNaN(DatePrototypeGetTime(value)) ?
DatePrototypeToString(value) :
DatePrototypeToISOString(value);
const prefix = getPrefix(constructor, tag, 'Date');
if (prefix !== 'Date ')
base = `${prefix}${base}`;
if (keys.length === 0 && protoProps === undefined) {
return ctx.stylize(base, 'date');
}
} else if (isError(value)) {
base = formatError(value, constructor, tag, ctx, keys);
if (keys.length === 0 && protoProps === undefined)
return base;
} else if (isAnyArrayBuffer(value)) {
// Fast path for ArrayBuffer and SharedArrayBuffer.
// Can't do the same for DataView because it has a non-primitive
// .buffer property that we need to recurse for.
const arrayType = isArrayBuffer(value) ? 'ArrayBuffer' :
'SharedArrayBuffer';
const prefix = getPrefix(constructor, tag, arrayType);
if (typedArray === undefined) {
formatter = formatArrayBuffer;
} else if (keys.length === 0 && protoProps === undefined) {
return prefix +
`{ byteLength: ${formatNumber(ctx.stylize, value.byteLength, false)} }`;