Sources/OrgApp/JavaScriptBlocks.swift

design-themes-widgets
orgstar/Sources/OrgApp/JavaScriptBlocks.swift history · blame · raw

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