Sources/OrgApp/JavaScriptBlocks.swift

2df4420ff51f7e97a9c06eacf814f64cdb5a4351
orgstar/Sources/OrgApp/JavaScriptBlocks.swift

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