Sources/OrgApp/JavaScriptBlocks.swift

7fee8f1214931d1d034bc40d1155a605813239cc
orgstar/Sources/OrgApp/JavaScriptBlocks.swift

1515 lines · 83996 bytes

   1#if canImport(JavaScriptCore)
   2import Foundation
   3import JavaScriptCore
   4import OrgCore
   5
   6/// js and javascript blocks in JavaScriptCore, as `node` runs them, for builds that can't start
   7/// node. Node's `require('util')`, `require('process')`, `console` and timers are written in
   8/// JavaScript below; a block that uses anything else of Node's, or prints a value whose text
   9/// can't be made the same as Node's, is refused rather than given a different result.
  10///
  11/// The public JavaScriptCore API can't stop a running script. A run that is canceled or times
  12/// out ends at once, but a script that never finishes keeps its thread busy until the app quits.
  13public enum JavaScriptBlocks {
  14    /// Runs `job` when it is a js block, in `directory` or its `:dir`; nil for other languages.
  15    /// `:cmd` is ignored.
  16    public static func run(_ job: BabelJob, directory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput? {
  17        guard job.language == "js" || job.language == "javascript" else { return nil }
  18        let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
  19        switch job.runner {
  20        case .process:
  21            guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
  22            return try await evaluate(timeout: timeout) { run in try Engine().main(job.input, run: run) }
  23        case .session(let name, _, .node):
  24            guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
  25            // One context per file folder and session name; a stopped run's context is dropped.
  26            let key = folder.path + "\u{1}" + name
  27            let engine = sessions.engine(key)
  28            do {
  29                return try await evaluate(timeout: timeout) { run in try engine.session(job.input, value: !job.finish.output, run: run) }
  30            } catch let error where error is CancellationError || error is Stopped {
  31                sessions.drop(key, engine)
  32                throw error
  33            }
  34        default:
  35            return nil
  36        }
  37    }
  38
  39    /// Runs a js `job` without a session on the calling thread, as `org-sbe` in a table
  40    /// formula needs; nil for other jobs.
  41    public static func runHere(_ job: BabelJob) throws -> BabelOutput? {
  42        guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil }
  43        return try Engine().main(job.input, run: Run())
  44    }
  45
  46    struct Stopped: Error, CustomStringConvertible {
  47        let description: String
  48    }
  49
  50    /// Runs `body` on a thread of its own, which a cancel or the timeout leaves behind.
  51    private static func evaluate(timeout: Duration, _ body: @escaping @Sendable (Run) throws -> BabelOutput) async throws -> BabelOutput {
  52        let run = Run()
  53        let thread = Thread { run.end(Result { try body(run) }) }
  54        thread.stackSize = 8 << 20
  55        thread.start()
  56        let limit = Task {
  57            try await Task.sleep(for: timeout)
  58            run.end(.failure(Stopped(description: "The block took longer than \(timeout) and was stopped.")))
  59        }
  60        defer { limit.cancel() }
  61        return try await withTaskCancellationHandler {
  62            try await withCheckedThrowingContinuation { run.wait($0) }
  63        } onCancel: {
  64            run.end(.failure(CancellationError()))
  65        }
  66    }
  67
  68    /// A run, which ends once: with the script's output, a cancel or the timeout.
  69    final class Run: @unchecked Sendable {
  70        private let lock = NSLock()
  71        private var result: Result<BabelOutput, Error>?
  72        private var continuation: CheckedContinuation<BabelOutput, Error>?
  73        private let wake = DispatchSemaphore(value: 0)
  74
  75        var stopped: Bool { lock.withLock { result != nil } }
  76
  77        func end(_ outcome: Result<BabelOutput, Error>) {
  78            let (first, waiting) = lock.withLock { () -> (Bool, CheckedContinuation<BabelOutput, Error>?) in
  79                guard result == nil else { return (false, nil) }
  80                result = outcome
  81                defer { continuation = nil }
  82                return (true, continuation)
  83            }
  84            guard first else { return }
  85            waiting?.resume(with: outcome)
  86            wake.signal()
  87        }
  88
  89        func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) {
  90            let done = lock.withLock { () -> Result<BabelOutput, Error>? in
  91                if result == nil { self.continuation = continuation }
  92                return result
  93            }
  94            if let done { continuation.resume(with: done) }
  95        }
  96
  97        /// Waits for a timer, or until the run ends.
  98        func sleep(milliseconds: Double) {
  99            _ = wake.wait(timeout: .now() + .milliseconds(Int(milliseconds.rounded(.up))))
 100        }
 101    }
 102
 103    private static let sessions = Sessions()
 104
 105    final class Sessions: @unchecked Sendable {
 106        private let lock = NSLock()
 107        private var engines: [String: Engine] = [:]
 108
 109        func engine(_ key: String) -> Engine {
 110            lock.withLock {
 111                if let engine = engines[key] { return engine }
 112                let engine = Engine(session: true)
 113                engines[key] = engine
 114                return engine
 115            }
 116        }
 117
 118        func drop(_ key: String, _ engine: Engine) {
 119            lock.withLock { if engines[key] === engine { engines[key] = nil } }
 120        }
 121    }
 122
 123    /// A context with Node's globals, and what its scripts wrote.
 124    final class Engine: @unchecked Sendable {
 125        private final class Output {
 126            var stdout = ""
 127            var stderr = ""
 128            var exception: JSValue?
 129        }
 130
 131        private let context: JSContext
 132        private let node: JSValue
 133        private let output: Output
 134        private let lock = NSLock()
 135
 136        /// A session's context has `require`, `module` and the rest of a module's names as
 137        /// globals, as `node -e` has them.
 138        init(session: Bool = false) {
 139            let output = Output()
 140            self.output = output
 141            context = JSContext()
 142            let write: @convention(block) (Int32, String) -> Void = { fd, text in
 143                if fd == 1 { output.stdout += text } else { output.stderr += text }
 144            }
 145            // Runs a session's script as a script of its own, which the caller's call holds back
 146            // the promise callbacks of: whether it threw, and its error or completion value.
 147            let script: @convention(block) (String) -> JSValue = { source in
 148                let context = JSContext.current()!
 149                output.exception = nil
 150                let completion = context.evaluateScript(source)
 151                let result = JSValue(newArrayIn: context)!
 152                result.setValue(output.exception != nil, at: 0)
 153                result.setValue(output.exception ?? completion, at: 1)
 154                output.exception = nil
 155                return result
 156            }
 157            context.exceptionHandler = { _, exception in output.exception = exception }
 158            node = context.evaluateScript(Self.shim).call(withArguments: [write, script, session])
 159        }
 160
 161        /// Runs `source` as node runs a script file, as Emacs runs it, then its timers.
 162        func main(_ source: String, run: Run) throws -> BabelOutput {
 163            node.invokeMethod("main", withArguments: [source])
 164            runTimers(run)
 165            return try finish(result: nil)
 166        }
 167
 168        /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does;
 169        /// with `value`, the result is its completion value as `util.inspect` prints it. A block
 170        /// that leaves a timer, or a promise callback that prints or throws, is refused.
 171        func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput {
 172            try lock.withLock {
 173                output.stdout = ""
 174                output.stderr = ""
 175                output.exception = nil
 176                node.invokeMethod("session", withArguments: [source, value])
 177                // node's session returns before its timers and promise callbacks run, and they print later.
 178                node.invokeMethod("settle", withArguments: [])
 179                let result = node.forProperty("result")
 180                return try finish(result: result?.isString == true ? result?.toString() : nil)
 181            }
 182        }
 183
 184        private func runTimers(_ run: Run) {
 185            while !run.stopped, let wait = node.invokeMethod("tick", withArguments: [])?.toDouble(), wait >= 0 {
 186                if wait > 0 { run.sleep(milliseconds: wait) }
 187            }
 188        }
 189
 190        private func finish(result: String?) throws -> BabelOutput {
 191            if let refused = node.forProperty("refused")?.toString(), !refused.isEmpty {
 192                throw Babel.Failure.message("This block uses \(refused), which runs only in node.")
 193            }
 194            guard let error = node.forProperty("error"), !error.isUndefined else {
 195                return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr)
 196            }
 197            return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr + (error.toString() ?? "") + "\n", status: 1)
 198        }
 199
 200        /// Node's globals and modules; `util.inspect` and `util.format` are ported from Node 26's
 201        /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the
 202        /// runner's controls.
 203        static let shim = #"""
 204            (function shim(write, script, session) {
 205              'use strict';
 206              const functionToString = Function.prototype.toString;
 207              const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now(), draining: false, result: undefined };
 208              const lateInSession = 'a promise callback that prints or throws in a session';
 209
 210              function refuse(what) {
 211                if (!state.refused) state.refused = what;
 212                throw new Error(`${what} isn't available`);
 213              }
 214              function out(fd, text) {
 215                // node's session prints a promise callback's text after the block.
 216                if (state.draining) {
 217                  if (!state.refused) state.refused = lateInSession;
 218                  return;
 219                }
 220                if (!state.dead) write(fd, text.toWellFormed());
 221              }
 222              // Members a script may use, its own and those in `extra`; any other, and listing them, is
 223              // refused rather than answered differently.
 224              const ownProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
 225              const guarded = new WeakMap();
 226              function guard(target, name, extra = []) {
 227                const known = (t, key) => typeof key === 'symbol' || ownProperty(t, key) || extra.includes(key);
 228                const member = (t, key) => { if (!known(t, key)) refuse(`${name}.${String(key)}`); };
 229                const proxy = new Proxy(target, {
 230                  get(t, key, receiver) { member(t, key); return Reflect.get(t, key, receiver); },
 231                  has(t, key) { member(t, key); return Reflect.has(t, key); },
 232                  set(t, key, value, receiver) { member(t, key); return Reflect.set(t, key, value, receiver); },
 233                  defineProperty(t, key, descriptor) { member(t, key); return Reflect.defineProperty(t, key, descriptor); },
 234                  deleteProperty(t, key) { member(t, key); return Reflect.deleteProperty(t, key); },
 235                  getOwnPropertyDescriptor(t, key) { member(t, key); return Reflect.getOwnPropertyDescriptor(t, key); },
 236                  ownKeys() { refuse(`the members of ${name}`); },
 237                  getPrototypeOf() { refuse(`the prototype of ${name}`); },
 238                  setPrototypeOf() { refuse(`the prototype of ${name}`); },
 239                });
 240                guarded.set(proxy, name);
 241                return proxy;
 242              }
 243              // The script's proxies, target and handler, or null once revoked: JavaScriptCore can't tell
 244              // a proxy, and Node shows one.
 245              const proxies = new WeakMap();
 246              const RealProxy = Proxy;
 247              function revocable(target, handler) {
 248                const made = RealProxy.revocable(target, handler);
 249                proxies.set(made.proxy, [target, handler]);
 250                return { proxy: made.proxy, revoke: [() => { proxies.set(made.proxy, null); made.revoke(); }][0] };
 251              }
 252              const ProxyConstructor = new RealProxy(RealProxy, {
 253                construct(target, args, newTarget) {
 254                  const proxy = Reflect.construct(target, args, newTarget);
 255                  proxies.set(proxy, [args[0], args[1]]);
 256                  return proxy;
 257                },
 258                get(target, key, receiver) {
 259                  return key === 'revocable' ? revocable : Reflect.get(target, key, receiver);
 260                },
 261              });
 262
 263              // util.inspect and util.format, after Node's lib/internal/util/inspect.js.
 264              const kObjectType = 0, kArrayType = 1, kArrayExtrasType = 2;
 265              const defaults = {
 266                showHidden: false, depth: 2, colors: false, customInspect: true, showProxy: false, maxArrayLength: 100,
 267                maxStringLength: 10000, breakLength: 80, compact: 3, sorted: false, getters: false, numericSeparator: false,
 268              };
 269              const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
 270              const builtInObjects = new Set(Object.getOwnPropertyNames(globalThis).filter((e) => /^[A-Z][a-zA-Z0-9]+$/.test(e)));
 271              const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
 272              const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
 273              const strEscapeSequencesRegExpSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
 274              const strEscapeSequencesReplacerSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
 275              const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
 276              const numberRegExp = /^(0|[1-9][0-9]*)$/;
 277              const classRegExp = /^(\s+[^(]*?)\s*{/;
 278              const stripCommentsRegExp = /(\/\/.*?\n)|(\/\*(.|\n)*?\*\/)/g;
 279              const kMinLineLength = 16;
 280              const meta = [
 281                '\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07',
 282                '\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F',
 283                '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17',
 284                '\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F',
 285                '', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '',
 286                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 287                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 288                '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '',
 289                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 290                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F',
 291                '\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87',
 292                '\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F',
 293                '\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97',
 294                '\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F',
 295              ];
 296
 297              // Type checks through the built-ins' own brand checks.
 298              function branded(fn, value) {
 299                try { fn.call(value); return true; } catch { return false; }
 300              }
 301              const getter = (proto, key) => Object.getOwnPropertyDescriptor(proto, key).get;
 302              const typedArrayProto = Object.getPrototypeOf(Int8Array.prototype);
 303              const typedArrayTag = getter(typedArrayProto, Symbol.toStringTag);
 304              const isSet = (v) => branded(getter(Set.prototype, 'size'), v);
 305              const isMap = (v) => branded(getter(Map.prototype, 'size'), v);
 306              const isTypedArray = (v) => typedArrayTag.call(v) !== undefined;
 307              const isArrayBuffer = (v) => branded(getter(ArrayBuffer.prototype, 'byteLength'), v);
 308              const isDataView = (v) => branded(getter(DataView.prototype, 'byteLength'), v);
 309              const isRegExp = (v) => v !== RegExp.prototype && branded(getter(RegExp.prototype, 'source'), v);
 310              const isDate = (v) => branded(Date.prototype.getTime, v);
 311              const isWeakMap = (v) => branded(function () { WeakMap.prototype.has.call(this, {}); }, v);
 312              const isWeakSet = (v) => branded(function () { WeakSet.prototype.has.call(this, {}); }, v);
 313              const isPromise = (v) => Object.prototype.toString.call(v) === '[object Promise]' && v instanceof Promise;
 314              const isError = (v) => v instanceof Error || Object.prototype.toString.call(v) === '[object Error]';
 315              const isArgumentsObject = (v) => Object.prototype.toString.call(v) === '[object Arguments]';
 316              const iteratorTags = ['[object Map Iterator]', '[object Set Iterator]', '[object Array Iterator]', '[object String Iterator]', '[object Generator]', '[object Iterator Helper]'];
 317              const generatorFunctionProto = Object.getPrototypeOf(function* () {});
 318              const asyncFunctionProto = Object.getPrototypeOf(async function () {});
 319              const asyncGeneratorFunctionProto = Object.getPrototypeOf(async function* () {});
 320              const boxes = [
 321                ['Number', Number.prototype.valueOf], ['String', String.prototype.valueOf], ['Boolean', Boolean.prototype.valueOf],
 322                ['BigInt', BigInt.prototype.valueOf], ['Symbol', Symbol.prototype.valueOf],
 323              ];
 324              const boxType = (v) => boxes.find(([, fn]) => branded(fn, v));
 325              const internalGetConstructorName = (v) => Object.prototype.toString.call(v).slice(8, -1);
 326
 327              // Width as a terminal shows it; text beyond ASCII is measured by ICU in Node.
 328              function getStringWidth(str) {
 329                let width = 0;
 330                for (let i = 0; i < str.length; i++) {
 331                  const code = str.charCodeAt(i);
 332                  if (code >= 127) refuse('lining up text beyond ASCII in util.inspect');
 333                  width += code >= 32 ? 1 : 0;
 334                }
 335                return width;
 336              }
 337
 338              function inspect(value, opts) {
 339                const ctx = { budget: {}, indentationLvl: 0, seen: [], currentDepth: 0, ...defaults };
 340                if (arguments.length > 1) {
 341                  if (arguments.length > 2) {
 342                    if (arguments[2] !== undefined) ctx.depth = arguments[2];
 343                    if (arguments.length > 3 && arguments[3] !== undefined) ctx.colors = arguments[3];
 344                  }
 345                  if (typeof opts === 'boolean') {
 346                    ctx.showHidden = opts;
 347                  } else if (opts) {
 348                    for (const key of Object.keys(opts)) {
 349                      if (Object.prototype.hasOwnProperty.call(defaults, key)) ctx[key] = opts[key];
 350                      else if (key === 'stylize') refuse('util.inspect with stylize');
 351                      else if (ctx.userOptions === undefined) ctx.userOptions = opts;
 352                    }
 353                  }
 354                }
 355                if (ctx.colors) refuse('util.inspect with colors');
 356                if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
 357                if (ctx.maxStringLength === null) ctx.maxStringLength = Infinity;
 358                return formatValue(ctx, value, 0);
 359              }
 360              inspect.custom = customInspectSymbol;
 361              Object.defineProperty(inspect, 'defaultOptions', { get() { refuse('util.inspect.defaultOptions'); } });
 362
 363              const stylize = (str) => str;
 364
 365              function getUserOptions(ctx) {
 366                const ret = { stylize };
 367                for (const key of Object.keys(defaults)) ret[key] = ctx[key];
 368                return { ...ret, ...ctx.userOptions };
 369              }
 370
 371              function formatValue(ctx, value, recurseTimes, typedArray) {
 372                if (typeof value !== 'object' && typeof value !== 'function') return formatPrimitive(value, ctx);
 373                if (value === null) return 'null';
 374                if (guarded.has(value)) refuse(`util.inspect of ${guarded.get(value)}`);
 375                if (value === globalThis) refuse('util.inspect of the global object');
 376                const context = value;
 377                let proxyCount = 0;
 378                let proxy = proxies.get(value);
 379                if (proxy !== undefined) {
 380                  if (ctx.showProxy) return proxy === null ? '<Revoked Proxy>' : formatProxy(ctx, proxy, recurseTimes);
 381                  do {
 382                    if (proxy === null) return 'Proxy('.repeat(proxyCount) + '<Revoked Proxy>' + ')'.repeat(proxyCount);
 383                    value = proxy[0];
 384                    proxy = proxies.get(value);
 385                    proxyCount += 1;
 386                  } while (proxy !== undefined);
 387                }
 388                const formatted = formatUnwrapped(ctx, value, context, recurseTimes, typedArray);
 389                return 'Proxy('.repeat(proxyCount) + formatted + ')'.repeat(proxyCount);
 390              }
 391
 392              function formatProxy(ctx, proxy, recurseTimes) {
 393                if (recurseTimes > ctx.depth && ctx.depth !== null) return 'Proxy [Array]';
 394                recurseTimes += 1;
 395                ctx.indentationLvl += 2;
 396                const res = [formatValue(ctx, proxy[0], recurseTimes), formatValue(ctx, proxy[1], recurseTimes)];
 397                ctx.indentationLvl -= 2;
 398                return reduceToSingleString(ctx, res, '', ['Proxy [', ']'], kArrayExtrasType, recurseTimes);
 399              }
 400
 401              function formatUnwrapped(ctx, value, context, recurseTimes, typedArray) {
 402                if (ctx.customInspect) {
 403                  const maybeCustom = value[customInspectSymbol];
 404                  if (typeof maybeCustom === 'function' && maybeCustom !== inspect &&
 405                      Object.getOwnPropertyDescriptor(value, 'constructor')?.value?.prototype !== value) {
 406                    const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
 407                    const ret = maybeCustom.call(context, depth, getUserOptions(ctx), inspect);
 408                    if (ret !== context) {
 409                      if (typeof ret !== 'string') return formatValue(ctx, ret, recurseTimes);
 410                      return ret.replaceAll('\n', `\n${' '.repeat(ctx.indentationLvl)}`);
 411                    }
 412                  }
 413                }
 414                if (ctx.seen.includes(value)) {
 415                  let index = 1;
 416                  if (ctx.circular === undefined) {
 417                    ctx.circular = new Map();
 418                    ctx.circular.set(value, index);
 419                  } else {
 420                    index = ctx.circular.get(value);
 421                    if (index === undefined) {
 422                      index = ctx.circular.size + 1;
 423                      ctx.circular.set(value, index);
 424                    }
 425                  }
 426                  return `[Circular *${index}]`;
 427                }
 428                return formatRaw(ctx, value, recurseTimes, typedArray);
 429              }
 430
 431              function getConstructorName(obj, ctx, recurseTimes, protoProps) {
 432                let firstProto;
 433                const tmp = obj;
 434                while (obj) {
 435                  const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
 436                  if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '' &&
 437                      isInstanceof(tmp, descriptor.value)) {
 438                    if (protoProps !== undefined && (firstProto !== obj || !builtInObjects.has(descriptor.value.name))) {
 439                      addPrototypeProperties(ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
 440                    }
 441                    return String(descriptor.value.name);
 442                  }
 443                  obj = Object.getPrototypeOf(obj);
 444                  if (firstProto === undefined) firstProto = obj;
 445                }
 446                if (firstProto === null) return null;
 447                const res = internalGetConstructorName(tmp);
 448                if (recurseTimes > ctx.depth && ctx.depth !== null) return `${res} <Complex prototype>`;
 449                const protoConstr = getConstructorName(firstProto, ctx, recurseTimes + 1, protoProps);
 450                if (protoConstr === null) {
 451                  return `${res} <${inspect(firstProto, { ...ctx, customInspect: false, depth: -1 })}>`;
 452                }
 453                return `${res} <${protoConstr}>`;
 454              }
 455
 456              function isInstanceof(object, proto) {
 457                try { return object instanceof proto; } catch { return false; }
 458              }
 459
 460              function addPrototypeProperties(ctx, main, obj, recurseTimes, output) {
 461                let depth = 0;
 462                let keys;
 463                let keySet;
 464                do {
 465                  if (depth !== 0 || main === obj) {
 466                    obj = Object.getPrototypeOf(obj);
 467                    if (obj === null) return;
 468                    const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
 469                    if (descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name)) return;
 470                  }
 471                  if (depth === 0) {
 472                    keySet = new Set();
 473                  } else {
 474                    keys.forEach((key) => keySet.add(key));
 475                  }
 476                  keys = Reflect.ownKeys(obj);
 477                  ctx.seen.push(main);
 478                  for (const key of keys) {
 479                    if (key === 'constructor' || Object.prototype.hasOwnProperty.call(main, key) || (depth !== 0 && keySet.has(key))) continue;
 480                    const desc = Object.getOwnPropertyDescriptor(obj, key);
 481                    if (typeof desc.value === 'function') continue;
 482                    output.push(formatProperty(ctx, obj, recurseTimes, key, kObjectType, desc, main));
 483                  }
 484                  ctx.seen.pop();
 485                } while (++depth !== 3);
 486              }
 487
 488              function getPrefix(constructor, tag, fallback, size = '') {
 489                if (constructor === null) {
 490                  if (tag !== '' && fallback !== tag) return `[${fallback}${size}: null prototype] [${tag}] `;
 491                  return `[${fallback}${size}: null prototype] `;
 492                }
 493                if (tag !== '') {
 494                  const dot = tag.lastIndexOf('.');
 495                  if (constructor === (dot >= 1 ? tag.slice(dot + 1) : tag)) return `${tag}${size} `;
 496                  return `${constructor}${size} [${tag}] `;
 497                }
 498                return `${constructor}${size} `;
 499              }
 500
 501              function getKeys(value, showHidden) {
 502                let keys;
 503                const symbols = Object.getOwnPropertySymbols(value);
 504                if (showHidden) {
 505                  keys = Object.getOwnPropertyNames(value);
 506                  if (symbols.length !== 0) keys.push(...symbols);
 507                } else {
 508                  keys = Object.keys(value);
 509                  if (symbols.length !== 0) keys.push(...symbols.filter((key) => Object.prototype.propertyIsEnumerable.call(value, key)));
 510                }
 511                return keys;
 512              }
 513
 514              function isIndex(key) {
 515                return typeof key === 'string' && numberRegExp.test(key) && Number(key) < 2 ** 32 - 1;
 516              }
 517
 518              function getOwnNonIndexProperties(value, showHidden) {
 519                const keys = Reflect.ownKeys(value).filter((key) => !isIndex(key) &&
 520                  (showHidden || Object.prototype.propertyIsEnumerable.call(value, key)));
 521                return [...keys.filter((key) => typeof key === 'string'), ...keys.filter((key) => typeof key === 'symbol')];
 522              }
 523
 524              function getCtxStyle(value, constructor, tag) {
 525                let fallback = '';
 526                if (constructor === null) {
 527                  fallback = internalGetConstructorName(value);
 528                  if (fallback === tag) fallback = 'Object';
 529                }
 530                return getPrefix(constructor, tag, fallback);
 531              }
 532
 533              function formatRaw(ctx, value, recurseTimes, typedArray) {
 534                let keys;
 535                let protoProps;
 536                if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) protoProps = [];
 537                const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
 538                if (protoProps !== undefined && protoProps.length === 0) protoProps = undefined;
 539                let tag = '';
 540                try { tag = value[Symbol.toStringTag]; } catch {}
 541                if (typeof tag !== 'string' || (tag !== '' && (ctx.showHidden ? Object.prototype.hasOwnProperty
 542                  : Object.prototype.propertyIsEnumerable).call(value, Symbol.toStringTag))) {
 543                  tag = '';
 544                }
 545                let base = '';
 546                let formatter = () => [];
 547                let braces;
 548                let noIterator = true;
 549                let extrasType = kObjectType;
 550                let extraKeys;
 551
 552                if (Symbol.iterator in value || constructor === null) {
 553                  noIterator = false;
 554                  if (Array.isArray(value)) {
 555                    const prefix = (constructor !== 'Array' || tag !== '') ? getPrefix(constructor, tag, 'Array', `(${value.length})`) : '';
 556                    keys = getOwnNonIndexProperties(value, ctx.showHidden);
 557                    braces = [`${prefix}[`, ']'];
 558                    if (value.length === 0 && keys.length === 0 && protoProps === undefined) return `${braces[0]}]`;
 559                    extrasType = kArrayExtrasType;
 560                    formatter = formatArray;
 561                  } else if (isSet(value)) {
 562                    const size = getter(Set.prototype, 'size').call(value);
 563                    const prefix = getPrefix(constructor, tag, 'Set', `(${size})`);
 564                    keys = getKeys(value, ctx.showHidden);
 565                    formatter = (ctx, v, recurseTimes) => formatSet(value, ctx, recurseTimes);
 566                    if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
 567                    braces = [`${prefix}{`, '}'];
 568                  } else if (isMap(value)) {
 569                    const size = getter(Map.prototype, 'size').call(value);
 570                    const prefix = getPrefix(constructor, tag, 'Map', `(${size})`);
 571                    keys = getKeys(value, ctx.showHidden);
 572                    formatter = (ctx, v, recurseTimes) => formatMap(value, ctx, recurseTimes);
 573                    if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
 574                    braces = [`${prefix}{`, '}'];
 575                  } else if (isTypedArray(value)) {
 576                    keys = getOwnNonIndexProperties(value, ctx.showHidden);
 577                    const fallback = constructor === null ? typedArrayTag.call(value) : '';
 578                    const size = getter(typedArrayProto, 'length').call(value);
 579                    const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
 580                    braces = [`${prefix}[`, ']'];
 581                    if (value.length === 0 && keys.length === 0 && !ctx.showHidden) return `${braces[0]}]`;
 582                    formatter = (ctx) => formatTypedArray(value, size, ctx);
 583                    extrasType = kArrayExtrasType;
 584                    if (ctx.showHidden) {
 585                      extraKeys = ['BYTES_PER_ELEMENT', 'length', 'byteLength', 'byteOffset', 'buffer'];
 586                      typedArray = true;
 587                    }
 588                  } else if (iteratorTags.includes(Object.prototype.toString.call(value))) {
 589                    refuse('util.inspect of an iterator');
 590                  } else {
 591                    noIterator = true;
 592                  }
 593                }
 594                if (noIterator) {
 595                  keys = getKeys(value, ctx.showHidden);
 596                  braces = ['{', '}'];
 597                  if (typeof value === 'function') {
 598                    base = getFunctionBase(ctx, value, constructor, tag);
 599                    if (keys.length === 0 && protoProps === undefined) return base;
 600                  } else if (constructor === 'Object') {
 601                    if (isArgumentsObject(value)) {
 602                      braces[0] = '[Arguments] {';
 603                    } else if (tag !== '') {
 604                      braces[0] = `${getPrefix(constructor, tag, 'Object')}{`;
 605                    }
 606                    if (keys.length === 0 && protoProps === undefined) return `${braces[0]}}`;
 607                  } else if (isRegExp(value)) {
 608                    base = RegExp.prototype.toString.call(constructor !== null ? value : new RegExp(value));
 609                    const prefix = getPrefix(constructor, tag, 'RegExp');
 610                    if (prefix !== 'RegExp ') base = `${prefix}${base}`;
 611                    if ((keys.length === 0 && protoProps === undefined) || (recurseTimes > ctx.depth && ctx.depth !== null)) return base;
 612                  } else if (isDate(value)) {
 613                    base = Number.isNaN(Date.prototype.getTime.call(value)) ? Date.prototype.toString.call(value) : Date.prototype.toISOString.call(value);
 614                    const prefix = getPrefix(constructor, tag, 'Date');
 615                    if (prefix !== 'Date ') base = `${prefix}${base}`;
 616                    if (keys.length === 0 && protoProps === undefined) return base;
 617                  } else if (isError(value)) {
 618                    refuse('util.inspect of an Error');
 619                  } else if (isArrayBuffer(value)) {
 620                    const prefix = getPrefix(constructor, tag, 'ArrayBuffer');
 621                    if (typedArray === undefined) {
 622                      formatter = formatArrayBuffer;
 623                    } else if (keys.length === 0 && protoProps === undefined) {
 624                      return prefix + `{ [byteLength]: ${formatNumber(value.byteLength, false)} }`;
 625                    }
 626                    braces[0] = `${prefix}{`;
 627                    extraKeys = ['byteLength'];
 628                  } else if (isDataView(value)) {
 629                    braces[0] = `${getPrefix(constructor, tag, 'DataView')}{`;
 630                    extraKeys = ['byteLength', 'byteOffset', 'buffer'];
 631                  } else if (isPromise(value)) {
 632                    refuse('util.inspect of a Promise');
 633                  } else if (isWeakSet(value) || isWeakMap(value)) {
 634                    if (ctx.showHidden) refuse('util.inspect of WeakMap or WeakSet entries');
 635                    braces[0] = `${getPrefix(constructor, tag, isWeakSet(value) ? 'WeakSet' : 'WeakMap')}{`;
 636                    formatter = () => ['<items unknown>'];
 637                  } else if (typeof value === 'object' && boxType(value)) {
 638                    base = getBoxedBase(value, ctx, keys, constructor, tag);
 639                    if (keys.length === 0 && protoProps === undefined) return base;
 640                  } else {
 641                    if (keys.length === 0 && protoProps === undefined) return `${getCtxStyle(value, constructor, tag)}{}`;
 642                    braces[0] = `${getCtxStyle(value, constructor, tag)}{`;
 643                  }
 644                }
 645
 646                if (recurseTimes > ctx.depth && ctx.depth !== null) {
 647                  let constructorName = getCtxStyle(value, constructor, tag).slice(0, -1);
 648                  if (constructor !== null) constructorName = `[${constructorName}]`;
 649                  return constructorName;
 650                }
 651                recurseTimes += 1;
 652                ctx.seen.push(value);
 653                ctx.currentDepth = recurseTimes;
 654                const output = formatter(ctx, value, recurseTimes);
 655                if (extraKeys !== undefined) {
 656                  for (const key of extraKeys) output.push(formatExtraProperties(ctx, value, recurseTimes, key, typedArray));
 657                }
 658                for (const key of keys) output.push(formatProperty(ctx, value, recurseTimes, key, extrasType));
 659                if (protoProps !== undefined) output.push(...protoProps);
 660                if (ctx.circular !== undefined) {
 661                  const index = ctx.circular.get(value);
 662                  if (index !== undefined) {
 663                    const reference = `<ref *${index}>`;
 664                    if (ctx.compact !== true) {
 665                      base = base === '' ? reference : `${reference} ${base}`;
 666                    } else {
 667                      braces[0] = `${reference} ${braces[0]}`;
 668                    }
 669                  }
 670                }
 671                ctx.seen.pop();
 672                if (ctx.sorted) {
 673                  const comparator = ctx.sorted === true ? undefined : ctx.sorted;
 674                  if (extrasType === kObjectType) {
 675                    output.sort(comparator);
 676                  } else if (keys.length > 1) {
 677                    const sorted = output.slice(output.length - keys.length).sort(comparator);
 678                    output.splice(output.length - keys.length, keys.length, ...sorted);
 679                  }
 680                }
 681                const res = reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value);
 682                const newLength = (ctx.budget[ctx.indentationLvl] || 0) + res.length;
 683                ctx.budget[ctx.indentationLvl] = newLength;
 684                if (newLength > 2 ** 27) ctx.depth = -1;
 685                return res;
 686              }
 687
 688              function getBoxedBase(value, ctx, keys, constructor, tag) {
 689                const [type, fn] = boxType(value);
 690                if (type === 'String') keys.splice(0, value.length);
 691                let base = `[${type}`;
 692                if (type !== constructor) base += constructor === null ? ' (null prototype)' : ` (${constructor})`;
 693                base += `: ${formatPrimitive(fn.call(value), ctx)}]`;
 694                if (tag !== '' && tag !== constructor) base += ` [${tag}]`;
 695                return base;
 696              }
 697
 698              function getClassBase(value, constructor, tag) {
 699                const hasName = Object.prototype.hasOwnProperty.call(value, 'name');
 700                const name = (hasName && value.name) || '(anonymous)';
 701                let base = `class ${name}`;
 702                if (constructor !== 'Function' && constructor !== null) base += ` [${constructor}]`;
 703                if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
 704                if (constructor !== null) {
 705                  const superName = Object.getPrototypeOf(value).name;
 706                  if (superName) base += ` extends ${superName}`;
 707                } else {
 708                  base += ' extends [null prototype]';
 709                }
 710                return `[${base}]`;
 711              }
 712
 713              function getFunctionBase(ctx, value, constructor, tag) {
 714                const stringified = functionToString.call(value);
 715                if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') {
 716                  const slice = stringified.slice(5, -1);
 717                  const bracketIndex = slice.indexOf('{');
 718                  if (bracketIndex !== -1 && (!slice.slice(0, bracketIndex).includes('(') ||
 719                      classRegExp.exec(slice.replace(stripCommentsRegExp, '')) !== null)) {
 720                    return getClassBase(value, constructor, tag);
 721                  }
 722                }
 723                const proto = Object.getPrototypeOf(value);
 724                let type = 'Function';
 725                if (proto === generatorFunctionProto || proto === asyncGeneratorFunctionProto) type = `Generator${type}`;
 726                if (proto === asyncFunctionProto || proto === asyncGeneratorFunctionProto) type = `Async${type}`;
 727                let base = `[${type}`;
 728                if (constructor === null) base += ' (null prototype)';
 729                if (value.name === '') {
 730                  base += ' (anonymous)';
 731                } else {
 732                  base += `: ${typeof value.name === 'string' ? value.name : formatValue(ctx, value.name)}`;
 733                }
 734                base += ']';
 735                if (constructor !== type && constructor !== null) base += ` ${constructor}`;
 736                if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
 737                return base;
 738              }
 739
 740              function addQuotes(str, quotes) {
 741                if (quotes === -1) return `"${str}"`;
 742                if (quotes === -2) return `\`${str}\``;
 743                return `'${str}'`;
 744              }
 745
 746              function escapeFn(str) {
 747                const charCode = str.charCodeAt(0);
 748                return meta.length > charCode ? meta[charCode] : `\\u${charCode.toString(16)}`;
 749              }
 750
 751              function strEscape(str) {
 752                let escapeTest = strEscapeSequencesRegExp;
 753                let escapeReplace = strEscapeSequencesReplacer;
 754                let singleQuote = 39;
 755                if (str.includes("'")) {
 756                  if (!str.includes('"')) {
 757                    singleQuote = -1;
 758                  } else if (!str.includes('`') && !str.includes('${')) {
 759                    singleQuote = -2;
 760                  }
 761                  if (singleQuote !== 39) {
 762                    escapeTest = strEscapeSequencesRegExpSingle;
 763                    escapeReplace = strEscapeSequencesReplacerSingle;
 764                  }
 765                }
 766                if (str.length < 5000 && escapeTest.exec(str) === null) return addQuotes(str, singleQuote);
 767                if (str.length > 100) {
 768                  str = str.replace(escapeReplace, escapeFn);
 769                  return addQuotes(str, singleQuote);
 770                }
 771                let result = '';
 772                let last = 0;
 773                for (let i = 0; i < str.length; i++) {
 774                  const point = str.charCodeAt(i);
 775                  if (point === singleQuote || point === 92 || point < 32 || (point > 126 && point < 160)) {
 776                    result += last === i ? meta[point] : `${str.slice(last, i)}${meta[point]}`;
 777                    last = i + 1;
 778                  } else if (point >= 0xd800 && point <= 0xdfff) {
 779                    if (point <= 0xdbff && i + 1 < str.length) {
 780                      const next = str.charCodeAt(i + 1);
 781                      if (next >= 0xdc00 && next <= 0xdfff) {
 782                        i++;
 783                        continue;
 784                      }
 785                    }
 786                    result += `${str.slice(last, i)}\\u${point.toString(16)}`;
 787                    last = i + 1;
 788                  }
 789                }
 790                if (last !== str.length) result += str.slice(last);
 791                return addQuotes(result, singleQuote);
 792              }
 793
 794              function addNumericSeparator(integerString) {
 795                let result = '';
 796                let i = integerString.length;
 797                const start = integerString[0] === '-' ? 1 : 0;
 798                for (; i >= start + 4; i -= 3) result = `_${integerString.slice(i - 3, i)}${result}`;
 799                return i === integerString.length ? integerString : `${integerString.slice(0, i)}${result}`;
 800              }
 801
 802              function addNumericSeparatorEnd(integerString) {
 803                let result = '';
 804                let i = 0;
 805                for (; i < integerString.length - 3; i += 3) result += `${integerString.slice(i, i + 3)}_`;
 806                return i === 0 ? integerString : `${result}${integerString.slice(i)}`;
 807              }
 808
 809              const remainingText = (remaining) => `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
 810
 811              function formatNumber(number, numericSeparator) {
 812                if (Object.is(number, -0)) return '-0';
 813                if (!numericSeparator) return `${number}`;
 814                const numberString = String(number);
 815                const integer = Math.trunc(number);
 816                if (integer === number) {
 817                  if (!Number.isFinite(number) || numberString.includes('e')) return numberString;
 818                  return addNumericSeparator(numberString);
 819                }
 820                if (Number.isNaN(number) || numberString.includes('e')) return numberString;
 821                const decimalIndex = numberString.indexOf('.');
 822                return `${addNumericSeparator(numberString.slice(0, decimalIndex))}.${addNumericSeparatorEnd(numberString.slice(decimalIndex + 1))}`;
 823              }
 824
 825              function formatBigInt(bigint, numericSeparator) {
 826                const string = String(bigint);
 827                return numericSeparator ? `${addNumericSeparator(string)}n` : `${string}n`;
 828              }
 829
 830              function formatPrimitive(value, ctx) {
 831                if (typeof value === 'string') {
 832                  let trailer = '';
 833                  if (value.length > ctx.maxStringLength) {
 834                    const remaining = value.length - ctx.maxStringLength;
 835                    value = value.slice(0, ctx.maxStringLength);
 836                    trailer = `... ${remaining} more character${remaining > 1 ? 's' : ''}`;
 837                  }
 838                  if (ctx.compact !== true && value.length > kMinLineLength && value.length > ctx.breakLength - ctx.indentationLvl - 4) {
 839                    return value.split(/(?<=\n)/).map((line) => strEscape(line)).join(` +\n${' '.repeat(ctx.indentationLvl + 2)}`) + trailer;
 840                  }
 841                  return strEscape(value) + trailer;
 842                }
 843                if (typeof value === 'number') return formatNumber(value, ctx.numericSeparator);
 844                if (typeof value === 'bigint') return formatBigInt(value, ctx.numericSeparator);
 845                if (typeof value === 'boolean') return `${value}`;
 846                if (typeof value === 'undefined') return 'undefined';
 847                return Symbol.prototype.toString.call(value);
 848              }
 849
 850              function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) {
 851                const keys = Object.keys(value);
 852                let index = i;
 853                for (; i < keys.length && output.length < maxLength; i++) {
 854                  const key = keys[i];
 855                  const tmp = +key;
 856                  if (tmp > 2 ** 32 - 2) break;
 857                  if (`${index}` !== key) {
 858                    if (numberRegExp.exec(key) === null) break;
 859                    const emptyItems = tmp - index;
 860                    output.push(`<${emptyItems} empty item${emptyItems > 1 ? 's' : ''}>`);
 861                    index = tmp;
 862                    if (output.length === maxLength) break;
 863                  }
 864                  output.push(formatProperty(ctx, value, recurseTimes, key, kArrayType));
 865                  index++;
 866                }
 867                const remaining = value.length - index;
 868                if (output.length !== maxLength) {
 869                  if (remaining > 0) output.push(`<${remaining} empty item${remaining > 1 ? 's' : ''}>`);
 870                } else if (remaining > 0) {
 871                  output.push(remainingText(remaining));
 872                }
 873                return output;
 874              }
 875
 876              function formatArrayBuffer(ctx, value) {
 877                const buffer = new Uint8Array(value);
 878                const shown = Array.from(buffer.subarray(0, Math.min(ctx.maxArrayLength, buffer.length)), (b) => b.toString(16).padStart(2, '0'));
 879                let str = shown.join(' ');
 880                const remaining = buffer.length - ctx.maxArrayLength;
 881                if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
 882                return [`[Uint8Contents]: <${str}>`];
 883              }
 884
 885              function formatArray(ctx, value, recurseTimes) {
 886                const valLen = value.length;
 887                const len = Math.min(Math.max(0, ctx.maxArrayLength), valLen);
 888                const remaining = valLen - len;
 889                const output = [];
 890                for (let i = 0; i < len; i++) {
 891                  const desc = Object.getOwnPropertyDescriptor(value, i);
 892                  if (desc === undefined) return formatSpecialArray(ctx, value, recurseTimes, len, output, i);
 893                  output.push(formatProperty(ctx, value, recurseTimes, i, kArrayType, desc));
 894                }
 895                if (remaining > 0) output.push(remainingText(remaining));
 896                return output;
 897              }
 898
 899              function formatTypedArray(value, length, ctx) {
 900                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 901                const remaining = value.length - maxLength;
 902                const output = new Array(maxLength);
 903                const elementFormatter = value.length > 0 && typeof value[0] === 'number' ? formatNumber : formatBigInt;
 904                for (let i = 0; i < maxLength; ++i) output[i] = elementFormatter(value[i], ctx.numericSeparator);
 905                if (remaining > 0) output[maxLength] = remainingText(remaining);
 906                return output;
 907              }
 908
 909              function formatSet(value, ctx, recurseTimes) {
 910                const length = value.size;
 911                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 912                const remaining = length - maxLength;
 913                const output = [];
 914                ctx.indentationLvl += 2;
 915                let i = 0;
 916                for (const v of Set.prototype.values.call(value)) {
 917                  if (i >= maxLength) break;
 918                  output.push(formatValue(ctx, v, recurseTimes));
 919                  i++;
 920                }
 921                if (remaining > 0) output.push(remainingText(remaining));
 922                ctx.indentationLvl -= 2;
 923                return output;
 924              }
 925
 926              function formatMap(value, ctx, recurseTimes) {
 927                const length = value.size;
 928                const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
 929                const remaining = length - maxLength;
 930                const output = [];
 931                ctx.indentationLvl += 2;
 932                let i = 0;
 933                for (const { 0: k, 1: v } of Map.prototype.entries.call(value)) {
 934                  if (i >= maxLength) break;
 935                  output.push(`${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`);
 936                  i++;
 937                }
 938                if (remaining > 0) output.push(remainingText(remaining));
 939                ctx.indentationLvl -= 2;
 940                return output;
 941              }
 942
 943              function formatExtraProperties(ctx, value, recurseTimes, key, typedArray) {
 944                const extraValue = value[key];
 945                ctx.indentationLvl += 2;
 946                const str = formatValue(ctx, extraValue, recurseTimes, typedArray);
 947                ctx.indentationLvl -= 2;
 948                return `[${key}]: ${str}`;
 949              }
 950
 951              function formatProperty(ctx, value, recurseTimes, key, type, desc, original = value) {
 952                let name, str;
 953                let extra = ' ';
 954                desc ??= Object.getOwnPropertyDescriptor(value, key);
 955                if (desc.value !== undefined) {
 956                  const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3;
 957                  ctx.indentationLvl += diff;
 958                  str = formatValue(ctx, desc.value, recurseTimes);
 959                  if (diff === 3 && ctx.breakLength < getStringWidth(str)) extra = `\n${' '.repeat(ctx.indentationLvl)}`;
 960                  ctx.indentationLvl -= diff;
 961                } else if (desc.get !== undefined) {
 962                  const label = desc.set !== undefined ? 'Getter/Setter' : 'Getter';
 963                  if (ctx.getters && (ctx.getters === true || (ctx.getters === 'get' && desc.set === undefined) ||
 964                      (ctx.getters === 'set' && desc.set !== undefined))) {
 965                    ctx.indentationLvl += 2;
 966                    try {
 967                      const tmp = desc.get.call(original);
 968                      if (tmp === null) {
 969                        str = `[${label}: null]`;
 970                      } else if (typeof tmp === 'object' || typeof tmp === 'function') {
 971                        str = `[${label}] ${formatValue(ctx, tmp, recurseTimes)}`;
 972                      } else {
 973                        str = `[${label}: ${formatPrimitive(tmp, ctx)}]`;
 974                      }
 975                    } catch (err) {
 976                      str = `[${label}: <Inspection threw (${formatValue(ctx, err, recurseTimes)})>]`;
 977                    }
 978                    ctx.indentationLvl -= 2;
 979                  } else {
 980                    str = `[${label}]`;
 981                  }
 982                } else if (desc.set !== undefined) {
 983                  str = '[Setter]';
 984                } else {
 985                  str = 'undefined';
 986                }
 987                if (type === kArrayType) return str;
 988                if (typeof key === 'symbol') {
 989                  name = Symbol.prototype.toString.call(key).replace(strEscapeSequencesReplacer, escapeFn);
 990                } else if (keyStrRegExp.exec(key) !== null) {
 991                  name = key === '__proto__' ? "['__proto__']" : key;
 992                } else {
 993                  name = strEscape(key);
 994                }
 995                if (desc.enumerable === false) name = `[${name}]`;
 996                return `${name}:${extra}${str}`;
 997              }
 998
 999              function groupArrayElements(ctx, output, value) {
1000                let totalLength = 0;
1001                let maxLength = 0;
1002                let i = 0;
1003                let outputLength = output.length;
1004                if (ctx.maxArrayLength < output.length) outputLength--;
1005                const separatorSpace = 2;
1006                const dataLen = new Array(outputLength);
1007                for (; i < outputLength; i++) {
1008                  const len = getStringWidth(output[i]);
1009                  dataLen[i] = len;
1010                  totalLength += len + separatorSpace;
1011                  if (maxLength < len) maxLength = len;
1012                }
1013                const actualMax = maxLength + separatorSpace;
1014                if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength && (totalLength / actualMax > 5 || maxLength <= 6)) {
1015                  const approxCharHeights = 2.5;
1016                  const averageBias = Math.sqrt(actualMax - totalLength / output.length);
1017                  const biasedMax = Math.max(actualMax - 3 - averageBias, 1);
1018                  const columns = Math.min(
1019                    Math.round(Math.sqrt(approxCharHeights * biasedMax * outputLength) / biasedMax),
1020                    Math.floor((ctx.breakLength - ctx.indentationLvl) / actualMax),
1021                    ctx.compact * 4,
1022                    15,
1023                  );
1024                  if (columns <= 1) return output;
1025                  const tmp = [];
1026                  const maxLineLength = [];
1027                  for (let i = 0; i < columns; i++) {
1028                    let lineMaxLength = 0;
1029                    for (let j = i; j < output.length; j += columns) {
1030                      if (dataLen[j] > lineMaxLength) lineMaxLength = dataLen[j];
1031                    }
1032                    maxLineLength[i] = lineMaxLength + separatorSpace;
1033                  }
1034                  let padStart = true;
1035                  if (value !== undefined) {
1036                    for (let i = 0; i < output.length; i++) {
1037                      if (typeof value[i] !== 'number' && typeof value[i] !== 'bigint') {
1038                        padStart = false;
1039                        break;
1040                      }
1041                    }
1042                  }
1043                  for (let i = 0; i < outputLength; i += columns) {
1044                    const max = Math.min(i + columns, outputLength);
1045                    let str = '';
1046                    let j = i;
1047                    for (; j < max - 1; j++) {
1048                      const padding = maxLineLength[j - i] + output[j].length - dataLen[j];
1049                      str += padStart ? `${output[j]}, `.padStart(padding, ' ') : `${output[j]}, `.padEnd(padding, ' ');
1050                    }
1051                    if (padStart) {
1052                      str += output[j].padStart(maxLineLength[j - i] + output[j].length - dataLen[j] - separatorSpace, ' ');
1053                    } else {
1054                      str += output[j];
1055                    }
1056                    tmp.push(str);
1057                  }
1058                  if (ctx.maxArrayLength < output.length) tmp.push(output[outputLength]);
1059                  output = tmp;
1060                }
1061                return output;
1062              }
1063
1064              function isBelowBreakLength(ctx, output, start, base) {
1065                if (ctx.breakLength === Infinity) {
1066                  if (base !== '' && base.includes('\n')) return false;
1067                  return !output.some((entry) => typeof entry === 'string' && entry.includes('\n'));
1068                }
1069                let totalLength = output.length + start;
1070                if (totalLength + output.length > ctx.breakLength) return false;
1071                for (let i = 0; i < output.length; i++) {
1072                  totalLength += output[i].length;
1073                  if (totalLength > ctx.breakLength) return false;
1074                }
1075                return base === '' || !base.includes('\n');
1076              }
1077
1078              function reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value) {
1079                if (ctx.compact !== true) {
1080                  if (typeof ctx.compact === 'number' && ctx.compact >= 1) {
1081                    const entries = output.length;
1082                    if (extrasType === kArrayExtrasType && entries > 6) output = groupArrayElements(ctx, output, value);
1083                    if (ctx.currentDepth - recurseTimes < ctx.compact && entries === output.length) {
1084                      const start = output.length + ctx.indentationLvl + braces[0].length + base.length + 10;
1085                      if (isBelowBreakLength(ctx, output, start, base)) {
1086                        const joinedOutput = output.join(', ');
1087                        if (!joinedOutput.includes('\n')) return `${base ? `${base} ` : ''}${braces[0]} ${joinedOutput}` + ` ${braces[1]}`;
1088                      }
1089                    }
1090                  }
1091                  const indentation = `\n${' '.repeat(ctx.indentationLvl)}`;
1092                  return `${base ? `${base} ` : ''}${braces[0]}${indentation}  ${output.join(`,${indentation}  `)}${indentation}${braces[1]}`;
1093                }
1094                if (isBelowBreakLength(ctx, output, 0, base)) return `${braces[0]}${base ? ` ${base}` : ''} ${output.join(', ')} ` + braces[1];
1095                const indentation = ' '.repeat(ctx.indentationLvl);
1096                const ln = base === '' && braces[0].length === 1 ? ' ' : `${base ? ` ${base}` : ''}\n${indentation}  `;
1097                return `${braces[0]}${ln}${output.join(`,\n${indentation}  `)} ${braces[1]}`;
1098              }
1099
1100              function hasBuiltInToString(value) {
1101                let hasOwnToString = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1102                let hasOwnToPrimitive = hasOwnToString;
1103                if (typeof value.toString !== 'function') {
1104                  if (typeof value[Symbol.toPrimitive] !== 'function') return true;
1105                  if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) return false;
1106                  hasOwnToString = () => false;
1107                } else if (Object.prototype.hasOwnProperty.call(value, 'toString')) {
1108                  return false;
1109                } else if (typeof value[Symbol.toPrimitive] !== 'function') {
1110                  hasOwnToPrimitive = () => false;
1111                } else if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) {
1112                  return false;
1113                }
1114                let pointer = value;
1115                do {
1116                  pointer = Object.getPrototypeOf(pointer);
1117                } while (!hasOwnToString(pointer, 'toString') && !hasOwnToPrimitive(pointer, Symbol.toPrimitive));
1118                const descriptor = Object.getOwnPropertyDescriptor(pointer, 'constructor');
1119                return descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name);
1120              }
1121
1122              let circularErrorMessage;
1123              function tryStringify(arg) {
1124                try {
1125                  return JSON.stringify(arg);
1126                } catch (err) {
1127                  if (!circularErrorMessage) {
1128                    try {
1129                      const a = {};
1130                      a.a = a;
1131                      JSON.stringify(a);
1132                    } catch (circularError) {
1133                      circularErrorMessage = circularError.message.split('\n', 1)[0];
1134                    }
1135                  }
1136                  if (err.name === 'TypeError' && err.message.split('\n', 1)[0] === circularErrorMessage) return '[Circular]';
1137                  throw err;
1138                }
1139              }
1140
1141              function formatWithOptions(inspectOptions, args) {
1142                const first = args[0];
1143                let a = 0;
1144                let str = '';
1145                let join = '';
1146                if (typeof first === 'string') {
1147                  if (args.length === 1) return first;
1148                  let tempStr;
1149                  let lastPos = 0;
1150                  for (let i = 0; i < first.length - 1; i++) {
1151                    if (first.charCodeAt(i) === 37) {
1152                      const nextChar = first.charCodeAt(++i);
1153                      if (a + 1 !== args.length) {
1154                        switch (nextChar) {
1155                          case 115: {
1156                            const tempArg = args[++a];
1157                            if (typeof tempArg === 'number') {
1158                              tempStr = formatNumber(tempArg, inspectOptions?.numericSeparator);
1159                            } else if (typeof tempArg === 'bigint') {
1160                              tempStr = formatBigInt(tempArg, inspectOptions?.numericSeparator);
1161                            } else if (typeof tempArg !== 'object' || tempArg === null || !hasBuiltInToString(tempArg)) {
1162                              tempStr = String(tempArg);
1163                            } else {
1164                              tempStr = inspect(tempArg, { ...inspectOptions, compact: 3, colors: false, depth: 0 });
1165                            }
1166                            break;
1167                          }
1168                          case 106:
1169                            tempStr = tryStringify(args[++a]);
1170                            break;
1171                          case 100: {
1172                            const tempNum = args[++a];
1173                            if (typeof tempNum === 'bigint') tempStr = formatBigInt(tempNum, inspectOptions?.numericSeparator);
1174                            else if (typeof tempNum === 'symbol') tempStr = 'NaN';
1175                            else tempStr = formatNumber(Number(tempNum), inspectOptions?.numericSeparator);
1176                            break;
1177                          }
1178                          case 79:
1179                            tempStr = inspect(args[++a], inspectOptions);
1180                            break;
1181                          case 111:
1182                            tempStr = inspect(args[++a], { ...inspectOptions, showHidden: true, showProxy: true, depth: 4 });
1183                            break;
1184                          case 105: {
1185                            const tempInteger = args[++a];
1186                            if (typeof tempInteger === 'bigint') tempStr = formatBigInt(tempInteger, inspectOptions?.numericSeparator);
1187                            else if (typeof tempInteger === 'symbol') tempStr = 'NaN';
1188                            else tempStr = formatNumber(Number.parseInt(tempInteger), inspectOptions?.numericSeparator);
1189                            break;
1190                          }
1191                          case 102: {
1192                            const tempFloat = args[++a];
1193                            if (typeof tempFloat === 'symbol') tempStr = 'NaN';
1194                            else tempStr = formatNumber(Number.parseFloat(tempFloat), inspectOptions?.numericSeparator);
1195                            break;
1196                          }
1197                          case 99:
1198                            a += 1;
1199                            tempStr = '';
1200                            break;
1201                          case 37:
1202                            str += first.slice(lastPos, i);
1203                            lastPos = i + 1;
1204                            continue;
1205                          default:
1206                            continue;
1207                        }
1208                        if (lastPos !== i - 1) str += first.slice(lastPos, i - 1);
1209                        str += tempStr;
1210                        lastPos = i + 1;
1211                      } else if (nextChar === 37) {
1212                        str += first.slice(lastPos, i);
1213                        lastPos = i + 1;
1214                      }
1215                    }
1216                  }
1217                  if (lastPos !== 0) {
1218                    a++;
1219                    join = ' ';
1220                    if (lastPos < first.length) str += first.slice(lastPos);
1221                  }
1222                }
1223                while (a < args.length) {
1224                  const value = args[a];
1225                  str += join;
1226                  str += typeof value !== 'string' ? inspect(value, inspectOptions) : value;
1227                  join = ' ';
1228                  a++;
1229                }
1230                return str;
1231              }
1232
1233              // Node's globals, as far as they go without files, processes or the network.
1234              function stream(fd, name) {
1235                return guard({
1236                  write(chunk, ...rest) {
1237                    if (typeof chunk !== 'string' || rest.length !== 0) refuse(`${name}.write with anything but text`);
1238                    out(fd, chunk);
1239                    return true;
1240                  },
1241                }, name);
1242              }
1243              const process = guard({ stdout: stream(1, 'process.stdout'), stderr: stream(2, 'process.stderr'), [Symbol.toStringTag]: 'process' }, 'process');
1244              const util = guard({
1245                inspect,
1246                format: (...args) => formatWithOptions(undefined, args),
1247                formatWithOptions: (options, ...args) => formatWithOptions(options, args),
1248              }, 'util');
1249              const modules = { process, util };
1250              const require = guard(function require(id) {
1251                const name = typeof id === 'string' && id.startsWith('node:') ? id.slice(5) : id;
1252                if (Object.prototype.hasOwnProperty.call(modules, name)) return modules[name];
1253                const error = new Error(`Cannot find module '${id}'`);
1254                error.code = 'MODULE_NOT_FOUND';
1255                throw error;
1256              }, 'require', ['call', 'apply', 'bind']);
1257              const print = (fd) => (...args) => out(fd, formatWithOptions(undefined, args) + '\n');
1258              const console = guard({
1259                log: print(1), info: print(1), debug: print(1), warn: print(2), error: print(2),
1260                dir(object, options) { out(1, inspect(object, { customInspect: false, ...options }) + '\n'); },
1261                [Symbol.toStringTag]: 'console',
1262              }, 'console');
1263
1264              // Timers run after the script, in order of when they are due, as Node's event loop runs them.
1265              class Timeout {
1266                constructor(timer) { this[timerKey] = timer; }
1267                ref() { this[timerKey].ref = true; return this; }
1268                unref() { this[timerKey].ref = false; return this; }
1269                hasRef() { return this[timerKey].ref; }
1270                [Symbol.toPrimitive]() { return this[timerKey].id; }
1271                [customInspectSymbol]() { refuse('util.inspect of a Timeout'); }
1272              }
1273              const timerKey = Symbol('timer');
1274              function schedule(callback, delay, args, repeat) {
1275                if (typeof callback !== 'function') {
1276                  const error = new TypeError(`The "callback" argument must be of type function. Received ${inspect(callback)}`);
1277                  error.code = 'ERR_INVALID_ARG_TYPE';
1278                  throw error;
1279                }
1280                delay *= 1;
1281                if (!(delay >= 1 && delay <= 2 ** 31 - 1)) delay = 1;
1282                const timer = { id: ++state.seq, seq: state.seq, due: state.now + delay, delay, callback, args, repeat, ref: true };
1283                timer.timeout = new Timeout(timer);
1284                state.timers.push(timer);
1285                return timer.timeout;
1286              }
1287              function clear(timeout) {
1288                const timer = timeout && typeof timeout === 'object' ? timeout[timerKey]
1289                  : state.timers.find((t) => t.id === Number(timeout));
1290                state.timers = state.timers.filter((t) => t !== timer);
1291              }
1292              function uncaught(error) {
1293                if (state.draining) {
1294                  if (!state.refused) state.refused = lateInSession;
1295                  return;
1296                }
1297                if (state.error === undefined) state.error = describe(error);
1298                state.dead = true;
1299              }
1300              function describe(error) {
1301                if (error instanceof Error) {
1302                  let message = String(error.message);
1303                  const missing = /^Can't find variable: (.*)$/.exec(message);
1304                  if (error.name === 'ReferenceError' && missing) message = `${missing[1]} is not defined`;
1305                  return message === '' ? String(error.name) : `${error.name}: ${message}`;
1306                }
1307                try { return `Uncaught ${inspect(error)}`; } catch { return 'Uncaught exception'; }
1308              }
1309
1310              const AsyncFunction = (async function () {}).constructor;
1311              // A script that doesn't parse, which node may run as an ES module. Any `import` or `export`
1312              // counts, even in a string or comment.
1313              function moduleOnly(source) {
1314                if (/\b(import|export)\b/.test(source)) return true;
1315                try { new AsyncFunction(source); } catch { return false; }
1316                try { new Function(source); return false; } catch { return true; }
1317              }
1318              // `import()`, which parses in a script and never settles here.
1319              const dynamicImport = /(?<![\w$.])import\s*(\(|\/[*\/])/;
1320
1321              const module = guard({ exports: {} }, 'module');
1322              const globals = {
1323                console, process, global: globalThis, Proxy: ProxyConstructor,
1324                setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false),
1325                setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true),
1326                clearTimeout: clear, clearInterval: clear,
1327                queueMicrotask(callback) {
1328                  if (typeof callback !== 'function') throw new TypeError('The "callback" argument must be of type function.');
1329                  Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } });
1330                },
1331              };
1332              // A promise callback that throws after a session's block ends its session in node.
1333              const then = Promise.prototype.then;
1334              const late = (callback) => typeof callback !== 'function' ? callback : function (value) {
1335                try {
1336                  return callback(value);
1337                } catch (error) {
1338                  if (state.draining && !state.refused) state.refused = lateInSession;
1339                  throw error;
1340                }
1341              };
1342              Object.defineProperty(Promise.prototype, 'then', {
1343                value: { then(onFulfilled, onRejected) { return then.call(this, late(onFulfilled), late(onRejected)); } }.then,
1344                writable: true, configurable: true,
1345              });
1346              // Node's enumerable globals, in node's order; `node -e` adds a module's names after them.
1347              const enumerable = [
1348                'global', 'clearImmediate', 'setImmediate', 'clearInterval', 'clearTimeout', 'setInterval', 'setTimeout',
1349                'queueMicrotask', 'structuredClone', 'atob', 'btoa', 'performance', 'fetch', 'crypto', 'navigator', 'sessionStorage',
1350              ];
1351              const moduleScope = session ? { __filename: '[eval]', module, exports: module.exports, __dirname: '.', require } : {};
1352              for (const name of enumerable) {
1353                if (Object.prototype.hasOwnProperty.call(globals, name)) {
1354                  Object.defineProperty(globalThis, name, { value: globals[name], writable: true, configurable: true, enumerable: true });
1355                } else {
1356                  Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true, enumerable: true });
1357                }
1358              }
1359              for (const [name, value] of Object.entries(moduleScope)) {
1360                Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: true });
1361              }
1362              for (const [name, value] of Object.entries(globals)) {
1363                if (!enumerable.includes(name)) Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
1364              }
1365              // Node 26's other globals that JavaScriptCore lacks.
1366              for (const name of [
1367                'AbortController', 'AbortSignal', 'AsyncDisposableStack', 'atob', 'Blob', 'BroadcastChannel', 'btoa', 'Buffer',
1368                'ByteLengthQueuingStrategy', 'clearImmediate', 'CloseEvent', 'CompressionStream', 'CountQueuingStrategy', 'Crypto',
1369                'crypto', 'CryptoKey', 'CustomEvent', 'DecompressionStream', 'DisposableStack', 'DOMException', 'ErrorEvent', 'Event',
1370                'EventTarget', 'fetch', 'File', 'FormData', 'Headers', 'localStorage', 'MessageChannel', 'MessageEvent', 'MessagePort',
1371                'Navigator', 'navigator', 'Performance', 'performance', 'PerformanceEntry', 'PerformanceMark', 'PerformanceMeasure',
1372                'PerformanceObserver', 'PerformanceObserverEntryList', 'PerformanceResourceTiming', 'QuotaExceededError',
1373                'ReadableByteStreamController', 'ReadableStream', 'ReadableStreamBYOBReader', 'ReadableStreamBYOBRequest',
1374                'ReadableStreamDefaultController', 'ReadableStreamDefaultReader', 'Request', 'Response', 'sessionStorage',
1375                'setImmediate', 'SharedArrayBuffer', 'Storage', 'structuredClone', 'SubtleCrypto', 'SuppressedError', 'Temporal',
1376                'TextDecoder', 'TextDecoderStream', 'TextEncoder', 'TextEncoderStream', 'TransformStream',
1377                'TransformStreamDefaultController', 'URL', 'URLPattern', 'URLSearchParams', 'WebSocket', 'WritableStream',
1378                'WritableStreamDefaultController', 'WritableStreamDefaultWriter'
1379              ]) {
1380                if (!(name in globalThis)) {
1381                  Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true });
1382                }
1383              }
1384
1385              // JavaScriptCore's stack text isn't V8's, so errors get none and reading one is refused. In
1386              // node an error's own keys include `stack`.
1387              Error.stackTraceLimit = 0;
1388              const refusing = (name) => ({ get() { refuse(name); }, set() { refuse(name); }, configurable: true });
1389              Object.defineProperty(Error, 'stackTraceLimit', { ...refusing('Error.stackTraceLimit'), enumerable: true });
1390              Object.defineProperty(Error, 'captureStackTrace', refusing('Error.captureStackTrace'));
1391              Object.defineProperty(Error.prototype, 'stack', {
1392                get() { refuse('Error.stack'); },
1393                set(value) { Object.defineProperty(this, 'stack', { value, writable: true, configurable: true }); },
1394                configurable: true,
1395              });
1396              const errorLike = (v) => v === Error.prototype || isError(v);
1397              // Calls `test` refuses, with what they use.
1398              function refuseCalls(object, name, test) {
1399                object[name] = new RealProxy(object[name], {
1400                  apply(target, self, args) {
1401                    const what = test(self, args);
1402                    if (what) refuse(what);
1403                    return Reflect.apply(target, self, args);
1404                  },
1405                });
1406              }
1407              const errors = "an error's own properties";
1408              // The global object behind the script's proxies. Its enumerable names are node's, but
1409              // the order of all of them is JavaScriptCore's.
1410              const isGlobal = (v) => {
1411                for (let p = proxies.get(v); p; p = proxies.get(v)) v = p[0];
1412                return v === globalThis;
1413              };
1414              const listing = (v) => isGlobal(v) ? "a list of the global object's properties" : '';
1415              for (const [object, name] of [[Object, 'getOwnPropertyNames'], [Object, 'getOwnPropertyDescriptors'], [Reflect, 'ownKeys']]) {
1416                refuseCalls(object, name, (self, [v]) => listing(v) || (errorLike(v) ? errors : ''));
1417              }
1418              refuseCalls(Object, 'getOwnPropertySymbols', (self, [v]) => listing(v));
1419              // A session's `var`s come first in JavaScriptCore and last in node.
1420              if (session) refuseCalls(Object, 'keys', (self, [v]) => listing(v));
1421              const sessionListing = /\bfor\s*\([^)]*\bin\s+(globalThis|global|this)\s*\)/;
1422              for (const [object, name] of [[Object, 'getOwnPropertyDescriptor'], [Object, 'hasOwn'], [Reflect, 'getOwnPropertyDescriptor']]) {
1423                refuseCalls(object, name, (self, [v, key]) => key === 'stack' && errorLike(v) ? errors : '');
1424              }
1425              for (const name of ['hasOwnProperty', 'propertyIsEnumerable']) {
1426                refuseCalls(Object.prototype, name, (self, [key]) => key === 'stack' && errorLike(self) ? errors : '');
1427              }
1428              // A built-in function's text is laid out differently from V8's, and the functions here
1429              // are native in node.
1430              const shimText = functionToString.call(shim);
1431              refuseCalls(Function.prototype, 'toString', (self) => {
1432                let text;
1433                try { text = functionToString.call(self); } catch { return ''; }
1434                return /\[native code\]\s*\}$/.test(text) || shimText.includes(text) ? "a built-in function's source text" : '';
1435              });
1436
1437              return {
1438                // A script run as `node` runs a CommonJS file; an uncaught error ends it. `__filename`
1439                // and `__dirname` name Emacs's temporary file.
1440                main(source) {
1441                  if (/\b__(filename|dirname)\b/.test(source)) {
1442                    state.refused = '__filename or __dirname';
1443                    return;
1444                  }
1445                  if (dynamicImport.test(source)) {
1446                    state.refused = 'top-level await, import or export';
1447                    return;
1448                  }
1449                  let body;
1450                  try {
1451                    body = new Function('exports', 'require', 'module', '__filename', '__dirname', source);
1452                  } catch (error) {
1453                    // node runs a script that doesn't parse as one as an ES module, when that parses.
1454                    if (error instanceof SyntaxError && moduleOnly(source)) state.refused = 'top-level await, import or export';
1455                    else uncaught(error);
1456                    return;
1457                  }
1458                  try {
1459                    body.call(module.exports, module.exports, require, module, undefined, undefined);
1460                  } catch (error) {
1461                    uncaught(error);
1462                  }
1463                },
1464                // A session's script, and its value as the session writes it. Promise callbacks run
1465                // after this returns.
1466                session(source, value) {
1467                  Object.assign(state, { dead: false, error: undefined, refused: '', now: Date.now(), draining: false, result: undefined });
1468                  if (dynamicImport.test(source)) {
1469                    state.refused = 'top-level await, import or export';
1470                    return;
1471                  }
1472                  if (sessionListing.test(source)) {
1473                    state.refused = "a list of the global object's properties";
1474                    return;
1475                  }
1476                  Promise.resolve().then(() => { state.draining = true; });
1477                  const [failed, completion] = script(source);
1478                  if (failed) {
1479                    uncaught(completion);
1480                  } else if (value) {
1481                    try { state.result = inspect(completion); } catch (error) { uncaught(error); }
1482                  }
1483                },
1484                // Drops a session's timers, which would print after the block in node, and refuses the block.
1485                settle() {
1486                  state.draining = false;
1487                  if (state.timers.length === 0) return;
1488                  state.timers = [];
1489                  if (!state.refused) state.refused = 'a timer in a session';
1490                },
1491                get result() { return state.result; },
1492                // Runs the next timer that is due: the milliseconds until one is, 0 after running one,
1493                // or -1 when none is left to wait for.
1494                tick() {
1495                  if (state.dead || !state.timers.some((t) => t.ref)) return -1;
1496                  state.now = Date.now();
1497                  const next = state.timers.reduce((a, b) => (b.due < a.due || (b.due === a.due && b.seq < a.seq) ? b : a));
1498                  if (next.due > state.now) return next.due - state.now;
1499                  if (next.repeat) {
1500                    next.due = state.now + next.delay;
1501                    next.seq = ++state.seq;
1502                  } else {
1503                    clear(next.timeout);
1504                  }
1505                  try { next.callback.apply(next.timeout, next.args); } catch (error) { uncaught(error); }
1506                  return 0;
1507                },
1508                get error() { return state.error; },
1509                get refused() { return state.refused; },
1510              };
1511            })
1512            """#
1513    }
1514}
1515#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form