Run js blocks in JavaScriptCore without node !411

merged merged by cmc on 2026-11-20 18:38 UTC · krz/orgstar:parity-js into main

10 files changed, +1877 −34

Layout: unified · split

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