@ohos-ports/bun-repl 0.0.0-stage → 2.1.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2760 @@
1
+ /**
2
+ @license
3
+ This code is an adaptation of the Node.js internal implementation, mostly from the file lib/internal/util/inspect.js,
4
+ which does not have the Joyent copyright header. The maintainers of this package will not assert copyright over this code,
5
+ but will assign ownership to the Node.js contributors, with the same license as specified in the Node.js codebase;
6
+ the portion adapted here should all be plain MIT license.
7
+
8
+ Node.js is licensed for use as follows:
9
+ Copyright Node.js contributors. All rights reserved.
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to
13
+ deal in the Software without restriction, including without limitation the
14
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
15
+ sell copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in
19
+ all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
22
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
25
+ // Node port: this file reads `Bun.enableANSIColors` / `Bun.peek` at module top
26
+ // level and uses `require("node:util/types")` (Bun allows require in ESM).
27
+ import '../shims/bun.js';
28
+ import util from 'node:util';
29
+ import { pathToFileURL } from 'node:url';
30
+ import { createRequire } from 'node:module';
31
+ import $proxy from './proxy.js';
32
+ import primordials from './primordials.js';
33
+ const require = createRequire(import.meta.url);
34
+ const {
35
+ Array,
36
+ ArrayFrom,
37
+ ArrayIsArray,
38
+ ArrayPrototypeFilter,
39
+ ArrayPrototypeFlat,
40
+ ArrayPrototypeForEach,
41
+ ArrayPrototypeIncludes,
42
+ ArrayPrototypeIndexOf,
43
+ ArrayPrototypeJoin,
44
+ ArrayPrototypeMap,
45
+ ArrayPrototypePop,
46
+ ArrayPrototypePush,
47
+ ArrayPrototypePushApply,
48
+ ArrayPrototypeSlice,
49
+ ArrayPrototypeSplice,
50
+ ArrayPrototypeSort,
51
+ ArrayPrototypeUnshift,
52
+ BigIntPrototypeValueOf,
53
+ BooleanPrototypeValueOf,
54
+ DatePrototypeGetTime,
55
+ DatePrototypeToISOString,
56
+ DatePrototypeToString,
57
+ ErrorCaptureStackTrace,
58
+ ErrorPrototypeToString,
59
+ FunctionPrototypeBind,
60
+ FunctionPrototypeCall,
61
+ FunctionPrototypeToString,
62
+ JSONStringify,
63
+ MapPrototypeGetSize,
64
+ MapPrototypeEntries,
65
+ MapPrototypeValues,
66
+ MapPrototypeKeys,
67
+ MathFloor,
68
+ MathMax,
69
+ MathMin,
70
+ MathRound,
71
+ MathSqrt,
72
+ MathTrunc,
73
+ Number,
74
+ NumberIsFinite,
75
+ NumberIsNaN,
76
+ NumberParseFloat,
77
+ NumberParseInt,
78
+ NumberPrototypeToString,
79
+ NumberPrototypeValueOf,
80
+ Object,
81
+ ObjectAssign,
82
+ ObjectDefineProperty,
83
+ ObjectEntries,
84
+ ObjectGetOwnPropertyDescriptor,
85
+ ObjectGetOwnPropertyDescriptors,
86
+ ObjectGetOwnPropertyNames,
87
+ ObjectGetOwnPropertySymbols,
88
+ ObjectGetPrototypeOf,
89
+ ObjectIs,
90
+ ObjectKeys,
91
+ ObjectPrototypeHasOwnProperty,
92
+ ObjectPrototypePropertyIsEnumerable,
93
+ ObjectPrototypeToString,
94
+ ObjectSeal,
95
+ ObjectSetPrototypeOf,
96
+ ReflectApply,
97
+ ReflectOwnKeys,
98
+ RegExp,
99
+ RegExpPrototypeExec,
100
+ RegExpPrototypeSymbolReplace,
101
+ RegExpPrototypeSymbolSplit,
102
+ RegExpPrototypeTest,
103
+ RegExpPrototypeToString,
104
+ SafeStringIterator,
105
+ SafeMap,
106
+ SafeSet,
107
+ SetPrototypeEntries,
108
+ SetPrototypeGetSize,
109
+ SetPrototypeValues,
110
+ String,
111
+ StringPrototypeCharCodeAt,
112
+ StringPrototypeCodePointAt,
113
+ StringPrototypeIncludes,
114
+ StringPrototypeIndexOf,
115
+ StringPrototypeLastIndexOf,
116
+ StringPrototypeMatch,
117
+ StringPrototypeNormalize,
118
+ StringPrototypePadEnd,
119
+ StringPrototypePadStart,
120
+ StringPrototypeRepeat,
121
+ StringPrototypeReplaceAll,
122
+ StringPrototypeSlice,
123
+ StringPrototypeSplit,
124
+ StringPrototypeEndsWith,
125
+ StringPrototypeStartsWith,
126
+ StringPrototypeToLowerCase,
127
+ StringPrototypeTrim,
128
+ StringPrototypeValueOf,
129
+ SymbolPrototypeToString,
130
+ SymbolPrototypeValueOf,
131
+ SymbolIterator,
132
+ SymbolToStringTag,
133
+ TypedArrayPrototypeGetLength,
134
+ TypedArrayPrototypeGetSymbolToStringTag,
135
+ Uint8Array,
136
+ } = primordials;
137
+
138
+ const customInspectSymbol = Symbol.for("nodejs.util.inspect.custom");
139
+ const kPending = Symbol("kPending"); // state ID 0
140
+ const kFulfilled = Symbol("kFulfilled"); // state ID 1
141
+ const kRejected = Symbol("kRejected"); // state ID 2
142
+ const ALL_PROPERTIES = 0;
143
+ const ONLY_ENUMERABLE = 2;
144
+
145
+ const isAsyncFunction = v =>
146
+ typeof v === "function" && StringPrototypeStartsWith(FunctionPrototypeToString(v), "async");
147
+ const isGeneratorFunction = v =>
148
+ typeof v === "function" && StringPrototypeMatch(FunctionPrototypeToString(v), /^(async\s+)?function *\*/);
149
+
150
+ function vmSafeInstanceof(val, ctor) {
151
+ if (val instanceof ctor) return true;
152
+ // instanceof doesn't work across vm boundaries, so check the whole inheritance chain
153
+ while (val) {
154
+ if (typeof val !== "object") return false;
155
+ if (ctor.name === internalGetConstructorName(val)) return true;
156
+ val = ObjectGetPrototypeOf(val);
157
+ }
158
+ return false;
159
+ }
160
+ function checkBox(ctor) {
161
+ return val => {
162
+ if (!vmSafeInstanceof(val, ctor)) return false;
163
+ try {
164
+ ctor.prototype.valueOf.call(val);
165
+ } catch {
166
+ return false;
167
+ }
168
+ return true;
169
+ };
170
+ }
171
+ const isBigIntObject = checkBox(BigInt);
172
+ const isSymbolObject = checkBox(Symbol);
173
+
174
+ const {
175
+ //! The native versions of the commented out functions are currently buggy, so we use the polyfills above for now.
176
+ //isAsyncFunction,
177
+ //isGeneratorFunction,
178
+ isAnyArrayBuffer,
179
+ isArrayBuffer,
180
+ isArgumentsObject,
181
+ isBoxedPrimitive: _native_isBoxedPrimitive,
182
+ isDataView,
183
+ isExternal,
184
+ isMap,
185
+ isMapIterator,
186
+ isModuleNamespaceObject,
187
+ isNativeError,
188
+ isPromise,
189
+ isSet,
190
+ isSetIterator,
191
+ isWeakMap,
192
+ isWeakSet,
193
+ isRegExp,
194
+ isDate,
195
+ isTypedArray,
196
+ isStringObject,
197
+ isNumberObject,
198
+ isBooleanObject,
199
+ //isBigIntObject,
200
+ } = require("node:util/types");
201
+
202
+ //! temp workaround to apply is{BigInt,Symbol}Object fix
203
+ const isBoxedPrimitive = val => isBigIntObject(val) || isSymbolObject(val) || _native_isBoxedPrimitive(val);
204
+
205
+ // We need this duplicate here to avoid a circular dependency between node:assert and node:util.
206
+ class AssertionError extends Error {
207
+ constructor(message, isForced = false) {
208
+ super(message);
209
+ this.name = "AssertionError";
210
+ this.code = "ERR_ASSERTION";
211
+ this.operator = "==";
212
+ this.generatedMessage = !isForced;
213
+ this.actual = isForced && undefined;
214
+ this.expected = !isForced || undefined;
215
+ }
216
+ }
217
+ function assert(p, message) {
218
+ if (!p) throw new AssertionError(message);
219
+ }
220
+
221
+ const codes = {}; // exported from errors.js
222
+ { // errors.js
223
+ // Sorted by a rough estimate on most frequently used entries.
224
+ const kTypes = [
225
+ "string",
226
+ "function",
227
+ "number",
228
+ "object",
229
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
230
+ "Function",
231
+ "Object",
232
+ "boolean",
233
+ "bigint",
234
+ "symbol",
235
+ ];
236
+ const classRegExp = /^([A-Z][a-z0-9]*)+$/;
237
+ const messages = new SafeMap();
238
+ const sym = "ERR_INVALID_ARG_TYPE";
239
+ messages.set(sym, (name, expected, actual) => {
240
+ assert(typeof name === "string", "'name' must be a string");
241
+ if (!ArrayIsArray(expected)) expected = [expected];
242
+
243
+ let msg = "The ";
244
+ if (StringPrototypeEndsWith(name, " argument")) msg += `${name} `; // For cases like 'first argument'
245
+ else msg += `"${name}" ${StringPrototypeIncludes(name, ".") ? "property" : "argument"} `;
246
+ msg += "must be ";
247
+
248
+ const types = [];
249
+ const instances = [];
250
+ const other = [];
251
+ for (const value of expected) {
252
+ assert(typeof value === "string", "All expected entries have to be of type string");
253
+ if (ArrayPrototypeIncludes(kTypes, value)) ArrayPrototypePush(types, StringPrototypeToLowerCase(value));
254
+ else if (RegExpPrototypeTest(classRegExp, value)) ArrayPrototypePush(instances, value);
255
+ else {
256
+ assert(value !== "object", 'The value "object" should be written as "Object"');
257
+ ArrayPrototypePush(other, value);
258
+ }
259
+ }
260
+ // Special handle `object` in case other instances are allowed to outline the differences between each other.
261
+ if (instances.length > 0) {
262
+ const pos = ArrayPrototypeIndexOf(types, "object");
263
+ if (pos !== -1) {
264
+ ArrayPrototypeSplice(types, pos, 1);
265
+ ArrayPrototypePush(instances, "Object");
266
+ }
267
+ }
268
+ if (types.length > 0) {
269
+ if (types.length > 2) msg += `one of type ${ArrayPrototypeJoin(types, ", ")}, or ${ArrayPrototypePop(types)}`;
270
+ else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}`;
271
+ else msg += `of type ${types[0]}`;
272
+ if (instances.length > 0 || other.length > 0) msg += " or ";
273
+ }
274
+ if (instances.length > 0) {
275
+ if (instances.length > 2) msg += `an instance of ${ArrayPrototypeJoin(instances, ", ")}, or ${ArrayPrototypePop(instances)}`;
276
+ else msg += `an instance of ${instances[0]}` + (instances.length === 2 ? ` or ${instances[1]}` : "");
277
+ if (other.length > 0) msg += " or ";
278
+ }
279
+ if (other.length > 0) {
280
+ if (other.length > 2) {
281
+ const last = ArrayPrototypePop(other);
282
+ msg += `one of ${ArrayPrototypeJoin(other, ", ")}, or ${last}`;
283
+ } else if (other.length === 2) {
284
+ msg += `one of ${other[0]} or ${other[1]}`;
285
+ } else {
286
+ if (StringPrototypeToLowerCase(other[0]) !== other[0]) msg += "an ";
287
+ msg += `${other[0]}`;
288
+ }
289
+ }
290
+
291
+ if (actual == null) msg += `. Received ${actual}`;
292
+ else if (typeof actual === "function" && actual.name) msg += `. Received function ${actual.name}`;
293
+ else if (typeof actual === "object") {
294
+ if (actual.constructor && actual.constructor.name) msg += `. Received an instance of ${actual.constructor.name}`;
295
+ else msg += `. Received ${inspect(actual, { depth: -1 })}`;
296
+ } else {
297
+ let inspected = inspect(actual, { colors: false });
298
+ if (inspected.length > 25) inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`;
299
+ msg += `. Received type ${typeof actual} (${inspected})`;
300
+ }
301
+ return msg;
302
+ });
303
+ codes[sym] = function NodeError(...args) {
304
+ const limit = Error.stackTraceLimit;
305
+ Error.stackTraceLimit = 0;
306
+ const error = new TypeError();
307
+ Error.stackTraceLimit = limit; // Reset the limit and setting the name property.
308
+
309
+ const msg = messages.get(sym);
310
+ assert(typeof msg === "function");
311
+ assert(msg.length <= args.length, // Default options do not count.
312
+ `Code: ${sym}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`);
313
+ const message = ReflectApply(msg, error, args);
314
+
315
+ ObjectDefineProperty(error, "message", { value: message, enumerable: false, writable: true, configurable: true });
316
+ ObjectDefineProperty(error, "toString", {
317
+ value() { return `${this.name} [${sym}]: ${this.message}`; },
318
+ enumerable: false, writable: true, configurable: true,
319
+ });
320
+ // addCodeToName + captureLargerStackTrace
321
+ let err = error;
322
+ const userStackTraceLimit = Error.stackTraceLimit;
323
+ Error.stackTraceLimit = Infinity;
324
+ ErrorCaptureStackTrace(err);
325
+ Error.stackTraceLimit = userStackTraceLimit; // Reset the limit
326
+ err.name = `${TypeError.name} [${sym}]`; // Add the error code to the name to include it in the stack trace.
327
+ err.stack; // Access the stack to generate the error message including the error code from the name.
328
+ Reflect.deleteProperty(err, 'name'); // Reset the name to the actual name.
329
+ Reflect.set(error, 'code', sym);
330
+ return error;
331
+ };
332
+ }
333
+ /**
334
+ * @param {unknown} value
335
+ * @param {string} name
336
+ * @param {{ allowArray?: boolean, allowFunction?: boolean, nullable?: boolean }} [options] */
337
+ const validateObject = ((value, name, allowArray = false) => {
338
+ if (
339
+ (value === null) || (!allowArray && ArrayIsArray(value)) ||
340
+ (typeof value !== "object" && (typeof value !== "function"))
341
+ ) throw new codes.ERR_INVALID_ARG_TYPE(name, "Object", value);
342
+ });
343
+
344
+ const builtInObjects = new SafeSet(
345
+ ArrayPrototypeFilter(
346
+ ObjectGetOwnPropertyNames(globalThis),
347
+ e => RegExpPrototypeExec(/^[A-Z][a-zA-Z0-9]+$/, e) !== null,
348
+ ),
349
+ );
350
+
351
+ // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
352
+ const isUndetectableObject = v => typeof v === "undefined" && v !== undefined;
353
+
354
+ // This is used for detecting stack overflows during inspection.
355
+ // It will probably never need to be changed, but it's here just in case JSC does change the message.
356
+ const ERROR_STACK_OVERFLOW_MSG = "Maximum call stack size exceeded.";
357
+
358
+ // These options must stay in sync with `getUserOptions`. So if any option will
359
+ // be added or removed, `getUserOptions` must also be updated accordingly.
360
+ const inspectDefaultOptions = ObjectSeal({
361
+ showHidden: false,
362
+ depth: 2,
363
+ colors: false,
364
+ customInspect: true,
365
+ showProxy: false,
366
+ maxArrayLength: 100,
367
+ maxStringLength: 10000,
368
+ breakLength: 80,
369
+ compact: 3,
370
+ sorted: false,
371
+ getters: false,
372
+ numericSeparator: false,
373
+ });
374
+ const inspectReplDefaults = ObjectSeal({
375
+ ...inspectDefaultOptions,
376
+ colors: Bun.enableANSIColors,
377
+ showProxy: true,
378
+ });
379
+
380
+ const kObjectType = 0;
381
+ const kArrayType = 1;
382
+ const kArrayExtrasType = 2;
383
+
384
+ // Work-arounds for Safari not implementing negative look-behinds.
385
+ // Remove all of this once Safari 16.4 is rolled out "enough".
386
+ let strEscapeSequencesRegExp,
387
+ strEscapeSequencesReplacer,
388
+ strEscapeSequencesRegExpSingle,
389
+ strEscapeSequencesReplacerSingle,
390
+ extractedSplitNewLines;
391
+ try {
392
+ // Change from regex literals to RegExp constructors to avoid unrecoverable
393
+ // syntax error at load time.
394
+ strEscapeSequencesRegExp = new RegExp(
395
+ "[\\x00-\\x1f\\x27\\x5c\\x7f-\\x9f]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]",
396
+ );
397
+ strEscapeSequencesReplacer = new RegExp(
398
+ "[\x00-\\x1f\\x27\\x5c\\x7f-\\x9f]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]",
399
+ "g",
400
+ );
401
+ strEscapeSequencesRegExpSingle = new RegExp(
402
+ "[\\x00-\\x1f\\x5c\\x7f-\\x9f]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]",
403
+ );
404
+ strEscapeSequencesReplacerSingle = new RegExp(
405
+ "[\\x00-\\x1f\\x5c\\x7f-\\x9f]|[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]",
406
+ "g",
407
+ );
408
+ const extractedNewLineRe = new RegExp("(?<=\\n)");
409
+ extractedSplitNewLines = value => RegExpPrototypeSymbolSplit(extractedNewLineRe, value);
410
+ // CI doesn't run in an elderly runtime
411
+ } catch {
412
+ // These are from a previous version of node,
413
+ // see commit 76372607a6743cc75eae50ca58657c9e8a654428
414
+ // dated 2021-12-06
415
+ strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c\x7f-\x9f]/;
416
+ strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c\x7f-\x9f]/g;
417
+ strEscapeSequencesRegExpSingle = /[\x00-\x1f\x5c\x7f-\x9f]/;
418
+ strEscapeSequencesReplacerSingle = /[\x00-\x1f\x5c\x7f-\x9f]/g;
419
+ extractedSplitNewLines = value => {
420
+ const lines = RegExpPrototypeSymbolSplit(/\n/, value);
421
+ const last = ArrayPrototypePop(lines);
422
+ const nlLines = ArrayPrototypeMap(lines, line => line + "\n");
423
+ if (last !== "") {
424
+ nlLines.push(last);
425
+ }
426
+ return nlLines;
427
+ };
428
+ }
429
+
430
+ const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
431
+ const numberRegExp = /^(0|[1-9][0-9]*)$/;
432
+
433
+ const coreModuleRegExp = /^ {4}at (?:[^/\\(]+ \(|)node:(.+):\d+:\d+\)?$/;
434
+ const nodeModulesRegExp = /[/\\]node_modules[/\\](.+?)(?=[/\\])/g;
435
+
436
+ const classRegExp = /^(\s+[^(]*?)\s*{/;
437
+ const stripCommentsRegExp = /(\/\/.*?\n)|(\/\*(.|\n)*?\*\/)/g;
438
+
439
+ const kMinLineLength = 16;
440
+
441
+ // Constants to map the iterator state.
442
+ const kWeak = 0;
443
+ const kIterator = 1;
444
+ const kMapEntries = 2;
445
+
446
+ // Escaped control characters (plus the single quote and the backslash). Use
447
+ // empty strings to fill up unused entries.
448
+ const meta = [
449
+ "\\x00",
450
+ "\\x01",
451
+ "\\x02",
452
+ "\\x03",
453
+ "\\x04",
454
+ "\\x05",
455
+ "\\x06",
456
+ "\\x07", // x07
457
+ "\\b",
458
+ "\\t",
459
+ "\\n",
460
+ "\\x0B",
461
+ "\\f",
462
+ "\\r",
463
+ "\\x0E",
464
+ "\\x0F", // x0F
465
+ "\\x10",
466
+ "\\x11",
467
+ "\\x12",
468
+ "\\x13",
469
+ "\\x14",
470
+ "\\x15",
471
+ "\\x16",
472
+ "\\x17", // x17
473
+ "\\x18",
474
+ "\\x19",
475
+ "\\x1A",
476
+ "\\x1B",
477
+ "\\x1C",
478
+ "\\x1D",
479
+ "\\x1E",
480
+ "\\x1F", // x1F
481
+ "",
482
+ "",
483
+ "",
484
+ "",
485
+ "",
486
+ "",
487
+ "",
488
+ "\\'",
489
+ "",
490
+ "",
491
+ "",
492
+ "",
493
+ "",
494
+ "",
495
+ "",
496
+ "", // x2F
497
+ "",
498
+ "",
499
+ "",
500
+ "",
501
+ "",
502
+ "",
503
+ "",
504
+ "",
505
+ "",
506
+ "",
507
+ "",
508
+ "",
509
+ "",
510
+ "",
511
+ "",
512
+ "", // x3F
513
+ "",
514
+ "",
515
+ "",
516
+ "",
517
+ "",
518
+ "",
519
+ "",
520
+ "",
521
+ "",
522
+ "",
523
+ "",
524
+ "",
525
+ "",
526
+ "",
527
+ "",
528
+ "", // x4F
529
+ "",
530
+ "",
531
+ "",
532
+ "",
533
+ "",
534
+ "",
535
+ "",
536
+ "",
537
+ "",
538
+ "",
539
+ "",
540
+ "",
541
+ "\\\\",
542
+ "",
543
+ "",
544
+ "", // x5F
545
+ "",
546
+ "",
547
+ "",
548
+ "",
549
+ "",
550
+ "",
551
+ "",
552
+ "",
553
+ "",
554
+ "",
555
+ "",
556
+ "",
557
+ "",
558
+ "",
559
+ "",
560
+ "", // x6F
561
+ "",
562
+ "",
563
+ "",
564
+ "",
565
+ "",
566
+ "",
567
+ "",
568
+ "",
569
+ "",
570
+ "",
571
+ "",
572
+ "",
573
+ "",
574
+ "",
575
+ "",
576
+ "\\x7F", // x7F
577
+ "\\x80",
578
+ "\\x81",
579
+ "\\x82",
580
+ "\\x83",
581
+ "\\x84",
582
+ "\\x85",
583
+ "\\x86",
584
+ "\\x87", // x87
585
+ "\\x88",
586
+ "\\x89",
587
+ "\\x8A",
588
+ "\\x8B",
589
+ "\\x8C",
590
+ "\\x8D",
591
+ "\\x8E",
592
+ "\\x8F", // x8F
593
+ "\\x90",
594
+ "\\x91",
595
+ "\\x92",
596
+ "\\x93",
597
+ "\\x94",
598
+ "\\x95",
599
+ "\\x96",
600
+ "\\x97", // x97
601
+ "\\x98",
602
+ "\\x99",
603
+ "\\x9A",
604
+ "\\x9B",
605
+ "\\x9C",
606
+ "\\x9D",
607
+ "\\x9E",
608
+ "\\x9F", // x9F
609
+ ];
610
+
611
+ let getStringWidth;
612
+
613
+ function getUserOptions(ctx, isCrossContext) {
614
+ const ret = {
615
+ stylize: ctx.stylize,
616
+ showHidden: ctx.showHidden,
617
+ depth: ctx.depth,
618
+ colors: ctx.colors,
619
+ customInspect: ctx.customInspect,
620
+ showProxy: ctx.showProxy,
621
+ maxArrayLength: ctx.maxArrayLength,
622
+ maxStringLength: ctx.maxStringLength,
623
+ breakLength: ctx.breakLength,
624
+ compact: ctx.compact,
625
+ sorted: ctx.sorted,
626
+ getters: ctx.getters,
627
+ numericSeparator: ctx.numericSeparator,
628
+ ...ctx.userOptions,
629
+ };
630
+
631
+ // Typically, the target value will be an instance of `Object`. If that is
632
+ // *not* the case, the object may come from another vm.Context, and we want
633
+ // to avoid passing it objects from this Context in that case, so we remove
634
+ // the prototype from the returned object itself + the `stylize()` function,
635
+ // and remove all other non-primitives, including non-primitive user options.
636
+ if (isCrossContext) {
637
+ ObjectSetPrototypeOf(ret, null);
638
+ for (const key of ObjectKeys(ret)) {
639
+ if ((typeof ret[key] === "object" || typeof ret[key] === "function") && ret[key] !== null) {
640
+ delete ret[key];
641
+ }
642
+ }
643
+ ret.stylize = ObjectSetPrototypeOf((value, flavour) => {
644
+ let stylized;
645
+ try {
646
+ stylized = `${ctx.stylize(value, flavour)}`;
647
+ } catch {
648
+ // Continue regardless of error.
649
+ }
650
+
651
+ if (typeof stylized !== "string") return value;
652
+ // `stylized` is a string as it should be, which is safe to pass along.
653
+ return stylized;
654
+ }, null);
655
+ }
656
+
657
+ return ret;
658
+ }
659
+
660
+ /**
661
+ * Echos the value of any input. Tries to print the value out
662
+ * in the best way possible given the different types.
663
+ * @param {any} value The value to print out.
664
+ * @param {object} opts Optional options object that alters the output.
665
+ */
666
+ /* Legacy: value, showHidden, depth, colors */
667
+ function inspect(value, opts) {
668
+ // Default options
669
+ const ctx = {
670
+ budget: {},
671
+ indentationLvl: 0,
672
+ seen: [],
673
+ currentDepth: 0,
674
+ stylize: stylizeNoColor,
675
+ showHidden: inspectDefaultOptions.showHidden,
676
+ depth: inspectDefaultOptions.depth,
677
+ colors: inspectDefaultOptions.colors,
678
+ customInspect: inspectDefaultOptions.customInspect,
679
+ showProxy: inspectDefaultOptions.showProxy,
680
+ maxArrayLength: inspectDefaultOptions.maxArrayLength,
681
+ maxStringLength: inspectDefaultOptions.maxStringLength,
682
+ breakLength: inspectDefaultOptions.breakLength,
683
+ compact: inspectDefaultOptions.compact,
684
+ sorted: inspectDefaultOptions.sorted,
685
+ getters: inspectDefaultOptions.getters,
686
+ numericSeparator: inspectDefaultOptions.numericSeparator,
687
+ };
688
+ if (arguments.length > 1) {
689
+ // Legacy...
690
+ if (arguments.length > 2) {
691
+ if (arguments[2] !== undefined) {
692
+ ctx.depth = arguments[2];
693
+ }
694
+ if (arguments.length > 3 && arguments[3] !== undefined) {
695
+ ctx.colors = arguments[3];
696
+ }
697
+ }
698
+ // Set user-specified options
699
+ if (typeof opts === "boolean") {
700
+ ctx.showHidden = opts;
701
+ } else if (opts) {
702
+ const optKeys = ObjectKeys(opts);
703
+ for (let i = 0; i < optKeys.length; ++i) {
704
+ const key = optKeys[i];
705
+ // TODO(BridgeAR): Find a solution what to do about stylize. Either make
706
+ // this function public or add a new API with a similar or better functionality.
707
+ if (ObjectPrototypeHasOwnProperty(inspectDefaultOptions, key) || key === "stylize") {
708
+ ctx[key] = opts[key];
709
+ } else if (ctx.userOptions === undefined) {
710
+ // This is required to pass through the actual user input.
711
+ ctx.userOptions = opts;
712
+ }
713
+ }
714
+ }
715
+ }
716
+ if (ctx.colors) ctx.stylize = stylizeWithColor;
717
+ if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
718
+ if (ctx.maxStringLength === null) ctx.maxStringLength = Infinity;
719
+ return formatValue(ctx, value, 0);
720
+ }
721
+ inspect.custom = customInspectSymbol;
722
+ ObjectDefineProperty(inspect, "defaultOptions", {
723
+ // @ts-expect-error
724
+ __proto__: null,
725
+ get() {
726
+ return inspectDefaultOptions;
727
+ },
728
+ set(options) {
729
+ validateObject(options, "options");
730
+ return ObjectAssign(inspectDefaultOptions, options);
731
+ },
732
+ });
733
+ ObjectDefineProperty(inspect, "replDefaults", {
734
+ // @ts-expect-error
735
+ __proto__: null,
736
+ get() {
737
+ return inspectReplDefaults;
738
+ },
739
+ set(options) {
740
+ validateObject(options, "options");
741
+ return ObjectAssign(inspectReplDefaults, options);
742
+ },
743
+ });
744
+
745
+ // Set Graphics Rendition https://en.wikipedia.org/wiki/ANSI_escape_code#graphics
746
+ // Each color consists of an array with the color code as first entry and the
747
+ // reset code as second entry.
748
+ const defaultFG = 39;
749
+ const defaultBG = 49;
750
+ inspect.colors = {
751
+ __proto__: null,
752
+ reset: [0, 0],
753
+ bold: [1, 22],
754
+ dim: [2, 22], // Alias: faint
755
+ italic: [3, 23],
756
+ underline: [4, 24],
757
+ blink: [5, 25],
758
+ // Swap foreground and background colors
759
+ inverse: [7, 27], // Alias: swapcolors, swapColors
760
+ hidden: [8, 28], // Alias: conceal
761
+ strikethrough: [9, 29], // Alias: strikeThrough, crossedout, crossedOut
762
+ doubleunderline: [21, 24], // Alias: doubleUnderline
763
+ black: [30, defaultFG],
764
+ red: [31, defaultFG],
765
+ green: [32, defaultFG],
766
+ yellow: [33, defaultFG],
767
+ blue: [34, defaultFG],
768
+ magenta: [35, defaultFG],
769
+ cyan: [36, defaultFG],
770
+ white: [37, defaultFG],
771
+ bgBlack: [40, defaultBG],
772
+ bgRed: [41, defaultBG],
773
+ bgGreen: [42, defaultBG],
774
+ bgYellow: [43, defaultBG],
775
+ bgBlue: [44, defaultBG],
776
+ bgMagenta: [45, defaultBG],
777
+ bgCyan: [46, defaultBG],
778
+ bgWhite: [47, defaultBG],
779
+ framed: [51, 54],
780
+ overlined: [53, 55],
781
+ gray: [90, defaultFG], // Alias: grey, blackBright
782
+ redBright: [91, defaultFG],
783
+ greenBright: [92, defaultFG],
784
+ yellowBright: [93, defaultFG],
785
+ blueBright: [94, defaultFG],
786
+ magentaBright: [95, defaultFG],
787
+ cyanBright: [96, defaultFG],
788
+ whiteBright: [97, defaultFG],
789
+ bgGray: [100, defaultBG], // Alias: bgGrey, bgBlackBright
790
+ bgRedBright: [101, defaultBG],
791
+ bgGreenBright: [102, defaultBG],
792
+ bgYellowBright: [103, defaultBG],
793
+ bgBlueBright: [104, defaultBG],
794
+ bgMagentaBright: [105, defaultBG],
795
+ bgCyanBright: [106, defaultBG],
796
+ bgWhiteBright: [107, defaultBG],
797
+ };
798
+
799
+ function defineColorAlias(target, alias) {
800
+ ObjectDefineProperty(inspect.colors, alias, {
801
+ // @ts-expect-error
802
+ __proto__: null,
803
+ get() {
804
+ return this[target];
805
+ },
806
+ set(value) {
807
+ this[target] = value;
808
+ },
809
+ configurable: true,
810
+ enumerable: false,
811
+ });
812
+ }
813
+
814
+ defineColorAlias("gray", "grey");
815
+ defineColorAlias("gray", "blackBright");
816
+ defineColorAlias("bgGray", "bgGrey");
817
+ defineColorAlias("bgGray", "bgBlackBright");
818
+ defineColorAlias("dim", "faint");
819
+ defineColorAlias("strikethrough", "crossedout");
820
+ defineColorAlias("strikethrough", "strikeThrough");
821
+ defineColorAlias("strikethrough", "crossedOut");
822
+ defineColorAlias("hidden", "conceal");
823
+ defineColorAlias("inverse", "swapColors");
824
+ defineColorAlias("inverse", "swapcolors");
825
+ defineColorAlias("doubleunderline", "doubleUnderline");
826
+
827
+ // TODO(BridgeAR): Add function style support for more complex styles.
828
+ // Don't use 'blue' not visible on cmd.exe
829
+ inspect.styles = {
830
+ __proto__: null,
831
+ special: "cyan",
832
+ number: "yellow",
833
+ bigint: "yellow",
834
+ boolean: "yellow",
835
+ undefined: "grey",
836
+ null: "bold",
837
+ string: "green",
838
+ symbol: "green",
839
+ date: "magenta",
840
+ // "name": intentionally not styling
841
+ // TODO(BridgeAR): Highlight regular expressions properly.
842
+ regexp: "red",
843
+ module: "underline",
844
+ };
845
+
846
+ function addQuotes(str, quotes) {
847
+ if (quotes === -1) return `"${str}"`;
848
+ if (quotes === -2) return `\`${str}\``;
849
+ return `'${str}'`;
850
+ }
851
+
852
+ function escapeFn(str) {
853
+ const charCode = StringPrototypeCharCodeAt(str);
854
+ return meta.length > charCode ? meta[charCode] : `\\u${NumberPrototypeToString(charCode, 16)}`;
855
+ }
856
+
857
+ // Escape control characters, single quotes and the backslash.
858
+ // This is similar to JSON stringify escaping.
859
+ function strEscape(str) {
860
+ let escapeTest = strEscapeSequencesRegExp;
861
+ let escapeReplace = strEscapeSequencesReplacer;
862
+ let singleQuote = 39;
863
+
864
+ // Check for double quotes. If not present, do not escape single quotes and
865
+ // instead wrap the text in double quotes. If double quotes exist, check for
866
+ // backticks. If they do not exist, use those as fallback instead of the
867
+ // double quotes.
868
+ if (StringPrototypeIncludes(str, "'")) {
869
+ // This invalidates the charCode and therefore can not be matched for
870
+ // anymore.
871
+ if (!StringPrototypeIncludes(str, '"')) {
872
+ singleQuote = -1;
873
+ } else if (!StringPrototypeIncludes(str, "`") && !StringPrototypeIncludes(str, "${")) {
874
+ singleQuote = -2;
875
+ }
876
+ if (singleQuote !== 39) {
877
+ escapeTest = strEscapeSequencesRegExpSingle;
878
+ escapeReplace = strEscapeSequencesReplacerSingle;
879
+ }
880
+ }
881
+
882
+ // Some magic numbers that worked out fine while benchmarking with v8 6.0
883
+ if (str.length < 5000 && RegExpPrototypeExec(escapeTest, str) === null) return addQuotes(str, singleQuote);
884
+ if (str.length > 100) {
885
+ str = RegExpPrototypeSymbolReplace(escapeReplace, str, escapeFn);
886
+ return addQuotes(str, singleQuote);
887
+ }
888
+
889
+ let result = "";
890
+ let last = 0;
891
+ for (let i = 0; i < str.length; i++) {
892
+ const point = StringPrototypeCharCodeAt(str, i);
893
+ if (point === singleQuote || point === 92 || point < 32 || (point > 126 && point < 160)) {
894
+ if (last === i) {
895
+ result += meta[point];
896
+ } else {
897
+ result += `${StringPrototypeSlice(str, last, i)}${meta[point]}`;
898
+ }
899
+ last = i + 1;
900
+ } else if (point >= 0xd800 && point <= 0xdfff) {
901
+ if (point <= 0xdbff && i + 1 < str.length) {
902
+ const point = StringPrototypeCharCodeAt(str, i + 1);
903
+ if (point >= 0xdc00 && point <= 0xdfff) {
904
+ i++;
905
+ continue;
906
+ }
907
+ }
908
+ result += `${StringPrototypeSlice(str, last, i)}\\u${NumberPrototypeToString(point, 16)}`;
909
+ last = i + 1;
910
+ }
911
+ }
912
+
913
+ if (last !== str.length) {
914
+ result += StringPrototypeSlice(str, last);
915
+ }
916
+ return addQuotes(result, singleQuote);
917
+ }
918
+
919
+ function stylizeWithColor(str, styleType) {
920
+ const style = inspect.styles[styleType];
921
+ if (style !== undefined) {
922
+ const color = inspect.colors[style];
923
+ if (color !== undefined) return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
924
+ }
925
+ return str;
926
+ }
927
+
928
+ function stylizeNoColor(str) {
929
+ return str;
930
+ }
931
+
932
+ // Return a new empty array to push in the results of the default formatter.
933
+ function getEmptyFormatArray(ctx, value, recurseTimes) {
934
+ return /** @type any[] */([]);
935
+ }
936
+
937
+ function isInstanceof(object, proto) {
938
+ try {
939
+ return object instanceof proto;
940
+ } catch {
941
+ return false;
942
+ }
943
+ }
944
+
945
+ function getConstructorName(obj, ctx, recurseTimes, protoProps) {
946
+ let firstProto;
947
+ const tmp = obj;
948
+ while (obj || isUndetectableObject(obj)) {
949
+ const descriptor = ObjectGetOwnPropertyDescriptor(obj, "constructor");
950
+ if (
951
+ descriptor !== undefined &&
952
+ typeof descriptor.value === "function" &&
953
+ descriptor.value.name !== "" &&
954
+ isInstanceof(tmp, descriptor.value)
955
+ ) {
956
+ if (protoProps !== undefined && (firstProto !== obj || !builtInObjects.has(descriptor.value.name))) {
957
+ addPrototypeProperties(ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
958
+ }
959
+ return String(descriptor.value.name);
960
+ }
961
+
962
+ obj = ObjectGetPrototypeOf(obj);
963
+ if (firstProto === undefined) {
964
+ firstProto = obj;
965
+ }
966
+ }
967
+
968
+ if (firstProto === null) {
969
+ return null;
970
+ }
971
+
972
+ const res = internalGetConstructorName(tmp);
973
+
974
+ if (recurseTimes > ctx.depth && ctx.depth !== null) {
975
+ return `${res} <Complex prototype>`;
976
+ }
977
+
978
+ const protoConstr = getConstructorName(firstProto, ctx, recurseTimes + 1, protoProps);
979
+
980
+ if (protoConstr === null) {
981
+ return `${res} <${inspect(firstProto, {
982
+ ...ctx,
983
+ customInspect: false,
984
+ depth: -1,
985
+ })}>`;
986
+ }
987
+
988
+ return `${res} <${protoConstr}>`;
989
+ }
990
+
991
+ // This function has the side effect of adding prototype properties to the
992
+ // `output` argument (which is an array). This is intended to highlight user
993
+ // defined prototype properties.
994
+ function addPrototypeProperties(ctx, main, obj, recurseTimes, output) {
995
+ let depth = 0;
996
+ let keys;
997
+ let keySet;
998
+ do {
999
+ if (depth !== 0 || main === obj) {
1000
+ obj = ObjectGetPrototypeOf(obj);
1001
+ // Stop as soon as a null prototype is encountered.
1002
+ if (obj === null) {
1003
+ return;
1004
+ }
1005
+ // Stop as soon as a built-in object type is detected.
1006
+ const descriptor = ObjectGetOwnPropertyDescriptor(obj, "constructor");
1007
+ if (
1008
+ descriptor !== undefined &&
1009
+ typeof descriptor.value === "function" &&
1010
+ builtInObjects.has(descriptor.value.name)
1011
+ ) {
1012
+ return;
1013
+ }
1014
+ }
1015
+
1016
+ if (depth === 0) {
1017
+ keySet = new SafeSet();
1018
+ } else {
1019
+ ArrayPrototypeForEach(keys, key => keySet.add(key));
1020
+ }
1021
+ // Get all own property names and symbols.
1022
+ keys = ReflectOwnKeys(obj);
1023
+ ArrayPrototypePush(ctx.seen, main);
1024
+ for (const key of keys) {
1025
+ // Ignore the `constructor` property and keys that exist on layers above.
1026
+ if (key === "constructor" || ObjectPrototypeHasOwnProperty(main, key) || (depth !== 0 && keySet.has(key))) continue;
1027
+ const desc = ObjectGetOwnPropertyDescriptor(obj, key);
1028
+ if (typeof desc?.value === "function") continue;
1029
+ const value = formatProperty(ctx, obj, recurseTimes, key, kObjectType, desc, main);
1030
+ if (ctx.colors) ArrayPrototypePush(output, `\u001b[2m${value}\u001b[22m`); // Faint!
1031
+ else ArrayPrototypePush(output, value);
1032
+ }
1033
+ ArrayPrototypePop(ctx.seen);
1034
+ // Limit the inspection to up to three prototype layers. Using `recurseTimes`
1035
+ // is not a good choice here, because it's as if the properties are declared
1036
+ // on the current object from the users perspective.
1037
+ } while (++depth !== 3);
1038
+ }
1039
+
1040
+ function getPrefix(constructor, tag, fallback, size = "") {
1041
+ if (constructor === null) {
1042
+ if (tag !== "" && fallback !== tag) return `[${fallback}${size}: null prototype] [${tag}] `;
1043
+ else return `[${fallback}${size}: null prototype] `;
1044
+ }
1045
+ if (tag !== "" && constructor !== tag) return `${constructor}${size} [${tag}] `;
1046
+ else return `${constructor}${size} `;
1047
+ }
1048
+
1049
+ // Look up the keys of the object.
1050
+ function getKeys(value, showHidden) {
1051
+ let keys;
1052
+ const symbols = ObjectGetOwnPropertySymbols(value);
1053
+ if (showHidden) {
1054
+ keys = ObjectGetOwnPropertyNames(value);
1055
+ if (symbols.length !== 0) ArrayPrototypePushApply(keys, symbols);
1056
+ } else {
1057
+ // This might throw if `value` is a Module Namespace Object from an
1058
+ // unevaluated module, but we don't want to perform the actual type
1059
+ // check because it's expensive.
1060
+ // TODO(devsnek): track https://github.com/tc39/ecma262/issues/1209
1061
+ // and modify this logic as needed.
1062
+ try {
1063
+ keys = ObjectKeys(value);
1064
+ } catch (err) {
1065
+ assert(isNativeError(err) && err.name === "ReferenceError" && isModuleNamespaceObject(value));
1066
+ keys = ObjectGetOwnPropertyNames(value);
1067
+ }
1068
+ if (symbols.length !== 0) {
1069
+ const filter = key => ObjectPrototypePropertyIsEnumerable(value, key);
1070
+ ArrayPrototypePushApply(keys, ArrayPrototypeFilter(symbols, filter));
1071
+ }
1072
+ }
1073
+ return keys;
1074
+ }
1075
+
1076
+ function getCtxStyle(value, constructor, tag) {
1077
+ let fallback = "";
1078
+ if (constructor === null) {
1079
+ fallback = internalGetConstructorName(value);
1080
+ if (fallback === tag) fallback = "Object";
1081
+ }
1082
+ return getPrefix(constructor, tag, fallback);
1083
+ }
1084
+
1085
+ function formatProxy(ctx, proxy, recurseTimes) {
1086
+ if (recurseTimes > ctx.depth && ctx.depth !== null) return ctx.stylize("Proxy [Array]", "special");
1087
+ recurseTimes += 1;
1088
+ ctx.indentationLvl += 2;
1089
+ const res = [formatValue(ctx, proxy[0], recurseTimes), formatValue(ctx, proxy[1], recurseTimes)];
1090
+ ctx.indentationLvl -= 2;
1091
+ return reduceToSingleString(ctx, res, "", ["Proxy [", "]"], kArrayExtrasType, recurseTimes);
1092
+ }
1093
+
1094
+ // Note: using `formatValue` directly requires the indentation level to be
1095
+ // corrected by setting `ctx.indentationLvL += diff` and then to decrease the
1096
+ // value afterwards again.
1097
+ function formatValue(ctx, value, recurseTimes, typedArray) {
1098
+ // Primitive types cannot have properties.
1099
+ if (typeof value !== "object" && typeof value !== "function" && !isUndetectableObject(value)) {
1100
+ return formatPrimitive(ctx.stylize, value, ctx);
1101
+ }
1102
+ if (value === null) return ctx.stylize("null", "null");
1103
+
1104
+ // Memorize the context for custom inspection on proxies.
1105
+ const context = value;
1106
+ // Always check for proxies to prevent side effects and to prevent triggering any proxy handlers.
1107
+ const proxy = getProxyDetails(value, !!ctx.showProxy);
1108
+ if (proxy !== undefined) {
1109
+ if (proxy === null || proxy[0] === null) return ctx.stylize("<Revoked Proxy>", "special");
1110
+ if (ctx.showProxy) return formatProxy(ctx, proxy, recurseTimes);
1111
+ value = proxy;
1112
+ }
1113
+
1114
+ // Provide a hook for user-specified inspect functions.
1115
+ // Check that value is an object with an inspect function on it.
1116
+ if (ctx.customInspect) {
1117
+ const maybeCustom = value[customInspectSymbol];
1118
+ if (
1119
+ typeof maybeCustom === "function" &&
1120
+ // Filter out the util module, its inspect function is special.
1121
+ maybeCustom !== inspect &&
1122
+ // Also filter out any prototype objects using the circular check.
1123
+ !(value.constructor && value.constructor.prototype === value)
1124
+ ) {
1125
+ // This makes sure the recurseTimes are reported as before while using
1126
+ // a counter internally.
1127
+ const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
1128
+ const isCrossContext = proxy !== undefined || !(context instanceof Object);
1129
+ const ret = FunctionPrototypeCall(maybeCustom, context, depth, getUserOptions(ctx, isCrossContext), inspect);
1130
+ // If the custom inspection method returned `this`, don't go into infinite recursion.
1131
+ if (ret !== context) {
1132
+ if (typeof ret !== "string") return formatValue(ctx, ret, recurseTimes);
1133
+ return StringPrototypeReplaceAll(ret, "\n", `\n${StringPrototypeRepeat(" ", ctx.indentationLvl)}`);
1134
+ }
1135
+ }
1136
+ }
1137
+
1138
+ // Using an array here is actually better for the average case than using
1139
+ // a Set. `seen` will only check for the depth and will never grow too large.
1140
+ if (ctx.seen.includes(value)) {
1141
+ let index = 1;
1142
+ if (ctx.circular === undefined) {
1143
+ ctx.circular = new SafeMap();
1144
+ ctx.circular.set(value, index);
1145
+ } else {
1146
+ index = ctx.circular.get(value);
1147
+ if (index === undefined) {
1148
+ index = ctx.circular.size + 1;
1149
+ ctx.circular.set(value, index);
1150
+ }
1151
+ }
1152
+ return ctx.stylize(`[Circular *${index}]`, "special");
1153
+ }
1154
+
1155
+ return formatRaw(ctx, value, recurseTimes, typedArray);
1156
+ }
1157
+
1158
+ function formatRaw(ctx, value, recurseTimes, typedArray) {
1159
+ let keys = [];
1160
+ let protoProps;
1161
+ if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) protoProps = [];
1162
+
1163
+ const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
1164
+ // Reset the variable to check for this later on.
1165
+ if (protoProps !== undefined && protoProps.length === 0) protoProps = undefined;
1166
+
1167
+ let tag = value[SymbolToStringTag];
1168
+ // Only list the tag in case it's non-enumerable / not an own property. Otherwise we'd print this twice.
1169
+ if (
1170
+ typeof tag !== "string" || (tag !== "" &&
1171
+ (ctx.showHidden ? ObjectPrototypeHasOwnProperty : ObjectPrototypePropertyIsEnumerable)(value, SymbolToStringTag)
1172
+ )
1173
+ ) tag = "";
1174
+ let base = "";
1175
+ let formatter = getEmptyFormatArray;
1176
+ let braces = [];
1177
+ let noIterator = true;
1178
+ let i = 0;
1179
+ const filter = ctx.showHidden ? ALL_PROPERTIES : ONLY_ENUMERABLE;
1180
+
1181
+ let extrasType = kObjectType;
1182
+
1183
+ // Iterators and the rest are split to reduce checks.
1184
+ // We have to check all values in case the constructor is set to null.
1185
+ // Otherwise it would not possible to identify all types properly.
1186
+ if (SymbolIterator in value || constructor === null) {
1187
+ noIterator = false;
1188
+ if (ArrayIsArray(value)) {
1189
+ // Only set the constructor for non ordinary ("Array [...]") arrays.
1190
+ const prefix = constructor !== "Array" || tag !== "" ? getPrefix(constructor, tag, "Array", `(${value.length})`) : "";
1191
+ keys = getOwnNonIndexProperties(value, filter);
1192
+ braces = [`${prefix}[`, "]"];
1193
+ if (value.length === 0 && keys.length === 0 && protoProps === undefined) return `${braces[0]}]`;
1194
+ extrasType = kArrayExtrasType;
1195
+ formatter = formatArray;
1196
+ } else if (isSet(value)) {
1197
+ const size = SetPrototypeGetSize(value);
1198
+ const prefix = getPrefix(constructor, tag, "Set", `(${size})`);
1199
+ keys = getKeys(value, ctx.showHidden);
1200
+ formatter = constructor !== null
1201
+ ? FunctionPrototypeBind(formatSet, null, value)
1202
+ : FunctionPrototypeBind(formatSet, null, SetPrototypeValues(value));
1203
+ if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
1204
+ braces = [`${prefix}{`, "}"];
1205
+ } else if (isMap(value)) {
1206
+ const size = MapPrototypeGetSize(value);
1207
+ const prefix = getPrefix(constructor, tag, "Map", `(${size})`);
1208
+ keys = getKeys(value, ctx.showHidden);
1209
+ formatter = constructor !== null
1210
+ ? FunctionPrototypeBind(formatMap, null, value)
1211
+ : FunctionPrototypeBind(formatMap, null, MapPrototypeEntries(value));
1212
+ if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
1213
+ braces = [`${prefix}{`, "}"];
1214
+ } else if (isTypedArray(value)) {
1215
+ keys = getOwnNonIndexProperties(value, filter);
1216
+ let bound = value;
1217
+ let fallback = "";
1218
+ if (constructor === null) {
1219
+ fallback = TypedArrayPrototypeGetSymbolToStringTag(value);
1220
+ // Reconstruct the array information.
1221
+ bound = new primordials[fallback](value);
1222
+ }
1223
+ const size = TypedArrayPrototypeGetLength(value);
1224
+ const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
1225
+ braces = [`${prefix}[`, "]"];
1226
+ if (value.length === 0 && keys.length === 0 && !ctx.showHidden) return `${braces[0]}]`;
1227
+ // Special handle the value. The original value is required below. The
1228
+ // bound function is required to reconstruct missing information.
1229
+ formatter = FunctionPrototypeBind(formatTypedArray, null, bound, size);
1230
+ extrasType = kArrayExtrasType;
1231
+ } else if (isMapIterator(value)) {
1232
+ keys = getKeys(value, ctx.showHidden);
1233
+ braces = getIteratorBraces("Map", tag);
1234
+ // Add braces to the formatter parameters.
1235
+ formatter = FunctionPrototypeBind(formatIterator, null, braces);
1236
+ } else if (isSetIterator(value)) {
1237
+ keys = getKeys(value, ctx.showHidden);
1238
+ braces = getIteratorBraces("Set", tag);
1239
+ // Add braces to the formatter parameters.
1240
+ formatter = FunctionPrototypeBind(formatIterator, null, braces);
1241
+ } else {
1242
+ noIterator = true;
1243
+ }
1244
+ }
1245
+ if (noIterator) {
1246
+ keys = getKeys(value, ctx.showHidden);
1247
+ braces = ["{", "}"];
1248
+ if (constructor === "Object") {
1249
+ if (isArgumentsObject(value)) {
1250
+ braces[0] = "[Arguments] {";
1251
+ } else if (tag !== "") {
1252
+ braces[0] = `${getPrefix(constructor, tag, "Object")}{`;
1253
+ }
1254
+ if (keys.length === 0 && protoProps === undefined) {
1255
+ return `${braces[0]}}`;
1256
+ }
1257
+ } else if (typeof value === "function") {
1258
+ base = getFunctionBase(value, constructor, tag);
1259
+ if (keys.length === 0 && protoProps === undefined) return ctx.stylize(base, "special");
1260
+ } else if (isRegExp(value)) {
1261
+ // Make RegExps say that they are RegExps
1262
+ base = RegExpPrototypeToString(constructor !== null ? value : new RegExp(value));
1263
+ const prefix = getPrefix(constructor, tag, "RegExp");
1264
+ if (prefix !== "RegExp ") base = `${prefix}${base}`;
1265
+ if ((keys.length === 0 && protoProps === undefined) || (recurseTimes > ctx.depth && ctx.depth !== null)) {
1266
+ return ctx.stylize(base, "regexp");
1267
+ }
1268
+ } else if (isDate(value)) {
1269
+ // Make dates with properties first say the date
1270
+ base = NumberIsNaN(DatePrototypeGetTime(value)) ? DatePrototypeToString(value) : DatePrototypeToISOString(value);
1271
+ const prefix = getPrefix(constructor, tag, "Date");
1272
+ if (prefix !== "Date ") base = `${prefix}${base}`;
1273
+ if (keys.length === 0 && protoProps === undefined) {
1274
+ return ctx.stylize(base, "date");
1275
+ }
1276
+ } else if (value instanceof Error) {
1277
+ base = formatError(value, constructor, tag, ctx, keys);
1278
+ if (keys.length === 0 && protoProps === undefined) return base;
1279
+ } else if (isAnyArrayBuffer(value)) {
1280
+ // Fast path for ArrayBuffer and SharedArrayBuffer.
1281
+ // Can't do the same for DataView because it has a non-primitive
1282
+ // .buffer property that we need to recurse for.
1283
+ const arrayType = isArrayBuffer(value) ? "ArrayBuffer" : "SharedArrayBuffer";
1284
+ const prefix = getPrefix(constructor, tag, arrayType);
1285
+ if (typedArray === undefined) {
1286
+ formatter = formatArrayBuffer;
1287
+ } else if (keys.length === 0 && protoProps === undefined) {
1288
+ return prefix + `{ byteLength: ${formatNumber(ctx.stylize, value.byteLength, false)} }`;
1289
+ }
1290
+ braces[0] = `${prefix}{`;
1291
+ ArrayPrototypeUnshift(keys, "byteLength");
1292
+ } else if (isDataView(value)) {
1293
+ braces[0] = `${getPrefix(constructor, tag, "DataView")}{`;
1294
+ // .buffer goes last, it's not a primitive like the others.
1295
+ ArrayPrototypeUnshift(keys, "byteLength", "byteOffset", "buffer");
1296
+ } else if (isPromise(value)) {
1297
+ braces[0] = `${getPrefix(constructor, tag, "Promise")}{`;
1298
+ formatter = formatPromise;
1299
+ } else if (isWeakSet(value)) {
1300
+ braces[0] = `${getPrefix(constructor, tag, "WeakSet")}{`;
1301
+ formatter = ctx.showHidden ? formatWeakSet : formatWeakCollection;
1302
+ } else if (isWeakMap(value)) {
1303
+ braces[0] = `${getPrefix(constructor, tag, "WeakMap")}{`;
1304
+ formatter = ctx.showHidden ? formatWeakMap : formatWeakCollection;
1305
+ } else if (isModuleNamespaceObject(value)) {
1306
+ braces[0] = `${getPrefix(constructor, tag, "Module")}{`;
1307
+ // Special handle keys for namespace objects.
1308
+ formatter = formatNamespaceObject.bind(null, keys);
1309
+ } else if (isBoxedPrimitive(value)) {
1310
+ base = getBoxedBase(value, ctx, keys, constructor, tag);
1311
+ if (keys.length === 0 && protoProps === undefined) {
1312
+ return base;
1313
+ }
1314
+ } else {
1315
+ if (keys.length === 0 && protoProps === undefined) {
1316
+ if (isExternal(value)) {
1317
+ const address = "0"; //getExternalValue(value).toString(16);
1318
+ return ctx.stylize(`[External: ${address}]`, "special");
1319
+ }
1320
+ return `${getCtxStyle(value, constructor, tag)}{}`;
1321
+ }
1322
+ braces[0] = `${getCtxStyle(value, constructor, tag)}{`;
1323
+ }
1324
+ }
1325
+
1326
+ if (recurseTimes > ctx.depth && ctx.depth !== null) {
1327
+ let constructorName = StringPrototypeSlice(getCtxStyle(value, constructor, tag), 0, -1);
1328
+ if (constructor !== null) constructorName = `[${constructorName}]`;
1329
+ return ctx.stylize(constructorName, "special");
1330
+ }
1331
+ recurseTimes += 1;
1332
+
1333
+ ctx.seen.push(value);
1334
+ ctx.currentDepth = recurseTimes;
1335
+ let output;
1336
+ const indentationLvl = ctx.indentationLvl;
1337
+ try {
1338
+ // JSC stack is too powerful it must be stopped manually
1339
+ if (ctx.currentDepth > 1000) throw new RangeError(ERROR_STACK_OVERFLOW_MSG);
1340
+ output = formatter(ctx, value, recurseTimes);
1341
+ for (i = 0; i < keys.length; i++) {
1342
+ ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, keys[i], extrasType));
1343
+ }
1344
+ if (protoProps !== undefined) {
1345
+ ArrayPrototypePushApply(output, protoProps);
1346
+ }
1347
+ } catch (err) {
1348
+ if (err instanceof RangeError && err.message === ERROR_STACK_OVERFLOW_MSG) {
1349
+ const constructorName = StringPrototypeSlice(getCtxStyle(value, constructor, tag), 0, -1);
1350
+ ctx.seen.pop();
1351
+ ctx.indentationLvl = indentationLvl;
1352
+ return ctx.stylize(
1353
+ `[${constructorName}: Inspection interrupted prematurely. Maximum call stack size exceeded.]`,
1354
+ "special",
1355
+ );
1356
+ }
1357
+ throw new AssertionError("handleMaxCallStackSize assertion failed: " + String(err), true);
1358
+ }
1359
+ if (ctx.circular !== undefined) {
1360
+ const index = ctx.circular.get(value);
1361
+ if (index !== undefined) {
1362
+ ctx.seenRefs ??= new Set();
1363
+ const SEEN = ctx.seenRefs.has(index);
1364
+ if (!SEEN) {
1365
+ ctx.seenRefs.add(index);
1366
+ const reference = ctx.stylize(`<ref *${index}>`, "special");
1367
+ // Add reference always to the very beginning of the output.
1368
+ if (ctx.compact !== true) {
1369
+ base = base === "" ? reference : `${reference} ${base}`;
1370
+ } else {
1371
+ braces[0] = `${reference} ${braces[0]}`;
1372
+ }
1373
+ } else {
1374
+ //! this is a non-standard behavior compared to Node's implementation
1375
+ // it optimizes the output by also collapsing indirect circular references
1376
+ // this is not known to cause any issues so far but this note is left here just in case
1377
+ const reference = ctx.stylize(`[Circular *${index}]`, "special");
1378
+ //ctx.seen.pop(); //? uncommenting this line would allow more accurate display semantics but causes a ~2x slowdown
1379
+ return reference;
1380
+ }
1381
+ }
1382
+ }
1383
+ ctx.seen.pop();
1384
+
1385
+ if (ctx.sorted) {
1386
+ const comparator = ctx.sorted === true ? undefined : ctx.sorted;
1387
+ if (extrasType === kObjectType) {
1388
+ ArrayPrototypeSort(output, comparator);
1389
+ } else if (keys.length > 1) {
1390
+ const sorted = ArrayPrototypeSort(ArrayPrototypeSlice(output, output.length - keys.length), comparator);
1391
+ ArrayPrototypeUnshift(sorted, output, output.length - keys.length, keys.length);
1392
+ ReflectApply(ArrayPrototypeSplice, null, sorted);
1393
+ }
1394
+ }
1395
+
1396
+ const res = reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value);
1397
+ const budget = ctx.budget[ctx.indentationLvl] || 0;
1398
+ const newLength = budget + res.length;
1399
+ ctx.budget[ctx.indentationLvl] = newLength;
1400
+ // If any indentationLvl exceeds this limit, limit further inspecting to the
1401
+ // minimum. Otherwise the recursive algorithm might continue inspecting the
1402
+ // object even though the maximum string size (~2 ** 28 on 32 bit systems and
1403
+ // ~2 ** 30 on 64 bit systems) exceeded. The actual output is not limited at
1404
+ // exactly 2 ** 27 but a bit higher. This depends on the object shape.
1405
+ // This limit also makes sure that huge objects don't block the event loop
1406
+ // significantly.
1407
+ if (newLength > 2 ** 27) {
1408
+ ctx.depth = -1;
1409
+ }
1410
+ return res;
1411
+ }
1412
+
1413
+ function getIteratorBraces(type, tag) {
1414
+ if (tag !== `${type} Iterator`) {
1415
+ if (tag !== "") tag += "] [";
1416
+ tag += `${type} Iterator`;
1417
+ }
1418
+ return [`[${tag}] {`, "}"];
1419
+ }
1420
+
1421
+ function getBoxedBase(value, ctx, keys, constructor, tag) {
1422
+ let fn;
1423
+ let type;
1424
+ if (isNumberObject(value)) {
1425
+ fn = NumberPrototypeValueOf;
1426
+ type = "Number";
1427
+ } else if (isStringObject(value)) {
1428
+ fn = StringPrototypeValueOf;
1429
+ type = "String";
1430
+ // For boxed Strings, we have to remove the 0-n indexed entries,
1431
+ // since they just noisy up the output and are redundant
1432
+ // Make boxed primitive Strings look like such
1433
+ keys.splice(0, value.length);
1434
+ } else if (isBooleanObject(value)) {
1435
+ fn = BooleanPrototypeValueOf;
1436
+ type = "Boolean";
1437
+ } else if (isBigIntObject(value)) {
1438
+ fn = BigIntPrototypeValueOf;
1439
+ type = "BigInt";
1440
+ } else {
1441
+ fn = SymbolPrototypeValueOf;
1442
+ type = "Symbol";
1443
+ }
1444
+ let base = `[${type}`;
1445
+ if (type !== constructor) {
1446
+ if (constructor === null) {
1447
+ base += " (null prototype)";
1448
+ } else {
1449
+ base += ` (${constructor})`;
1450
+ }
1451
+ }
1452
+ base += `: ${formatPrimitive(stylizeNoColor, fn(value), ctx)}]`;
1453
+ if (tag !== "" && tag !== constructor) {
1454
+ base += ` [${tag}]`;
1455
+ }
1456
+ if (keys.length !== 0 || ctx.stylize === stylizeNoColor) return base;
1457
+ return ctx.stylize(base, StringPrototypeToLowerCase(type));
1458
+ }
1459
+
1460
+ function getClassBase(value, constructor, tag) {
1461
+ const hasName = ObjectPrototypeHasOwnProperty(value, "name");
1462
+ const name = (hasName && value.name) || "(anonymous)";
1463
+ let base = `class ${name}`;
1464
+ if (constructor !== "Function" && constructor !== null) {
1465
+ base += ` [${constructor}]`;
1466
+ }
1467
+ if (tag !== "" && constructor !== tag) {
1468
+ base += ` [${tag}]`;
1469
+ }
1470
+ if (constructor !== null) {
1471
+ const superName = ObjectGetPrototypeOf(value).name;
1472
+ if (superName) {
1473
+ base += ` extends ${superName}`;
1474
+ }
1475
+ } else {
1476
+ base += " extends [null prototype]";
1477
+ }
1478
+ return `[${base}]`;
1479
+ }
1480
+
1481
+ function getFunctionBase(value, constructor, tag) {
1482
+ const stringified = FunctionPrototypeToString(value);
1483
+ if (StringPrototypeStartsWith(stringified, "class") && StringPrototypeEndsWith(stringified, "}")) {
1484
+ const slice = StringPrototypeSlice(stringified, 5, -1);
1485
+ const bracketIndex = StringPrototypeIndexOf(slice, "{");
1486
+ if (
1487
+ bracketIndex !== -1 &&
1488
+ (!StringPrototypeIncludes(StringPrototypeSlice(slice, 0, bracketIndex), "(") ||
1489
+ // Slow path to guarantee that it's indeed a class.
1490
+ RegExpPrototypeExec(classRegExp, RegExpPrototypeSymbolReplace(stripCommentsRegExp, slice)) !== null)
1491
+ ) {
1492
+ return getClassBase(value, constructor, tag);
1493
+ }
1494
+ }
1495
+ let type = "Function";
1496
+ if (isGeneratorFunction(value)) {
1497
+ type = `Generator${type}`;
1498
+ }
1499
+ if (isAsyncFunction(value)) {
1500
+ type = `Async${type}`;
1501
+ }
1502
+ let base = `[${type}`;
1503
+ if (constructor === null) {
1504
+ base += " (null prototype)";
1505
+ }
1506
+ if (value.name === "") {
1507
+ base += " (anonymous)";
1508
+ } else {
1509
+ base += `: ${value.name}`;
1510
+ }
1511
+ base += "]";
1512
+ if (constructor !== type && constructor !== null) {
1513
+ base += ` ${constructor}`;
1514
+ }
1515
+ if (tag !== "" && constructor !== tag) {
1516
+ base += ` [${tag}]`;
1517
+ }
1518
+ return base;
1519
+ }
1520
+
1521
+ function identicalSequenceRange(a, b) {
1522
+ for (let i = 0; i < a.length - 3; i++) {
1523
+ // Find the first entry of b that matches the current entry of a.
1524
+ const pos = b.indexOf(a[i]);
1525
+ if (pos !== -1) {
1526
+ const rest = b.length - pos;
1527
+ if (rest > 3) {
1528
+ let len = 1;
1529
+ const maxLen = MathMin(a.length - i, rest);
1530
+ // Count the number of consecutive entries.
1531
+ while (maxLen > len && a[i + len] === b[pos + len]) {
1532
+ len++;
1533
+ }
1534
+ if (len > 3) {
1535
+ return { len, offset: i };
1536
+ }
1537
+ }
1538
+ }
1539
+ }
1540
+
1541
+ return { len: 0, offset: 0 };
1542
+ }
1543
+
1544
+ function getStackString(error) {
1545
+ return error.stack ? String(error.stack) : ErrorPrototypeToString(error);
1546
+ }
1547
+
1548
+ function getStackFrames(ctx, err, stack) {
1549
+ const frames = StringPrototypeSplit(stack, "\n");
1550
+
1551
+ let cause;
1552
+ try {
1553
+ ({ cause } = err);
1554
+ } catch {
1555
+ // If 'cause' is a getter that throws, ignore it.
1556
+ }
1557
+
1558
+ // Remove stack frames identical to frames in cause.
1559
+ if (cause != null && cause instanceof Error) {
1560
+ const causeStack = getStackString(cause);
1561
+ const causeStackStart = StringPrototypeIndexOf(causeStack, "\n at");
1562
+ if (causeStackStart !== -1) {
1563
+ const causeFrames = StringPrototypeSplit(StringPrototypeSlice(causeStack, causeStackStart + 1), "\n");
1564
+ const { len, offset } = identicalSequenceRange(frames, causeFrames);
1565
+ if (len > 0) {
1566
+ const skipped = len - 2;
1567
+ const msg = ` ... ${skipped} lines matching cause stack trace ...`;
1568
+ frames.splice(offset + 1, skipped, ctx.stylize(msg, "undefined"));
1569
+ }
1570
+ }
1571
+ }
1572
+ return frames;
1573
+ }
1574
+
1575
+ function improveStack(stack, constructor, name, tag) {
1576
+ // A stack trace may contain arbitrary data. Only manipulate the output
1577
+ // for "regular errors" (errors that "look normal") for now.
1578
+ let len = name.length;
1579
+
1580
+ if (
1581
+ constructor === null ||
1582
+ (StringPrototypeEndsWith(name, "Error") &&
1583
+ StringPrototypeStartsWith(stack, name) &&
1584
+ (stack.length === len || stack[len] === ":" || stack[len] === "\n"))
1585
+ ) {
1586
+ let fallback = "Error";
1587
+ if (constructor === null) {
1588
+ const start =
1589
+ RegExpPrototypeExec(/^([A-Z][a-z_ A-Z0-9[\]()-]+)(?::|\n {4}at)/, stack) ||
1590
+ RegExpPrototypeExec(/^([a-z_A-Z0-9-]*Error)$/, stack);
1591
+ fallback = (start && start[1]) || "";
1592
+ len = fallback.length;
1593
+ fallback = fallback || "Error";
1594
+ }
1595
+ const prefix = StringPrototypeSlice(getPrefix(constructor, tag, fallback), 0, -1);
1596
+ if (name !== prefix) {
1597
+ if (StringPrototypeIncludes(prefix, name)) {
1598
+ if (len === 0) {
1599
+ stack = `${prefix}: ${stack}`;
1600
+ } else {
1601
+ stack = `${prefix}${StringPrototypeSlice(stack, len)}`;
1602
+ }
1603
+ } else {
1604
+ stack = `${prefix} [${name}]${StringPrototypeSlice(stack, len)}`;
1605
+ }
1606
+ }
1607
+ }
1608
+ return stack;
1609
+ }
1610
+
1611
+ function removeDuplicateErrorKeys(ctx, keys, err, stack) {
1612
+ if (!ctx.showHidden && keys.length !== 0) {
1613
+ for (const name of ["name", "message", "stack"]) {
1614
+ const index = ArrayPrototypeIndexOf(keys, name);
1615
+ // Only hide the property in case it's part of the original stack
1616
+ if (index !== -1 && StringPrototypeIncludes(stack, err[name])) {
1617
+ ArrayPrototypeSplice(keys, index, 1);
1618
+ }
1619
+ }
1620
+ }
1621
+ }
1622
+
1623
+ function markNodeModules(ctx, line) {
1624
+ let tempLine = "";
1625
+ let nodeModule;
1626
+ let pos = 0;
1627
+ while ((nodeModule = nodeModulesRegExp.exec(line)) !== null) {
1628
+ // '/node_modules/'.length === 14
1629
+ tempLine += StringPrototypeSlice(line, pos, nodeModule.index + 14);
1630
+ tempLine += ctx.stylize(nodeModule[1], "module");
1631
+ pos = nodeModule.index + nodeModule[0].length;
1632
+ }
1633
+ if (pos !== 0) {
1634
+ line = tempLine + StringPrototypeSlice(line, pos);
1635
+ }
1636
+ return line;
1637
+ }
1638
+
1639
+ function markCwd(ctx, line, workingDirectory) {
1640
+ let cwdStartPos = StringPrototypeIndexOf(line, workingDirectory);
1641
+ let tempLine = "";
1642
+ let cwdLength = workingDirectory.length;
1643
+ if (cwdStartPos !== -1) {
1644
+ if (StringPrototypeSlice(line, cwdStartPos - 7, cwdStartPos) === "file://") {
1645
+ cwdLength += 7;
1646
+ cwdStartPos -= 7;
1647
+ }
1648
+ const start = line[cwdStartPos - 1] === "(" ? cwdStartPos - 1 : cwdStartPos;
1649
+ const end = start !== cwdStartPos && StringPrototypeEndsWith(line, ")") ? -1 : line.length;
1650
+ const workingDirectoryEndPos = cwdStartPos + cwdLength + 1;
1651
+ const cwdSlice = StringPrototypeSlice(line, start, workingDirectoryEndPos);
1652
+
1653
+ tempLine += StringPrototypeSlice(line, 0, start);
1654
+ tempLine += ctx.stylize(cwdSlice, "undefined");
1655
+ tempLine += StringPrototypeSlice(line, workingDirectoryEndPos, end);
1656
+ if (end === -1) {
1657
+ tempLine += ctx.stylize(")", "undefined");
1658
+ }
1659
+ } else {
1660
+ tempLine += line;
1661
+ }
1662
+ return tempLine;
1663
+ }
1664
+
1665
+ function safeGetCWD() {
1666
+ let workingDirectory;
1667
+ try {
1668
+ workingDirectory = process.cwd();
1669
+ } catch {
1670
+ return;
1671
+ }
1672
+ return workingDirectory;
1673
+ }
1674
+
1675
+ function formatError(err, constructor, tag, ctx, keys) {
1676
+ const name = err.name != null ? String(err.name) : "Error";
1677
+ let stack = getStackString(err);
1678
+
1679
+ //! temp fix for Bun losing the error name from inherited errors + extraneous ": " with no message
1680
+ stack = stack.replace(/^Error: /, `${name}${err.message ? ": " : ""}`);
1681
+
1682
+ removeDuplicateErrorKeys(ctx, keys, err, stack);
1683
+
1684
+ if ("cause" in err && (keys.length === 0 || !ArrayPrototypeIncludes(keys, "cause"))) {
1685
+ ArrayPrototypePush(keys, "cause");
1686
+ }
1687
+
1688
+ // Print errors aggregated into AggregateError
1689
+ if (ArrayIsArray(err.errors) && (keys.length === 0 || !ArrayPrototypeIncludes(keys, "errors"))) {
1690
+ ArrayPrototypePush(keys, "errors");
1691
+ }
1692
+
1693
+ stack = improveStack(stack, constructor, name, tag);
1694
+
1695
+ // Ignore the error message if it's contained in the stack.
1696
+ let pos = (err.message && StringPrototypeIndexOf(stack, err.message)) || -1;
1697
+ if (pos !== -1) pos += err.message.length;
1698
+ // Wrap the error in brackets in case it has no stack trace.
1699
+ const stackStart = StringPrototypeIndexOf(stack, "\n at", pos);
1700
+ if (stackStart === -1) {
1701
+ stack = `[${stack}]`;
1702
+ } else {
1703
+ let newStack = StringPrototypeSlice(stack, 0, stackStart);
1704
+ const stackFramePart = StringPrototypeSlice(stack, stackStart + 1);
1705
+ const lines = getStackFrames(ctx, err, stackFramePart);
1706
+ if (ctx.colors) {
1707
+ // Highlight userland code and node modules.
1708
+ const workingDirectory = safeGetCWD();
1709
+ let esmWorkingDirectory;
1710
+ for (let line of lines) {
1711
+ const core = RegExpPrototypeExec(coreModuleRegExp, line);
1712
+ if (
1713
+ core !== null &&
1714
+ (StringPrototypeStartsWith(core[1], "internal/") ||
1715
+ ArrayPrototypeIncludes(require("node:module").builtinModules, core[1]))
1716
+ ) {
1717
+ newStack += `\n${ctx.stylize(line, "undefined")}`;
1718
+ } else {
1719
+ newStack += "\n";
1720
+
1721
+ line = markNodeModules(ctx, line);
1722
+ if (workingDirectory !== undefined) {
1723
+ let newLine = markCwd(ctx, line, workingDirectory);
1724
+ if (newLine === line) {
1725
+ esmWorkingDirectory ??= pathToFileURL(workingDirectory);
1726
+ newLine = markCwd(ctx, line, esmWorkingDirectory);
1727
+ }
1728
+ line = newLine;
1729
+ }
1730
+
1731
+ newStack += line;
1732
+ }
1733
+ }
1734
+ } else {
1735
+ newStack += `\n${ArrayPrototypeJoin(lines, "\n")}`;
1736
+ }
1737
+ stack = newStack;
1738
+ }
1739
+ // The message and the stack have to be indented as well!
1740
+ if (ctx.indentationLvl !== 0) {
1741
+ const indentation = StringPrototypeRepeat(" ", ctx.indentationLvl);
1742
+ stack = StringPrototypeReplaceAll(stack, "\n", `\n${indentation}`);
1743
+ }
1744
+ return stack;
1745
+ }
1746
+
1747
+ function groupArrayElements(ctx, output, value) {
1748
+ let totalLength = 0;
1749
+ let maxLength = 0;
1750
+ let i = 0;
1751
+ let outputLength = output.length;
1752
+ if (ctx.maxArrayLength < output.length) {
1753
+ // This makes sure the "... n more items" part is not taken into account.
1754
+ outputLength--;
1755
+ }
1756
+ const separatorSpace = 2; // Add 1 for the space and 1 for the separator.
1757
+ const dataLen = new Array(outputLength);
1758
+ // Calculate the total length of all output entries and the individual max
1759
+ // entries length of all output entries. We have to remove colors first,
1760
+ // otherwise the length would not be calculated properly.
1761
+ for (; i < outputLength; i++) {
1762
+ const len = getStringWidth(output[i], ctx.colors);
1763
+ dataLen[i] = len;
1764
+ totalLength += len + separatorSpace;
1765
+ if (maxLength < len) maxLength = len;
1766
+ }
1767
+ // Add two to `maxLength` as we add a single whitespace character plus a comma
1768
+ // in-between two entries.
1769
+ const actualMax = maxLength + separatorSpace;
1770
+ // Check if at least three entries fit next to each other and prevent grouping
1771
+ // of arrays that contains entries of very different length (i.e., if a single
1772
+ // entry is longer than 1/5 of all other entries combined). Otherwise the
1773
+ // space in-between small entries would be enormous.
1774
+ if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength && (totalLength / actualMax > 5 || maxLength <= 6)) {
1775
+ const approxCharHeights = 2.5;
1776
+ const averageBias = MathSqrt(actualMax - totalLength / output.length);
1777
+ const biasedMax = MathMax(actualMax - 3 - averageBias, 1);
1778
+ // Dynamically check how many columns seem possible.
1779
+ const columns = MathMin(
1780
+ // Ideally a square should be drawn. We expect a character to be about 2.5
1781
+ // times as high as wide. This is the area formula to calculate a square
1782
+ // which contains n rectangles of size `actualMax * approxCharHeights`.
1783
+ // Divide that by `actualMax` to receive the correct number of columns.
1784
+ // The added bias increases the columns for short entries.
1785
+ MathRound(MathSqrt(approxCharHeights * biasedMax * outputLength) / biasedMax),
1786
+ // Do not exceed the breakLength.
1787
+ MathFloor((ctx.breakLength - ctx.indentationLvl) / actualMax),
1788
+ // Limit array grouping for small `compact` modes as the user requested
1789
+ // minimal grouping.
1790
+ ctx.compact * 4,
1791
+ // Limit the columns to a maximum of fifteen.
1792
+ 15,
1793
+ );
1794
+ // Return with the original output if no grouping should happen.
1795
+ if (columns <= 1) {
1796
+ return output;
1797
+ }
1798
+ const tmp = [];
1799
+ const maxLineLength = [];
1800
+ for (let i = 0; i < columns; i++) {
1801
+ let lineMaxLength = 0;
1802
+ for (let j = i; j < output.length; j += columns) {
1803
+ if (dataLen[j] > lineMaxLength) lineMaxLength = dataLen[j];
1804
+ }
1805
+ lineMaxLength += separatorSpace;
1806
+ maxLineLength[i] = lineMaxLength;
1807
+ }
1808
+ let order = StringPrototypePadStart;
1809
+ if (value !== undefined) {
1810
+ for (let i = 0; i < output.length; i++) {
1811
+ if (typeof value[i] !== "number" && typeof value[i] !== "bigint") {
1812
+ order = StringPrototypePadEnd;
1813
+ break;
1814
+ }
1815
+ }
1816
+ }
1817
+ // Each iteration creates a single line of grouped entries.
1818
+ for (let i = 0; i < outputLength; i += columns) {
1819
+ // The last lines may contain less entries than columns.
1820
+ const max = MathMin(i + columns, outputLength);
1821
+ let str = "";
1822
+ let j = i;
1823
+ for (; j < max - 1; j++) {
1824
+ // Calculate extra color padding in case it's active. This has to be
1825
+ // done line by line as some lines might contain more colors than
1826
+ // others.
1827
+ const padding = maxLineLength[j - i] + output[j].length - dataLen[j];
1828
+ str += order(`${output[j]}, `, padding, " ");
1829
+ }
1830
+ if (order === StringPrototypePadStart) {
1831
+ const padding = maxLineLength[j - i] + output[j].length - dataLen[j] - separatorSpace;
1832
+ str += StringPrototypePadStart(output[j], padding, " ");
1833
+ } else {
1834
+ str += output[j];
1835
+ }
1836
+ ArrayPrototypePush(tmp, str);
1837
+ }
1838
+ if (ctx.maxArrayLength < output.length) {
1839
+ ArrayPrototypePush(tmp, output[outputLength]);
1840
+ }
1841
+ output = tmp;
1842
+ }
1843
+ return output;
1844
+ }
1845
+
1846
+ function addNumericSeparator(integerString) {
1847
+ let result = "";
1848
+ let i = integerString.length;
1849
+ const start = StringPrototypeStartsWith(integerString, "-") ? 1 : 0;
1850
+ for (; i >= start + 4; i -= 3) {
1851
+ result = `_${StringPrototypeSlice(integerString, i - 3, i)}${result}`;
1852
+ }
1853
+ return i === integerString.length ? integerString : `${StringPrototypeSlice(integerString, 0, i)}${result}`;
1854
+ }
1855
+
1856
+ function addNumericSeparatorEnd(integerString) {
1857
+ let result = "";
1858
+ let i = 0;
1859
+ for (; i < integerString.length - 3; i += 3) {
1860
+ result += `${StringPrototypeSlice(integerString, i, i + 3)}_`;
1861
+ }
1862
+ return i === 0 ? integerString : `${result}${StringPrototypeSlice(integerString, i)}`;
1863
+ }
1864
+
1865
+ const remainingText = remaining => `... ${remaining} more item${remaining > 1 ? "s" : ""}`;
1866
+
1867
+ function formatNumber(fn, number, numericSeparator) {
1868
+ if (!numericSeparator) {
1869
+ // Format -0 as '-0'. Checking `number === -0` won't distinguish 0 from -0.
1870
+ if (ObjectIs(number, -0)) {
1871
+ return fn("-0", "number");
1872
+ }
1873
+ return fn(`${number}`, "number");
1874
+ }
1875
+ const integer = MathTrunc(number);
1876
+ const string = String(integer);
1877
+ if (integer === number) {
1878
+ if (!NumberIsFinite(number) || StringPrototypeIncludes(string, "e")) {
1879
+ return fn(string, "number");
1880
+ }
1881
+ return fn(`${addNumericSeparator(string)}`, "number");
1882
+ }
1883
+ if (NumberIsNaN(number)) {
1884
+ return fn(string, "number");
1885
+ }
1886
+ return fn(
1887
+ `${addNumericSeparator(string)}.${addNumericSeparatorEnd(StringPrototypeSlice(String(number), string.length + 1))}`,
1888
+ "number",
1889
+ );
1890
+ }
1891
+
1892
+ function formatBigInt(fn, bigint, numericSeparator) {
1893
+ const string = String(bigint);
1894
+ if (!numericSeparator) {
1895
+ return fn(`${string}n`, "bigint");
1896
+ }
1897
+ return fn(`${addNumericSeparator(string)}n`, "bigint");
1898
+ }
1899
+
1900
+ function formatPrimitive(fn, value, ctx) {
1901
+ if (typeof value === "string") {
1902
+ let trailer = "";
1903
+ if (value.length > ctx.maxStringLength) {
1904
+ const remaining = value.length - ctx.maxStringLength;
1905
+ value = StringPrototypeSlice(value, 0, ctx.maxStringLength);
1906
+ trailer = `... ${remaining} more character${remaining > 1 ? "s" : ""}`;
1907
+ }
1908
+ if (
1909
+ ctx.compact !== true &&
1910
+ // We do not support handling unicode characters width with
1911
+ // the readline getStringWidth function as there are performance implications.
1912
+ value.length > kMinLineLength &&
1913
+ value.length > ctx.breakLength - ctx.indentationLvl - 4
1914
+ ) {
1915
+ return (
1916
+ ArrayPrototypeJoin(
1917
+ ArrayPrototypeMap(extractedSplitNewLines(value), line => fn(strEscape(line), "string")),
1918
+ ` +\n${StringPrototypeRepeat(" ", ctx.indentationLvl + 2)}`,
1919
+ ) + trailer
1920
+ );
1921
+ }
1922
+ return fn(strEscape(value), "string") + trailer;
1923
+ }
1924
+ if (typeof value === "number") return formatNumber(fn, value, ctx.numericSeparator);
1925
+ if (typeof value === "bigint") return formatBigInt(fn, value, ctx.numericSeparator);
1926
+ if (typeof value === "boolean") return fn(`${value}`, "boolean");
1927
+ if (typeof value === "undefined") return fn("undefined", "undefined");
1928
+ // es6 symbol primitive
1929
+ return fn(SymbolPrototypeToString(value), "symbol");
1930
+ }
1931
+
1932
+ function formatNamespaceObject(keys, ctx, value, recurseTimes) {
1933
+ const output = new Array(keys.length);
1934
+ for (let i = 0; i < keys.length; i++) {
1935
+ try {
1936
+ output[i] = formatProperty(ctx, value, recurseTimes, keys[i], kObjectType);
1937
+ } catch (err) {
1938
+ assert(isNativeError(err) && err.name === "ReferenceError");
1939
+ // Use the existing functionality. This makes sure the indentation and
1940
+ // line breaks are always correct. Otherwise it is very difficult to keep
1941
+ // this aligned, even though this is a hacky way of dealing with this.
1942
+ const tmp = { [keys[i]]: "" };
1943
+ output[i] = formatProperty(ctx, tmp, recurseTimes, keys[i], kObjectType);
1944
+ const pos = StringPrototypeLastIndexOf(output[i], " ");
1945
+ // We have to find the last whitespace and have to replace that value as
1946
+ // it will be visualized as a regular string.
1947
+ output[i] = StringPrototypeSlice(output[i], 0, pos + 1) + ctx.stylize("<uninitialized>", "special");
1948
+ }
1949
+ }
1950
+ // Reset the keys to an empty array. This prevents duplicated inspection.
1951
+ keys.length = 0;
1952
+ return output;
1953
+ }
1954
+
1955
+ // The array is sparse and/or has extra keys
1956
+ function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) {
1957
+ const keys = ObjectKeys(value);
1958
+ let index = i;
1959
+ for (; i < keys.length && output.length < maxLength; i++) {
1960
+ const key = keys[i];
1961
+ const tmp = +key;
1962
+ // Arrays can only have up to 2^32 - 1 entries
1963
+ if (tmp > 2 ** 32 - 2) {
1964
+ break;
1965
+ }
1966
+ if (`${index}` !== key) {
1967
+ if (RegExpPrototypeExec(numberRegExp, key) === null) {
1968
+ break;
1969
+ }
1970
+ const emptyItems = tmp - index;
1971
+ const ending = emptyItems > 1 ? "s" : "";
1972
+ const message = `<${emptyItems} empty item${ending}>`;
1973
+ ArrayPrototypePush(output, ctx.stylize(message, "undefined"));
1974
+ index = tmp;
1975
+ if (output.length === maxLength) {
1976
+ break;
1977
+ }
1978
+ }
1979
+ ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, key, kArrayType));
1980
+ index++;
1981
+ }
1982
+ const remaining = value.length - index;
1983
+ if (output.length !== maxLength) {
1984
+ if (remaining > 0) {
1985
+ const ending = remaining > 1 ? "s" : "";
1986
+ const message = `<${remaining} empty item${ending}>`;
1987
+ ArrayPrototypePush(output, ctx.stylize(message, "undefined"));
1988
+ }
1989
+ } else if (remaining > 0) {
1990
+ ArrayPrototypePush(output, remainingText(remaining));
1991
+ }
1992
+ return output;
1993
+ }
1994
+
1995
+ function hexSlice(buf, start = 0, end) {
1996
+ return ArrayPrototypeJoin(
1997
+ ArrayPrototypeMap(buf.slice(start, end), x => ("00" + x.toString(16)).slice(-2)),
1998
+ "",
1999
+ );
2000
+ }
2001
+
2002
+ function formatArrayBuffer(ctx, value) {
2003
+ let buffer;
2004
+ try {
2005
+ buffer = new Uint8Array(value);
2006
+ } catch {
2007
+ return [ctx.stylize("(detached)", "special")];
2008
+ }
2009
+ let str = StringPrototypeTrim(
2010
+ RegExpPrototypeSymbolReplace(/(.{2})/g, hexSlice(buffer, 0, MathMin(ctx.maxArrayLength, buffer.length)), "$1 "),
2011
+ );
2012
+ const remaining = buffer.length - ctx.maxArrayLength;
2013
+ if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? "s" : ""}`;
2014
+ return [`${ctx.stylize("[Uint8Contents]", "special")}: <${str}>`];
2015
+ }
2016
+
2017
+ function formatArray(ctx, value, recurseTimes) {
2018
+ const valLen = value.length;
2019
+ const len = MathMin(MathMax(0, ctx.maxArrayLength), valLen);
2020
+
2021
+ const remaining = valLen - len;
2022
+ const output = [];
2023
+ for (let i = 0; i < len; i++) {
2024
+ // Special handle sparse arrays.
2025
+ if (!ObjectPrototypeHasOwnProperty(value, i)) {
2026
+ return formatSpecialArray(ctx, value, recurseTimes, len, output, i);
2027
+ }
2028
+ ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, i, kArrayType));
2029
+ }
2030
+ if (remaining > 0) {
2031
+ ArrayPrototypePush(output, remainingText(remaining));
2032
+ }
2033
+ return output;
2034
+ }
2035
+
2036
+ function formatTypedArray(value, length, ctx, ignored, recurseTimes) {
2037
+ const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), length);
2038
+ const remaining = value.length - maxLength;
2039
+ const output = new Array(maxLength);
2040
+ const elementFormatter = value.length > 0 && typeof value[0] === "number" ? formatNumber : formatBigInt;
2041
+ for (let i = 0; i < maxLength; ++i) {
2042
+ output[i] = elementFormatter(ctx.stylize, value[i], ctx.numericSeparator);
2043
+ }
2044
+ if (remaining > 0) {
2045
+ output[maxLength] = remainingText(remaining);
2046
+ }
2047
+ if (ctx.showHidden) {
2048
+ // .buffer goes last, it's not a primitive like the others.
2049
+ // All besides `BYTES_PER_ELEMENT` are actually getters.
2050
+ ctx.indentationLvl += 2;
2051
+ for (const key of ["BYTES_PER_ELEMENT", "length", "byteLength", "byteOffset", "buffer"]) {
2052
+ const str = formatValue(ctx, value[key], recurseTimes, true);
2053
+ ArrayPrototypePush(output, `[${key}]: ${str}`);
2054
+ }
2055
+ ctx.indentationLvl -= 2;
2056
+ }
2057
+ return output;
2058
+ }
2059
+
2060
+ function formatSet(value, ctx, ignored, recurseTimes) {
2061
+ const length = value.size;
2062
+ const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), length);
2063
+ const remaining = length - maxLength;
2064
+ const output = [];
2065
+ ctx.indentationLvl += 2;
2066
+ let i = 0;
2067
+ for (const v of value) {
2068
+ if (i >= maxLength) break;
2069
+ ArrayPrototypePush(output, formatValue(ctx, v, recurseTimes));
2070
+ i++;
2071
+ }
2072
+ if (remaining > 0) {
2073
+ ArrayPrototypePush(output, remainingText(remaining));
2074
+ }
2075
+ ctx.indentationLvl -= 2;
2076
+ return output;
2077
+ }
2078
+
2079
+ function formatMap(value, ctx, ignored, recurseTimes) {
2080
+ const length = value.size;
2081
+ const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), length);
2082
+ const remaining = length - maxLength;
2083
+ const output = [];
2084
+ ctx.indentationLvl += 2;
2085
+ let i = 0;
2086
+ for (const { 0: k, 1: v } of value) {
2087
+ if (i >= maxLength) break;
2088
+ ArrayPrototypePush(output, `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`);
2089
+ i++;
2090
+ }
2091
+ if (remaining > 0) {
2092
+ ArrayPrototypePush(output, remainingText(remaining));
2093
+ }
2094
+ ctx.indentationLvl -= 2;
2095
+ return output;
2096
+ }
2097
+
2098
+ function formatSetIterInner(ctx, recurseTimes, entries, state) {
2099
+ const maxArrayLength = MathMax(ctx.maxArrayLength, 0);
2100
+ const maxLength = MathMin(maxArrayLength, entries.length);
2101
+ const output = new Array(maxLength);
2102
+ ctx.indentationLvl += 2;
2103
+ for (let i = 0; i < maxLength; i++) {
2104
+ output[i] = formatValue(ctx, entries[i], recurseTimes);
2105
+ }
2106
+ ctx.indentationLvl -= 2;
2107
+ if (state === kWeak && !ctx.sorted) {
2108
+ // Sort all entries to have a halfway reliable output (if more entries than
2109
+ // retrieved ones exist, we can not reliably return the same output) if the
2110
+ // output is not sorted anyway.
2111
+ ArrayPrototypeSort(output);
2112
+ }
2113
+ const remaining = entries.length - maxLength;
2114
+ if (remaining > 0) {
2115
+ ArrayPrototypePush(output, remainingText(remaining));
2116
+ }
2117
+ return output;
2118
+ }
2119
+
2120
+ function formatMapIterInner(ctx, recurseTimes, entries, state) {
2121
+ const maxArrayLength = MathMax(ctx.maxArrayLength, 0);
2122
+ // Entries exist as [key1, val1, key2, val2, ...]
2123
+ const len = entries.length / 2;
2124
+ const remaining = len - maxArrayLength;
2125
+ const maxLength = MathMin(maxArrayLength, len);
2126
+ const output = new Array(maxLength);
2127
+ let i = 0;
2128
+ ctx.indentationLvl += 2;
2129
+ if (state === kWeak) {
2130
+ for (; i < maxLength; i++) {
2131
+ const pos = i * 2;
2132
+ output[i] = `${formatValue(ctx, entries[pos], recurseTimes)} => ${formatValue(
2133
+ ctx,
2134
+ entries[pos + 1],
2135
+ recurseTimes,
2136
+ )}`;
2137
+ }
2138
+ // Sort all entries to have a halfway reliable output (if more entries than
2139
+ // retrieved ones exist, we can not reliably return the same output) if the
2140
+ // output is not sorted anyway.
2141
+ if (!ctx.sorted) ArrayPrototypeSort(output);
2142
+ } else {
2143
+ for (; i < maxLength; i++) {
2144
+ const pos = i * 2;
2145
+ const res = [formatValue(ctx, entries[pos], recurseTimes), formatValue(ctx, entries[pos + 1], recurseTimes)];
2146
+ output[i] = reduceToSingleString(ctx, res, "", ["[", "]"], kArrayExtrasType, recurseTimes);
2147
+ }
2148
+ }
2149
+ ctx.indentationLvl -= 2;
2150
+ if (remaining > 0) {
2151
+ ArrayPrototypePush(output, remainingText(remaining));
2152
+ }
2153
+ return output;
2154
+ }
2155
+
2156
+ function formatWeakCollection(ctx) {
2157
+ return [ctx.stylize("<items unknown>", "special")];
2158
+ }
2159
+
2160
+ function formatWeakSet(ctx, value, recurseTimes) {
2161
+ const entries = previewEntries(value);
2162
+ return formatSetIterInner(ctx, recurseTimes, entries, kWeak);
2163
+ }
2164
+
2165
+ function formatWeakMap(ctx, value, recurseTimes) {
2166
+ const entries = previewEntries(value);
2167
+ return formatMapIterInner(ctx, recurseTimes, entries, kWeak);
2168
+ }
2169
+
2170
+ function formatIterator(braces, ctx, value, recurseTimes) {
2171
+ const { 0: entries, 1: isKeyValue } = previewEntries(value, true);
2172
+ if (isKeyValue) {
2173
+ // TODO(bun): JSC can also differ between the keys and values iterator, maybe we should also distinguish those in the future?
2174
+ // Mark entry iterators as such.
2175
+ braces[0] = RegExpPrototypeSymbolReplace(/ Iterator] {$/, braces[0], " Entries] {");
2176
+ return formatMapIterInner(ctx, recurseTimes, entries, kMapEntries);
2177
+ }
2178
+
2179
+ return formatSetIterInner(ctx, recurseTimes, entries, kIterator);
2180
+ }
2181
+
2182
+ function formatPromise(ctx, value, recurseTimes) {
2183
+ let output;
2184
+ const { 0: state, 1: result } = getPromiseDetails(value);
2185
+ if (state === kPending) {
2186
+ output = [ctx.stylize("<pending>", "special")];
2187
+ } else {
2188
+ ctx.indentationLvl += 2;
2189
+ const str = formatValue(ctx, result, recurseTimes);
2190
+ ctx.indentationLvl -= 2;
2191
+ output = [state === kRejected ? `${ctx.stylize("<rejected>", "special")} ${str}` : str];
2192
+ }
2193
+ return output;
2194
+ }
2195
+
2196
+ function formatProperty(ctx, value, recurseTimes, key, type, desc, original = value) {
2197
+ let name, str;
2198
+ let extra = " ";
2199
+ desc ||= ObjectGetOwnPropertyDescriptor(value, key) || { value: value[key], enumerable: true };
2200
+ if (desc.value !== undefined) {
2201
+ const diff = ctx.compact !== true || type !== kObjectType ? 2 : 3;
2202
+ ctx.indentationLvl += diff;
2203
+ str = formatValue(ctx, desc.value, recurseTimes);
2204
+ if (diff === 3 && ctx.breakLength < getStringWidth(str, ctx.colors)) {
2205
+ extra = `\n${StringPrototypeRepeat(" ", ctx.indentationLvl)}`;
2206
+ }
2207
+ ctx.indentationLvl -= diff;
2208
+ } else if (desc.get !== undefined) {
2209
+ const label = desc.set !== undefined ? "Getter/Setter" : "Getter";
2210
+ const s = ctx.stylize;
2211
+ const sp = "special";
2212
+ if (
2213
+ ctx.getters &&
2214
+ (ctx.getters === true ||
2215
+ (ctx.getters === "get" && desc.set === undefined) ||
2216
+ (ctx.getters === "set" && desc.set !== undefined))
2217
+ ) {
2218
+ try {
2219
+ const tmp = FunctionPrototypeCall(desc.get, original);
2220
+ ctx.indentationLvl += 2;
2221
+ if (tmp === null) {
2222
+ str = `${s(`[${label}:`, sp)} ${s("null", "null")}${s("]", sp)}`;
2223
+ } else if (typeof tmp === "object") {
2224
+ str = `${s(`[${label}]`, sp)} ${formatValue(ctx, tmp, recurseTimes)}`;
2225
+ } else {
2226
+ const primitive = formatPrimitive(s, tmp, ctx);
2227
+ str = `${s(`[${label}:`, sp)} ${primitive}${s("]", sp)}`;
2228
+ }
2229
+ ctx.indentationLvl -= 2;
2230
+ } catch (err) {
2231
+ const message = `<Inspection threw (${err.message})>`;
2232
+ str = `${s(`[${label}:`, sp)} ${message}${s("]", sp)}`;
2233
+ }
2234
+ } else {
2235
+ str = ctx.stylize(`[${label}]`, sp);
2236
+ }
2237
+ } else if (desc.set !== undefined) {
2238
+ str = ctx.stylize("[Setter]", "special");
2239
+ } else {
2240
+ str = ctx.stylize("undefined", "undefined");
2241
+ }
2242
+ if (type === kArrayType) return str;
2243
+ if (typeof key === "symbol") {
2244
+ const tmp = RegExpPrototypeSymbolReplace(strEscapeSequencesReplacer, SymbolPrototypeToString(key), escapeFn);
2245
+ name = `[${ctx.stylize(tmp, "symbol")}]`;
2246
+ } else if (key === "__proto__") {
2247
+ name = "['__proto__']";
2248
+ } else if (desc.enumerable === false) {
2249
+ const tmp = RegExpPrototypeSymbolReplace(strEscapeSequencesReplacer, key, escapeFn);
2250
+ name = `[${tmp}]`;
2251
+ } else if (RegExpPrototypeExec(keyStrRegExp, key) !== null) {
2252
+ name = ctx.stylize(key, "name");
2253
+ } else {
2254
+ name = ctx.stylize(strEscape(key), "string");
2255
+ }
2256
+ return `${name}:${extra}${str}`;
2257
+ }
2258
+
2259
+ function isBelowBreakLength(ctx, output, start, base) {
2260
+ // Each entry is separated by at least a comma. Thus, we start with a total
2261
+ // length of at least `output.length`. In addition, some cases have a
2262
+ // whitespace in-between each other that is added to the total as well.
2263
+ // TODO(BridgeAR): Add unicode support. Use the readline getStringWidth
2264
+ // function. Check the performance overhead and make it an opt-in in case it's significant.
2265
+ let totalLength = output.length + start;
2266
+ if (totalLength + output.length > ctx.breakLength) return false;
2267
+ for (let i = 0; i < output.length; i++) {
2268
+ if (ctx.colors) {
2269
+ totalLength += StringPrototypeReplaceAll(output[i], /\u001B\[\d\d?m/g, "").length; // remove colors
2270
+ } else {
2271
+ totalLength += output[i].length;
2272
+ }
2273
+ if (totalLength > ctx.breakLength) {
2274
+ return false;
2275
+ }
2276
+ }
2277
+ // Do not line up properties on the same line if `base` contains line breaks.
2278
+ return base === "" || !StringPrototypeIncludes(base, "\n");
2279
+ }
2280
+
2281
+ function reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value) {
2282
+ if (ctx.compact !== true) {
2283
+ if (typeof ctx.compact === "number" && ctx.compact >= 1) {
2284
+ // Memorize the original output length. In case the output is grouped,
2285
+ // prevent lining up the entries on a single line.
2286
+ const entries = output.length;
2287
+ // Group array elements together if the array contains at least six
2288
+ // separate entries.
2289
+ if (extrasType === kArrayExtrasType && entries > 6) {
2290
+ output = groupArrayElements(ctx, output, value);
2291
+ }
2292
+ // `ctx.currentDepth` is set to the most inner depth of the currently
2293
+ // inspected object part while `recurseTimes` is the actual current depth
2294
+ // that is inspected.
2295
+ //
2296
+ // Example:
2297
+ //
2298
+ // const a = { first: [ 1, 2, 3 ], second: { inner: [ 1, 2, 3 ] } }
2299
+ //
2300
+ // The deepest depth of `a` is 2 (a.second.inner) and `a.first` has a max
2301
+ // depth of 1.
2302
+ //
2303
+ // Consolidate all entries of the local most inner depth up to
2304
+ // `ctx.compact`, as long as the properties are smaller than
2305
+ // `ctx.breakLength`.
2306
+ if (ctx.currentDepth - recurseTimes < ctx.compact && entries === output.length) {
2307
+ // Line up all entries on a single line in case the entries do not
2308
+ // exceed `breakLength`. Add 10 as constant to start next to all other
2309
+ // factors that may reduce `breakLength`.
2310
+ const start = output.length + ctx.indentationLvl + braces[0].length + base.length + 10;
2311
+ if (isBelowBreakLength(ctx, output, start, base)) {
2312
+ const joinedOutput = ArrayPrototypeJoin(output, ", ");
2313
+ if (!StringPrototypeIncludes(joinedOutput, "\n")) {
2314
+ return `${base ? `${base} ` : ""}${braces[0]} ${joinedOutput}` + ` ${braces[1]}`;
2315
+ }
2316
+ }
2317
+ }
2318
+ }
2319
+ // Line up each entry on an individual line.
2320
+ const indentation = `\n${StringPrototypeRepeat(" ", ctx.indentationLvl)}`;
2321
+ return (
2322
+ `${base ? `${base} ` : ""}${braces[0]}${indentation} ` +
2323
+ `${ArrayPrototypeJoin(output, `,${indentation} `)}${indentation}${braces[1]}`
2324
+ );
2325
+ }
2326
+ // Line up all entries on a single line in case the entries do not exceed
2327
+ // `breakLength`.
2328
+ if (isBelowBreakLength(ctx, output, 0, base)) {
2329
+ return `${braces[0]}${base ? ` ${base}` : ""} ${ArrayPrototypeJoin(output, ", ")} ` + braces[1];
2330
+ }
2331
+ const indentation = StringPrototypeRepeat(" ", ctx.indentationLvl);
2332
+ // If the opening "brace" is too large, like in the case of "Set {",
2333
+ // we need to force the first item to be on the next line or the
2334
+ // items will not line up correctly.
2335
+ const ln = base === "" && braces[0].length === 1 ? " " : `${base ? ` ${base}` : ""}\n${indentation} `;
2336
+ // Line up each entry on an individual line.
2337
+ return `${braces[0]}${ln}${ArrayPrototypeJoin(output, `,\n${indentation} `)} ${braces[1]}`;
2338
+ }
2339
+
2340
+ function hasBuiltInToString(value) {
2341
+ // Prevent triggering proxy traps.
2342
+ const proxyTarget = getProxyDetails(value, false);
2343
+ if (proxyTarget !== undefined) {
2344
+ if (proxyTarget === null) return true;
2345
+ value = proxyTarget;
2346
+ }
2347
+
2348
+ // Count objects that have no `toString` function as built-in.
2349
+ if (typeof value.toString !== "function") return true;
2350
+
2351
+ // The object has a own `toString` property. Thus it's not not a built-in one.
2352
+ if (ObjectPrototypeHasOwnProperty(value, "toString")) return false;
2353
+
2354
+ // Find the object that has the `toString` property as own property in the prototype chain.
2355
+ let pointer = value;
2356
+ do {
2357
+ pointer = ObjectGetPrototypeOf(pointer);
2358
+ } while (!ObjectPrototypeHasOwnProperty(pointer, "toString"));
2359
+
2360
+ // Check closer if the object is a built-in.
2361
+ const descriptor = ObjectGetOwnPropertyDescriptor(pointer, "constructor");
2362
+ return (
2363
+ descriptor !== undefined && typeof descriptor.value === "function" && builtInObjects.has(descriptor.value.name)
2364
+ );
2365
+ }
2366
+
2367
+ const firstErrorLine = error => StringPrototypeSplit(error.message, "\n", 1)[0];
2368
+ let CIRCULAR_ERROR_MESSAGE;
2369
+ function tryStringify(arg) {
2370
+ try {
2371
+ return JSONStringify(arg);
2372
+ } catch (err) {
2373
+ // Populate the circular error message lazily
2374
+ if (!CIRCULAR_ERROR_MESSAGE) {
2375
+ try {
2376
+ const a = {};
2377
+ a.a = a;
2378
+ JSONStringify(a);
2379
+ } catch (circularError) {
2380
+ CIRCULAR_ERROR_MESSAGE = firstErrorLine(circularError);
2381
+ }
2382
+ }
2383
+ if (err.name === "TypeError" && firstErrorLine(err) === CIRCULAR_ERROR_MESSAGE) {
2384
+ return "[Circular]";
2385
+ }
2386
+ throw err;
2387
+ }
2388
+ }
2389
+
2390
+ function format(...args) {
2391
+ return formatWithOptionsInternal(undefined, args);
2392
+ }
2393
+
2394
+ function formatWithOptions(inspectOptions, ...args) {
2395
+ validateObject(inspectOptions, "inspectOptions", true);
2396
+ return formatWithOptionsInternal(inspectOptions, args);
2397
+ }
2398
+
2399
+ function formatNumberNoColor(number, options) {
2400
+ return formatNumber(stylizeNoColor, number, options?.numericSeparator ?? inspectDefaultOptions.numericSeparator);
2401
+ }
2402
+
2403
+ function formatBigIntNoColor(bigint, options) {
2404
+ return formatBigInt(stylizeNoColor, bigint, options?.numericSeparator ?? inspectDefaultOptions.numericSeparator);
2405
+ }
2406
+
2407
+ function formatWithOptionsInternal(inspectOptions, args) {
2408
+ const first = args[0];
2409
+ let a = 0;
2410
+ let str = "";
2411
+ let join = "";
2412
+
2413
+ if (typeof first === "string") {
2414
+ if (args.length === 1) {
2415
+ return first;
2416
+ }
2417
+ let tempStr;
2418
+ let lastPos = 0;
2419
+
2420
+ for (let i = 0; i < first.length - 1; i++) {
2421
+ if (StringPrototypeCharCodeAt(first, i) === 37) {
2422
+ // '%'
2423
+ const nextChar = StringPrototypeCharCodeAt(first, ++i);
2424
+ if (a + 1 !== args.length) {
2425
+ switch (nextChar) {
2426
+ case 115: {
2427
+ // 's'
2428
+ const tempArg = args[++a];
2429
+ if (typeof tempArg === "number") {
2430
+ tempStr = formatNumberNoColor(tempArg, inspectOptions);
2431
+ } else if (typeof tempArg === "bigint") {
2432
+ tempStr = formatBigIntNoColor(tempArg, inspectOptions);
2433
+ } else if (typeof tempArg !== "object" || tempArg === null || !hasBuiltInToString(tempArg)) {
2434
+ tempStr = String(tempArg);
2435
+ } else {
2436
+ tempStr = inspect(tempArg, {
2437
+ ...inspectOptions,
2438
+ compact: 3,
2439
+ colors: false,
2440
+ depth: 0,
2441
+ });
2442
+ }
2443
+ break;
2444
+ }
2445
+ case 106: // 'j'
2446
+ tempStr = tryStringify(args[++a]);
2447
+ break;
2448
+ case 100: {
2449
+ // 'd'
2450
+ const tempNum = args[++a];
2451
+ if (typeof tempNum === "bigint") {
2452
+ tempStr = formatBigIntNoColor(tempNum, inspectOptions);
2453
+ } else if (typeof tempNum === "symbol") {
2454
+ tempStr = "NaN";
2455
+ } else {
2456
+ tempStr = formatNumberNoColor(Number(tempNum), inspectOptions);
2457
+ }
2458
+ break;
2459
+ }
2460
+ case 79: // 'O'
2461
+ tempStr = inspect(args[++a], inspectOptions);
2462
+ break;
2463
+ case 111: // 'o'
2464
+ tempStr = inspect(args[++a], {
2465
+ ...inspectOptions,
2466
+ showHidden: true,
2467
+ showProxy: true,
2468
+ depth: 4,
2469
+ });
2470
+ break;
2471
+ case 105: {
2472
+ // 'i'
2473
+ const tempInteger = args[++a];
2474
+ if (typeof tempInteger === "bigint") {
2475
+ tempStr = formatBigIntNoColor(tempInteger, inspectOptions);
2476
+ } else if (typeof tempInteger === "symbol") {
2477
+ tempStr = "NaN";
2478
+ } else {
2479
+ tempStr = formatNumberNoColor(NumberParseInt(tempInteger), inspectOptions);
2480
+ }
2481
+ break;
2482
+ }
2483
+ case 102: {
2484
+ // 'f'
2485
+ const tempFloat = args[++a];
2486
+ if (typeof tempFloat === "symbol") {
2487
+ tempStr = "NaN";
2488
+ } else {
2489
+ tempStr = formatNumberNoColor(NumberParseFloat(tempFloat), inspectOptions);
2490
+ }
2491
+ break;
2492
+ }
2493
+ case 99: // 'c'
2494
+ a += 1;
2495
+ tempStr = "";
2496
+ break;
2497
+ case 37: // '%'
2498
+ str += StringPrototypeSlice(first, lastPos, i);
2499
+ lastPos = i + 1;
2500
+ continue;
2501
+ default: // Any other character is not a correct placeholder
2502
+ continue;
2503
+ }
2504
+ if (lastPos !== i - 1) {
2505
+ str += StringPrototypeSlice(first, lastPos, i - 1);
2506
+ }
2507
+ str += tempStr;
2508
+ lastPos = i + 1;
2509
+ } else if (nextChar === 37) {
2510
+ str += StringPrototypeSlice(first, lastPos, i);
2511
+ lastPos = i + 1;
2512
+ }
2513
+ }
2514
+ }
2515
+ if (lastPos !== 0) {
2516
+ a++;
2517
+ join = " ";
2518
+ if (lastPos < first.length) {
2519
+ str += StringPrototypeSlice(first, lastPos);
2520
+ }
2521
+ }
2522
+ }
2523
+
2524
+ while (a < args.length) {
2525
+ const value = args[a];
2526
+ str += join;
2527
+ str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
2528
+ join = " ";
2529
+ a++;
2530
+ }
2531
+ return str;
2532
+ }
2533
+
2534
+ function isZeroWidthCodePoint(code) {
2535
+ return (
2536
+ code <= 0x1f || // C0 control codes
2537
+ (code >= 0x7f && code <= 0x9f) || // C1 control codes
2538
+ (code >= 0x300 && code <= 0x36f) || // Combining Diacritical Marks
2539
+ (code >= 0x200b && code <= 0x200f) || // Modifying Invisible Characters
2540
+ // Combining Diacritical Marks for Symbols
2541
+ (code >= 0x20d0 && code <= 0x20ff) ||
2542
+ (code >= 0xfe00 && code <= 0xfe0f) || // Variation Selectors
2543
+ (code >= 0xfe20 && code <= 0xfe2f) || // Combining Half Marks
2544
+ (code >= 0xe0100 && code <= 0xe01ef)
2545
+ ); // Variation Selectors
2546
+ }
2547
+
2548
+ {
2549
+ /**
2550
+ * Returns the number of columns required to display the given string.
2551
+ */
2552
+ getStringWidth = function getStringWidth(str, removeControlChars = true) {
2553
+ let width = 0;
2554
+
2555
+ if (removeControlChars) str = stripVTControlCharacters(str);
2556
+ str = StringPrototypeNormalize(str, "NFC");
2557
+ for (const char of new SafeStringIterator(str)) {
2558
+ const code = StringPrototypeCodePointAt(char, 0);
2559
+ if (isFullWidthCodePoint(code)) {
2560
+ width += 2;
2561
+ } else if (!isZeroWidthCodePoint(code)) {
2562
+ width++;
2563
+ }
2564
+ }
2565
+
2566
+ return width;
2567
+ };
2568
+
2569
+ /**
2570
+ * Returns true if the character represented by a given
2571
+ * Unicode code point is full-width. Otherwise returns false.
2572
+ */
2573
+ const isFullWidthCodePoint = code => {
2574
+ // Code points are partially derived from:
2575
+ // https://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt
2576
+ return (
2577
+ code >= 0x1100 &&
2578
+ (code <= 0x115f || // Hangul Jamo
2579
+ code === 0x2329 || // LEFT-POINTING ANGLE BRACKET
2580
+ code === 0x232a || // RIGHT-POINTING ANGLE BRACKET
2581
+ // CJK Radicals Supplement .. Enclosed CJK Letters and Months
2582
+ (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) ||
2583
+ // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
2584
+ (code >= 0x3250 && code <= 0x4dbf) ||
2585
+ // CJK Unified Ideographs .. Yi Radicals
2586
+ (code >= 0x4e00 && code <= 0xa4c6) ||
2587
+ // Hangul Jamo Extended-A
2588
+ (code >= 0xa960 && code <= 0xa97c) ||
2589
+ // Hangul Syllables
2590
+ (code >= 0xac00 && code <= 0xd7a3) ||
2591
+ // CJK Compatibility Ideographs
2592
+ (code >= 0xf900 && code <= 0xfaff) ||
2593
+ // Vertical Forms
2594
+ (code >= 0xfe10 && code <= 0xfe19) ||
2595
+ // CJK Compatibility Forms .. Small Form Variants
2596
+ (code >= 0xfe30 && code <= 0xfe6b) ||
2597
+ // Halfwidth and Fullwidth Forms
2598
+ (code >= 0xff01 && code <= 0xff60) ||
2599
+ (code >= 0xffe0 && code <= 0xffe6) ||
2600
+ // Kana Supplement
2601
+ (code >= 0x1b000 && code <= 0x1b001) ||
2602
+ // Enclosed Ideographic Supplement
2603
+ (code >= 0x1f200 && code <= 0x1f251) ||
2604
+ // Miscellaneous Symbols and Pictographs 0x1f300 - 0x1f5ff
2605
+ // Emoticons 0x1f600 - 0x1f64f
2606
+ (code >= 0x1f300 && code <= 0x1f64f) ||
2607
+ // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
2608
+ (code >= 0x20000 && code <= 0x3fffd))
2609
+ );
2610
+ };
2611
+ }
2612
+
2613
+ // Regex used for ansi escape code splitting
2614
+ // Adopted from https://github.com/chalk/ansi-regex/blob/HEAD/index.js
2615
+ // License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore
2616
+ // Matches all ansi escape code sequences in a string
2617
+ const ansiPattern =
2618
+ "[\\u001B\\u009B][[\\]()#;?]*" +
2619
+ "(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*" +
2620
+ "|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)" +
2621
+ "|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))";
2622
+ const ansi = new RegExp(ansiPattern, "g");
2623
+ /** Remove all VT control characters. Use to estimate displayed string width. */
2624
+ function stripVTControlCharacters(str) {
2625
+ if (typeof str !== "string") throw new codes.ERR_INVALID_ARG_TYPE("str", "string", str);
2626
+ return RegExpPrototypeSymbolReplace(ansi, str, "");
2627
+ }
2628
+
2629
+ // stubs for internal funcs and props
2630
+ const $promiseFieldFlags = Symbol("[[PromiseFlags]]");
2631
+ const $promiseFieldReactionsOrResult = Symbol("[[PromiseResult]]");
2632
+ const $promiseStatePending = 'pending';
2633
+ const $promiseStateRejected = 'rejected';
2634
+ const $proxyFieldHandler = Symbol("[[ProxyHandler]]");
2635
+ const $proxyFieldTarget = Symbol("[[ProxyTarget]]");
2636
+ //const $isMap = util.types.isMap;
2637
+ //const $isSet = util.types.isSet;
2638
+ const $getPromiseInternalField = (promise, field) => {
2639
+ if (field === $promiseFieldFlags) return Bun.peek.status(promise);
2640
+ if (field === $promiseFieldReactionsOrResult) return Bun.peek(promise);
2641
+ throw new Error("Unknown internal promise field");
2642
+ };
2643
+ const $isProxyObject = util.types.isProxy;
2644
+ const $getProxyInternalField = (proxy, field) => {
2645
+ if (field === $proxyFieldHandler) return $proxy.getProxyDetails(proxy, true)?.[1];
2646
+ if (field === $proxyFieldTarget) return $proxy.getProxyDetails(proxy, false);
2647
+ throw new Error("Unknown internal proxy field");
2648
+ };
2649
+ //const $getInternalField = (obj, field) => {
2650
+ // //if (field === 1 /*iteratorFieldIteratedObject*/) return Bun.peek.iteratedObject(obj);
2651
+ // //if (field === 2 /*iteratorFieldKind*/) return Bun.peek.kind(obj);
2652
+ // throw new Error("Unknown internal field");
2653
+ //};
2654
+
2655
+ // utils
2656
+ function getOwnNonIndexProperties(a, filter = ONLY_ENUMERABLE) {
2657
+ const desc = ObjectGetOwnPropertyDescriptors(a);
2658
+ const ret = [];
2659
+ for (const [k, v] of ObjectEntries(desc)) {
2660
+ if (!RegExpPrototypeTest(/^(0|[1-9][0-9]*)$/, k) || NumberParseInt(k, 10) >= 2 ** 32 - 1) {
2661
+ if (filter === ONLY_ENUMERABLE && !v.enumerable) continue; // Arrays are limited in size
2662
+ else ArrayPrototypePush(ret, k);
2663
+ }
2664
+ }
2665
+ for (const s of ObjectGetOwnPropertySymbols(a)) {
2666
+ const v = ObjectGetOwnPropertyDescriptor(a, s);
2667
+ if (filter === ONLY_ENUMERABLE && !v?.enumerable) continue;
2668
+ ArrayPrototypePush(ret, s);
2669
+ }
2670
+ return ret;
2671
+ }
2672
+ function getPromiseDetails(promise) {
2673
+ const state = $getPromiseInternalField(promise, $promiseFieldFlags);// & $promiseStateMask;
2674
+ if (state !== $promiseStatePending) {
2675
+ return [
2676
+ state === $promiseStateRejected ? kRejected : kFulfilled,
2677
+ $getPromiseInternalField(promise, $promiseFieldReactionsOrResult),
2678
+ ];
2679
+ }
2680
+ return [kPending, undefined];
2681
+ }
2682
+ function getProxyDetails(proxy, withHandler = true) {
2683
+ const isProxy = $isProxyObject(proxy);
2684
+ if (!isProxy) return undefined;
2685
+ const handler = $getProxyInternalField(proxy, $proxyFieldHandler);
2686
+ // if handler is null, the proxy is revoked
2687
+ const target = handler === null ? null : $getProxyInternalField(proxy, $proxyFieldTarget);
2688
+ if (target === undefined || handler === undefined) return undefined;
2689
+ if (withHandler) return [target, handler];
2690
+ else return target;
2691
+ }
2692
+ function previewEntries(val, isIterator = false) {
2693
+ return isIterator ? [[], false] : []; // sad
2694
+ //if (isIterator) {
2695
+ // // the Map or Set instance this iterator belongs to
2696
+ // const iteratedObject = $getInternalField(val, 1 /*iteratorFieldIteratedObject*/);
2697
+ // // for Maps: 0 = keys, 1 = values, 2 = entries
2698
+ // // for Sets: 1 = keys|values, 2 = entries
2699
+ // const kind = $getInternalField(val, 2 /*iteratorFieldKind*/);
2700
+ // const isEntries = kind === 2;
2701
+ // // TODO(bun): improve performance by not using Array.from and instead using the iterator directly to only get the first
2702
+ // // few entries which will actually be displayed (this requires changing some logic in the call sites of this function)
2703
+ // if ($isMap(iteratedObject)) {
2704
+ // if (isEntries) return [ArrayPrototypeFlat(ArrayFrom(iteratedObject)), true];
2705
+ // else if (kind === 1) return [ArrayFrom(MapPrototypeValues(iteratedObject)), false];
2706
+ // else return [ArrayFrom(MapPrototypeKeys(iteratedObject)), false];
2707
+ // } else if ($isSet(iteratedObject)) {
2708
+ // if (isEntries) return [ArrayPrototypeFlat(ArrayFrom(SetPrototypeEntries(iteratedObject))), true];
2709
+ // else return [ArrayFrom(iteratedObject), false];
2710
+ // }
2711
+ // // TODO(bun): This function is currently only called for Map and Set iterators
2712
+ // // perhaps we should add support for other iterators in the future? (e.g. ArrayIterator and StringIterator)
2713
+ // else throw new Error("previewEntries(): Invalid iterator received");
2714
+ //}
2715
+ //// TODO(bun): are there any JSC APIs for viewing the contents of these in JS?
2716
+ //if (isWeakMap(val)) return [];
2717
+ //if (isWeakSet(val)) return [];
2718
+ //else throw new Error("previewEntries(): Invalid object received");
2719
+ }
2720
+ function internalGetConstructorName(val) {
2721
+ if (!val || typeof val !== "object") throw new Error("Invalid object");
2722
+ if (val.constructor?.name) return val.constructor.name;
2723
+ const str = ObjectPrototypeToString(val);
2724
+ const m = StringPrototypeMatch(str, /^\[object ([^\]]+)\]/); // e.g. [object Boolean]
2725
+ return m ? m[1] : "Object";
2726
+ }
2727
+
2728
+ export const $Proxy = $proxy.Proxy; //! modified
2729
+ export default {
2730
+ inspect,
2731
+ format,
2732
+ formatWithOptions,
2733
+ stripVTControlCharacters,
2734
+ //! non-standard properties, should these be kept? (not currently exposed)
2735
+ //stylizeWithColor,
2736
+ //stylizeWithHTML(str, styleType) {
2737
+ // const style = inspect.styles[styleType];
2738
+ // if (style !== undefined) {
2739
+ // return `<span style="color:${style};">${escapeHTML(str)}</span>`;
2740
+ // }
2741
+ // return escapeHTML(str);
2742
+ //},
2743
+ };
2744
+
2745
+ // unused without `stylizeWithHTML`
2746
+ /*const entities = {
2747
+ 34: "&quot;",
2748
+ 38: "&amp;",
2749
+ 39: "&apos;",
2750
+ 60: "&lt;",
2751
+ 62: "&gt;",
2752
+ 160: "&nbsp;",
2753
+ };
2754
+ function escapeHTML(str) {
2755
+ return str.replace(/[\u0000-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u00FF]/g, c => {
2756
+ const code = String(c.charCodeAt(0));
2757
+ const ent = entities[code];
2758
+ return ent || "&#" + code + ";";
2759
+ });
2760
+ }*/