Commit 702b2432b0

702b2432b070f1428ff34e8d5ae3d141ba29a007

parent: ba8f6b883c

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 16:26 UTC

Run js blocks in JavaScriptCore without node

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 +1332
@@ -0,0 +1,1332 @@
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()
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 init() {
130 let output = Output()
131 self.output = output
132 context = JSContext()
133 let write: @convention(block) (Int32, String) -> Void = { fd, text in
134 if fd == 1 { output.stdout += text } else { output.stderr += text }
135 }
136 context.exceptionHandler = { _, exception in output.exception = exception }
137 node = context.evaluateScript(Self.shim).call(withArguments: [write])
138 }
139
140 /// Runs `source` as node runs a script on standard input, then its timers.
141 func main(_ source: String, run: Run) throws -> BabelOutput {
142 node.invokeMethod("main", withArguments: [source])
143 runTimers(run)
144 return try finish(result: nil)
145 }
146
147 /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does;
148 /// with `value`, the result is its completion value as `util.inspect` prints it.
149 func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput {
150 try lock.withLock {
151 output.stdout = ""
152 output.stderr = ""
153 output.exception = nil
154 node.invokeMethod("begin", withArguments: [])
155 let completion = context.evaluateScript(source)
156 var result: String?
157 if let exception = output.exception {
158 node.invokeMethod("failed", withArguments: [exception])
159 } else if value, let completion {
160 result = node.invokeMethod("inspect", withArguments: [completion]).toString()
161 }
162 runTimers(run)
163 return try finish(result: result)
164 }
165 }
166
167 private func runTimers(_ run: Run) {
168 while !run.stopped, let wait = node.invokeMethod("tick", withArguments: [])?.toDouble(), wait >= 0 {
169 if wait > 0 { run.sleep(milliseconds: wait) }
170 }
171 }
172
173 private func finish(result: String?) throws -> BabelOutput {
174 if let refused = node.forProperty("refused")?.toString(), !refused.isEmpty {
175 throw Babel.Failure.message("This block uses \(refused), which runs only in node.")
176 }
177 guard let error = node.forProperty("error"), !error.isUndefined else {
178 return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr)
179 }
180 return BabelOutput(stdout: output.stdout, resultFile: result, stderr: output.stderr + (error.toString() ?? "") + "\n", status: 1)
181 }
182
183 /// Node's globals and modules; `util.inspect` and `util.format` are ported from Node 26's
184 /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the
185 /// runner's controls.
186 static let shim = #"""
187 (function (write) {
188 'use strict';
189 const evaluate = eval;
190 const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now() };
191
192 function refuse(what) {
193 if (!state.refused) state.refused = what;
194 throw new Error(`${what} isn't available`);
195 }
196 function out(fd, text) {
197 if (!state.dead) write(fd, text.toWellFormed());
198 }
199 // Members a script may use; any other is refused rather than answered differently.
200 const guarded = new WeakSet();
201 function guard(target, name) {
202 const proxy = new Proxy(target, {
203 get(t, key, receiver) {
204 if (typeof key === 'symbol' || key in t) return Reflect.get(t, key, receiver);
205 refuse(`${name}.${key}`);
206 },
207 });
208 guarded.add(proxy);
209 return proxy;
210 }
211 // The script's proxies, target and handler, or null once revoked: JavaScriptCore can't tell
212 // a proxy, and Node shows one.
213 const proxies = new WeakMap();
214 const RealProxy = Proxy;
215 function revocable(target, handler) {
216 const made = RealProxy.revocable(target, handler);
217 proxies.set(made.proxy, [target, handler]);
218 return { proxy: made.proxy, revoke: [() => { proxies.set(made.proxy, null); made.revoke(); }][0] };
219 }
220 const ProxyConstructor = new RealProxy(RealProxy, {
221 construct(target, args, newTarget) {
222 const proxy = Reflect.construct(target, args, newTarget);
223 proxies.set(proxy, [args[0], args[1]]);
224 return proxy;
225 },
226 get(target, key, receiver) {
227 return key === 'revocable' ? revocable : Reflect.get(target, key, receiver);
228 },
229 });
230
231 // util.inspect and util.format, after Node's lib/internal/util/inspect.js.
232 const kObjectType = 0, kArrayType = 1, kArrayExtrasType = 2;
233 const defaults = {
234 showHidden: false, depth: 2, colors: false, customInspect: true, showProxy: false, maxArrayLength: 100,
235 maxStringLength: 10000, breakLength: 80, compact: 3, sorted: false, getters: false, numericSeparator: false,
236 };
237 const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
238 const builtInObjects = new Set(Object.getOwnPropertyNames(globalThis).filter((e) => /^[A-Z][a-zA-Z0-9]+$/.test(e)));
239 const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
240 const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
241 const strEscapeSequencesRegExpSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
242 const strEscapeSequencesReplacerSingle = /[\x00-\x1f\x5c\x7f-\x9f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
243 const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
244 const numberRegExp = /^(0|[1-9][0-9]*)$/;
245 const classRegExp = /^(\s+[^(]*?)\s*{/;
246 const stripCommentsRegExp = /(\/\/.*?\n)|(\/\*(.|\n)*?\*\/)/g;
247 const kMinLineLength = 16;
248 const meta = [
249 '\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07',
250 '\\b', '\\t', '\\n', '\\x0B', '\\f', '\\r', '\\x0E', '\\x0F',
251 '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17',
252 '\\x18', '\\x19', '\\x1A', '\\x1B', '\\x1C', '\\x1D', '\\x1E', '\\x1F',
253 '', '', '', '', '', '', '', "\\'", '', '', '', '', '', '', '', '',
254 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
255 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
256 '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '',
257 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
258 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\x7F',
259 '\\x80', '\\x81', '\\x82', '\\x83', '\\x84', '\\x85', '\\x86', '\\x87',
260 '\\x88', '\\x89', '\\x8A', '\\x8B', '\\x8C', '\\x8D', '\\x8E', '\\x8F',
261 '\\x90', '\\x91', '\\x92', '\\x93', '\\x94', '\\x95', '\\x96', '\\x97',
262 '\\x98', '\\x99', '\\x9A', '\\x9B', '\\x9C', '\\x9D', '\\x9E', '\\x9F',
263 ];
264
265 // Type checks through the built-ins' own brand checks.
266 function branded(fn, value) {
267 try { fn.call(value); return true; } catch { return false; }
268 }
269 const getter = (proto, key) => Object.getOwnPropertyDescriptor(proto, key).get;
270 const typedArrayProto = Object.getPrototypeOf(Int8Array.prototype);
271 const typedArrayTag = getter(typedArrayProto, Symbol.toStringTag);
272 const isSet = (v) => branded(getter(Set.prototype, 'size'), v);
273 const isMap = (v) => branded(getter(Map.prototype, 'size'), v);
274 const isTypedArray = (v) => typedArrayTag.call(v) !== undefined;
275 const isArrayBuffer = (v) => branded(getter(ArrayBuffer.prototype, 'byteLength'), v);
276 const isDataView = (v) => branded(getter(DataView.prototype, 'byteLength'), v);
277 const isRegExp = (v) => v !== RegExp.prototype && branded(getter(RegExp.prototype, 'source'), v);
278 const isDate = (v) => branded(Date.prototype.getTime, v);
279 const isWeakMap = (v) => branded(function () { WeakMap.prototype.has.call(this, {}); }, v);
280 const isWeakSet = (v) => branded(function () { WeakSet.prototype.has.call(this, {}); }, v);
281 const isPromise = (v) => Object.prototype.toString.call(v) === '[object Promise]' && v instanceof Promise;
282 const isError = (v) => v instanceof Error || Object.prototype.toString.call(v) === '[object Error]';
283 const isArgumentsObject = (v) => Object.prototype.toString.call(v) === '[object Arguments]';
284 const iteratorTags = ['[object Map Iterator]', '[object Set Iterator]', '[object Array Iterator]', '[object String Iterator]', '[object Generator]', '[object Iterator Helper]'];
285 const generatorFunctionProto = Object.getPrototypeOf(function* () {});
286 const asyncFunctionProto = Object.getPrototypeOf(async function () {});
287 const asyncGeneratorFunctionProto = Object.getPrototypeOf(async function* () {});
288 const boxes = [
289 ['Number', Number.prototype.valueOf], ['String', String.prototype.valueOf], ['Boolean', Boolean.prototype.valueOf],
290 ['BigInt', BigInt.prototype.valueOf], ['Symbol', Symbol.prototype.valueOf],
291 ];
292 const boxType = (v) => boxes.find(([, fn]) => branded(fn, v));
293 const internalGetConstructorName = (v) => Object.prototype.toString.call(v).slice(8, -1);
294
295 // Width as a terminal shows it; text beyond ASCII is measured by ICU in Node.
296 function getStringWidth(str) {
297 let width = 0;
298 for (let i = 0; i < str.length; i++) {
299 const code = str.charCodeAt(i);
300 if (code >= 127) refuse('lining up text beyond ASCII in util.inspect');
301 width += code >= 32 ? 1 : 0;
302 }
303 return width;
304 }
305
306 function inspect(value, opts) {
307 const ctx = { budget: {}, indentationLvl: 0, seen: [], currentDepth: 0, ...defaults };
308 if (arguments.length > 1) {
309 if (arguments.length > 2) {
310 if (arguments[2] !== undefined) ctx.depth = arguments[2];
311 if (arguments.length > 3 && arguments[3] !== undefined) ctx.colors = arguments[3];
312 }
313 if (typeof opts === 'boolean') {
314 ctx.showHidden = opts;
315 } else if (opts) {
316 for (const key of Object.keys(opts)) {
317 if (Object.prototype.hasOwnProperty.call(defaults, key)) ctx[key] = opts[key];
318 else if (key === 'stylize') refuse('util.inspect with stylize');
319 else if (ctx.userOptions === undefined) ctx.userOptions = opts;
320 }
321 }
322 }
323 if (ctx.colors) refuse('util.inspect with colors');
324 if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
325 if (ctx.maxStringLength === null) ctx.maxStringLength = Infinity;
326 return formatValue(ctx, value, 0);
327 }
328 inspect.custom = customInspectSymbol;
329 Object.defineProperty(inspect, 'defaultOptions', { get() { refuse('util.inspect.defaultOptions'); } });
330
331 const stylize = (str) => str;
332
333 function getUserOptions(ctx) {
334 const ret = { stylize };
335 for (const key of Object.keys(defaults)) ret[key] = ctx[key];
336 return { ...ret, ...ctx.userOptions };
337 }
338
339 function formatValue(ctx, value, recurseTimes, typedArray) {
340 if (typeof value !== 'object' && typeof value !== 'function') return formatPrimitive(value, ctx);
341 if (value === null) return 'null';
342 if (guarded.has(value)) refuse('util.inspect of console, process or util');
343 const context = value;
344 let proxyCount = 0;
345 let proxy = proxies.get(value);
346 if (proxy !== undefined) {
347 if (ctx.showProxy) return proxy === null ? '<Revoked Proxy>' : formatProxy(ctx, proxy, recurseTimes);
348 do {
349 if (proxy === null) return 'Proxy('.repeat(proxyCount) + '<Revoked Proxy>' + ')'.repeat(proxyCount);
350 value = proxy[0];
351 proxy = proxies.get(value);
352 proxyCount += 1;
353 } while (proxy !== undefined);
354 }
355 const formatted = formatUnwrapped(ctx, value, context, recurseTimes, typedArray);
356 return 'Proxy('.repeat(proxyCount) + formatted + ')'.repeat(proxyCount);
357 }
358
359 function formatProxy(ctx, proxy, recurseTimes) {
360 if (recurseTimes > ctx.depth && ctx.depth !== null) return 'Proxy [Array]';
361 recurseTimes += 1;
362 ctx.indentationLvl += 2;
363 const res = [formatValue(ctx, proxy[0], recurseTimes), formatValue(ctx, proxy[1], recurseTimes)];
364 ctx.indentationLvl -= 2;
365 return reduceToSingleString(ctx, res, '', ['Proxy [', ']'], kArrayExtrasType, recurseTimes);
366 }
367
368 function formatUnwrapped(ctx, value, context, recurseTimes, typedArray) {
369 if (ctx.customInspect) {
370 const maybeCustom = value[customInspectSymbol];
371 if (typeof maybeCustom === 'function' && maybeCustom !== inspect &&
372 Object.getOwnPropertyDescriptor(value, 'constructor')?.value?.prototype !== value) {
373 const depth = ctx.depth === null ? null : ctx.depth - recurseTimes;
374 const ret = maybeCustom.call(context, depth, getUserOptions(ctx), inspect);
375 if (ret !== context) {
376 if (typeof ret !== 'string') return formatValue(ctx, ret, recurseTimes);
377 return ret.replaceAll('\n', `\n${' '.repeat(ctx.indentationLvl)}`);
378 }
379 }
380 }
381 if (ctx.seen.includes(value)) {
382 let index = 1;
383 if (ctx.circular === undefined) {
384 ctx.circular = new Map();
385 ctx.circular.set(value, index);
386 } else {
387 index = ctx.circular.get(value);
388 if (index === undefined) {
389 index = ctx.circular.size + 1;
390 ctx.circular.set(value, index);
391 }
392 }
393 return `[Circular *${index}]`;
394 }
395 return formatRaw(ctx, value, recurseTimes, typedArray);
396 }
397
398 function getConstructorName(obj, ctx, recurseTimes, protoProps) {
399 let firstProto;
400 const tmp = obj;
401 while (obj) {
402 const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
403 if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '' &&
404 isInstanceof(tmp, descriptor.value)) {
405 if (protoProps !== undefined && (firstProto !== obj || !builtInObjects.has(descriptor.value.name))) {
406 addPrototypeProperties(ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
407 }
408 return String(descriptor.value.name);
409 }
410 obj = Object.getPrototypeOf(obj);
411 if (firstProto === undefined) firstProto = obj;
412 }
413 if (firstProto === null) return null;
414 const res = internalGetConstructorName(tmp);
415 if (recurseTimes > ctx.depth && ctx.depth !== null) return `${res} <Complex prototype>`;
416 const protoConstr = getConstructorName(firstProto, ctx, recurseTimes + 1, protoProps);
417 if (protoConstr === null) {
418 return `${res} <${inspect(firstProto, { ...ctx, customInspect: false, depth: -1 })}>`;
419 }
420 return `${res} <${protoConstr}>`;
421 }
422
423 function isInstanceof(object, proto) {
424 try { return object instanceof proto; } catch { return false; }
425 }
426
427 function addPrototypeProperties(ctx, main, obj, recurseTimes, output) {
428 let depth = 0;
429 let keys;
430 let keySet;
431 do {
432 if (depth !== 0 || main === obj) {
433 obj = Object.getPrototypeOf(obj);
434 if (obj === null) return;
435 const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
436 if (descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name)) return;
437 }
438 if (depth === 0) {
439 keySet = new Set();
440 } else {
441 keys.forEach((key) => keySet.add(key));
442 }
443 keys = Reflect.ownKeys(obj);
444 ctx.seen.push(main);
445 for (const key of keys) {
446 if (key === 'constructor' || Object.prototype.hasOwnProperty.call(main, key) || (depth !== 0 && keySet.has(key))) continue;
447 const desc = Object.getOwnPropertyDescriptor(obj, key);
448 if (typeof desc.value === 'function') continue;
449 output.push(formatProperty(ctx, obj, recurseTimes, key, kObjectType, desc, main));
450 }
451 ctx.seen.pop();
452 } while (++depth !== 3);
453 }
454
455 function getPrefix(constructor, tag, fallback, size = '') {
456 if (constructor === null) {
457 if (tag !== '' && fallback !== tag) return `[${fallback}${size}: null prototype] [${tag}] `;
458 return `[${fallback}${size}: null prototype] `;
459 }
460 if (tag !== '') {
461 const dot = tag.lastIndexOf('.');
462 if (constructor === (dot >= 1 ? tag.slice(dot + 1) : tag)) return `${tag}${size} `;
463 return `${constructor}${size} [${tag}] `;
464 }
465 return `${constructor}${size} `;
466 }
467
468 function getKeys(value, showHidden) {
469 let keys;
470 const symbols = Object.getOwnPropertySymbols(value);
471 if (showHidden) {
472 keys = Object.getOwnPropertyNames(value);
473 if (symbols.length !== 0) keys.push(...symbols);
474 } else {
475 keys = Object.keys(value);
476 if (symbols.length !== 0) keys.push(...symbols.filter((key) => Object.prototype.propertyIsEnumerable.call(value, key)));
477 }
478 return keys;
479 }
480
481 function isIndex(key) {
482 return typeof key === 'string' && numberRegExp.test(key) && Number(key) < 2 ** 32 - 1;
483 }
484
485 function getOwnNonIndexProperties(value, showHidden) {
486 const keys = Reflect.ownKeys(value).filter((key) => !isIndex(key) &&
487 (showHidden || Object.prototype.propertyIsEnumerable.call(value, key)));
488 return [...keys.filter((key) => typeof key === 'string'), ...keys.filter((key) => typeof key === 'symbol')];
489 }
490
491 function getCtxStyle(value, constructor, tag) {
492 let fallback = '';
493 if (constructor === null) {
494 fallback = internalGetConstructorName(value);
495 if (fallback === tag) fallback = 'Object';
496 }
497 return getPrefix(constructor, tag, fallback);
498 }
499
500 function formatRaw(ctx, value, recurseTimes, typedArray) {
501 let keys;
502 let protoProps;
503 if (ctx.showHidden && (recurseTimes <= ctx.depth || ctx.depth === null)) protoProps = [];
504 const constructor = getConstructorName(value, ctx, recurseTimes, protoProps);
505 if (protoProps !== undefined && protoProps.length === 0) protoProps = undefined;
506 let tag = '';
507 try { tag = value[Symbol.toStringTag]; } catch {}
508 if (typeof tag !== 'string' || (tag !== '' && (ctx.showHidden ? Object.prototype.hasOwnProperty
509 : Object.prototype.propertyIsEnumerable).call(value, Symbol.toStringTag))) {
510 tag = '';
511 }
512 let base = '';
513 let formatter = () => [];
514 let braces;
515 let noIterator = true;
516 let extrasType = kObjectType;
517 let extraKeys;
518
519 if (Symbol.iterator in value || constructor === null) {
520 noIterator = false;
521 if (Array.isArray(value)) {
522 const prefix = (constructor !== 'Array' || tag !== '') ? getPrefix(constructor, tag, 'Array', `(${value.length})`) : '';
523 keys = getOwnNonIndexProperties(value, ctx.showHidden);
524 braces = [`${prefix}[`, ']'];
525 if (value.length === 0 && keys.length === 0 && protoProps === undefined) return `${braces[0]}]`;
526 extrasType = kArrayExtrasType;
527 formatter = formatArray;
528 } else if (isSet(value)) {
529 const size = getter(Set.prototype, 'size').call(value);
530 const prefix = getPrefix(constructor, tag, 'Set', `(${size})`);
531 keys = getKeys(value, ctx.showHidden);
532 formatter = (ctx, v, recurseTimes) => formatSet(value, ctx, recurseTimes);
533 if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
534 braces = [`${prefix}{`, '}'];
535 } else if (isMap(value)) {
536 const size = getter(Map.prototype, 'size').call(value);
537 const prefix = getPrefix(constructor, tag, 'Map', `(${size})`);
538 keys = getKeys(value, ctx.showHidden);
539 formatter = (ctx, v, recurseTimes) => formatMap(value, ctx, recurseTimes);
540 if (size === 0 && keys.length === 0 && protoProps === undefined) return `${prefix}{}`;
541 braces = [`${prefix}{`, '}'];
542 } else if (isTypedArray(value)) {
543 keys = getOwnNonIndexProperties(value, ctx.showHidden);
544 const fallback = constructor === null ? typedArrayTag.call(value) : '';
545 const size = getter(typedArrayProto, 'length').call(value);
546 const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
547 braces = [`${prefix}[`, ']'];
548 if (value.length === 0 && keys.length === 0 && !ctx.showHidden) return `${braces[0]}]`;
549 formatter = (ctx) => formatTypedArray(value, size, ctx);
550 extrasType = kArrayExtrasType;
551 if (ctx.showHidden) {
552 extraKeys = ['BYTES_PER_ELEMENT', 'length', 'byteLength', 'byteOffset', 'buffer'];
553 typedArray = true;
554 }
555 } else if (iteratorTags.includes(Object.prototype.toString.call(value))) {
556 refuse('util.inspect of an iterator');
557 } else {
558 noIterator = true;
559 }
560 }
561 if (noIterator) {
562 keys = getKeys(value, ctx.showHidden);
563 braces = ['{', '}'];
564 if (typeof value === 'function') {
565 base = getFunctionBase(ctx, value, constructor, tag);
566 if (keys.length === 0 && protoProps === undefined) return base;
567 } else if (constructor === 'Object') {
568 if (isArgumentsObject(value)) {
569 braces[0] = '[Arguments] {';
570 } else if (tag !== '') {
571 braces[0] = `${getPrefix(constructor, tag, 'Object')}{`;
572 }
573 if (keys.length === 0 && protoProps === undefined) return `${braces[0]}}`;
574 } else if (isRegExp(value)) {
575 base = RegExp.prototype.toString.call(constructor !== null ? value : new RegExp(value));
576 const prefix = getPrefix(constructor, tag, 'RegExp');
577 if (prefix !== 'RegExp ') base = `${prefix}${base}`;
578 if ((keys.length === 0 && protoProps === undefined) || (recurseTimes > ctx.depth && ctx.depth !== null)) return base;
579 } else if (isDate(value)) {
580 base = Number.isNaN(Date.prototype.getTime.call(value)) ? Date.prototype.toString.call(value) : Date.prototype.toISOString.call(value);
581 const prefix = getPrefix(constructor, tag, 'Date');
582 if (prefix !== 'Date ') base = `${prefix}${base}`;
583 if (keys.length === 0 && protoProps === undefined) return base;
584 } else if (isError(value)) {
585 refuse('util.inspect of an Error');
586 } else if (isArrayBuffer(value)) {
587 const prefix = getPrefix(constructor, tag, 'ArrayBuffer');
588 if (typedArray === undefined) {
589 formatter = formatArrayBuffer;
590 } else if (keys.length === 0 && protoProps === undefined) {
591 return prefix + `{ [byteLength]: ${formatNumber(value.byteLength, false)} }`;
592 }
593 braces[0] = `${prefix}{`;
594 extraKeys = ['byteLength'];
595 } else if (isDataView(value)) {
596 braces[0] = `${getPrefix(constructor, tag, 'DataView')}{`;
597 extraKeys = ['byteLength', 'byteOffset', 'buffer'];
598 } else if (isPromise(value)) {
599 refuse('util.inspect of a Promise');
600 } else if (isWeakSet(value) || isWeakMap(value)) {
601 if (ctx.showHidden) refuse('util.inspect of WeakMap or WeakSet entries');
602 braces[0] = `${getPrefix(constructor, tag, isWeakSet(value) ? 'WeakSet' : 'WeakMap')}{`;
603 formatter = () => ['<items unknown>'];
604 } else if (typeof value === 'object' && boxType(value)) {
605 base = getBoxedBase(value, ctx, keys, constructor, tag);
606 if (keys.length === 0 && protoProps === undefined) return base;
607 } else {
608 if (keys.length === 0 && protoProps === undefined) return `${getCtxStyle(value, constructor, tag)}{}`;
609 braces[0] = `${getCtxStyle(value, constructor, tag)}{`;
610 }
611 }
612
613 if (recurseTimes > ctx.depth && ctx.depth !== null) {
614 let constructorName = getCtxStyle(value, constructor, tag).slice(0, -1);
615 if (constructor !== null) constructorName = `[${constructorName}]`;
616 return constructorName;
617 }
618 recurseTimes += 1;
619 ctx.seen.push(value);
620 ctx.currentDepth = recurseTimes;
621 const output = formatter(ctx, value, recurseTimes);
622 if (extraKeys !== undefined) {
623 for (const key of extraKeys) output.push(formatExtraProperties(ctx, value, recurseTimes, key, typedArray));
624 }
625 for (const key of keys) output.push(formatProperty(ctx, value, recurseTimes, key, extrasType));
626 if (protoProps !== undefined) output.push(...protoProps);
627 if (ctx.circular !== undefined) {
628 const index = ctx.circular.get(value);
629 if (index !== undefined) {
630 const reference = `<ref *${index}>`;
631 if (ctx.compact !== true) {
632 base = base === '' ? reference : `${reference} ${base}`;
633 } else {
634 braces[0] = `${reference} ${braces[0]}`;
635 }
636 }
637 }
638 ctx.seen.pop();
639 if (ctx.sorted) {
640 const comparator = ctx.sorted === true ? undefined : ctx.sorted;
641 if (extrasType === kObjectType) {
642 output.sort(comparator);
643 } else if (keys.length > 1) {
644 const sorted = output.slice(output.length - keys.length).sort(comparator);
645 output.splice(output.length - keys.length, keys.length, ...sorted);
646 }
647 }
648 const res = reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value);
649 const newLength = (ctx.budget[ctx.indentationLvl] || 0) + res.length;
650 ctx.budget[ctx.indentationLvl] = newLength;
651 if (newLength > 2 ** 27) ctx.depth = -1;
652 return res;
653 }
654
655 function getBoxedBase(value, ctx, keys, constructor, tag) {
656 const [type, fn] = boxType(value);
657 if (type === 'String') keys.splice(0, value.length);
658 let base = `[${type}`;
659 if (type !== constructor) base += constructor === null ? ' (null prototype)' : ` (${constructor})`;
660 base += `: ${formatPrimitive(fn.call(value), ctx)}]`;
661 if (tag !== '' && tag !== constructor) base += ` [${tag}]`;
662 return base;
663 }
664
665 function getClassBase(value, constructor, tag) {
666 const hasName = Object.prototype.hasOwnProperty.call(value, 'name');
667 const name = (hasName && value.name) || '(anonymous)';
668 let base = `class ${name}`;
669 if (constructor !== 'Function' && constructor !== null) base += ` [${constructor}]`;
670 if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
671 if (constructor !== null) {
672 const superName = Object.getPrototypeOf(value).name;
673 if (superName) base += ` extends ${superName}`;
674 } else {
675 base += ' extends [null prototype]';
676 }
677 return `[${base}]`;
678 }
679
680 function getFunctionBase(ctx, value, constructor, tag) {
681 const stringified = Function.prototype.toString.call(value);
682 if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') {
683 const slice = stringified.slice(5, -1);
684 const bracketIndex = slice.indexOf('{');
685 if (bracketIndex !== -1 && (!slice.slice(0, bracketIndex).includes('(') ||
686 classRegExp.exec(slice.replace(stripCommentsRegExp, '')) !== null)) {
687 return getClassBase(value, constructor, tag);
688 }
689 }
690 const proto = Object.getPrototypeOf(value);
691 let type = 'Function';
692 if (proto === generatorFunctionProto || proto === asyncGeneratorFunctionProto) type = `Generator${type}`;
693 if (proto === asyncFunctionProto || proto === asyncGeneratorFunctionProto) type = `Async${type}`;
694 let base = `[${type}`;
695 if (constructor === null) base += ' (null prototype)';
696 if (value.name === '') {
697 base += ' (anonymous)';
698 } else {
699 base += `: ${typeof value.name === 'string' ? value.name : formatValue(ctx, value.name)}`;
700 }
701 base += ']';
702 if (constructor !== type && constructor !== null) base += ` ${constructor}`;
703 if (tag !== '' && constructor !== tag) base += ` [${tag}]`;
704 return base;
705 }
706
707 function addQuotes(str, quotes) {
708 if (quotes === -1) return `"${str}"`;
709 if (quotes === -2) return `\`${str}\``;
710 return `'${str}'`;
711 }
712
713 function escapeFn(str) {
714 const charCode = str.charCodeAt(0);
715 return meta.length > charCode ? meta[charCode] : `\\u${charCode.toString(16)}`;
716 }
717
718 function strEscape(str) {
719 let escapeTest = strEscapeSequencesRegExp;
720 let escapeReplace = strEscapeSequencesReplacer;
721 let singleQuote = 39;
722 if (str.includes("'")) {
723 if (!str.includes('"')) {
724 singleQuote = -1;
725 } else if (!str.includes('`') && !str.includes('${')) {
726 singleQuote = -2;
727 }
728 if (singleQuote !== 39) {
729 escapeTest = strEscapeSequencesRegExpSingle;
730 escapeReplace = strEscapeSequencesReplacerSingle;
731 }
732 }
733 if (str.length < 5000 && escapeTest.exec(str) === null) return addQuotes(str, singleQuote);
734 if (str.length > 100) {
735 str = str.replace(escapeReplace, escapeFn);
736 return addQuotes(str, singleQuote);
737 }
738 let result = '';
739 let last = 0;
740 for (let i = 0; i < str.length; i++) {
741 const point = str.charCodeAt(i);
742 if (point === singleQuote || point === 92 || point < 32 || (point > 126 && point < 160)) {
743 result += last === i ? meta[point] : `${str.slice(last, i)}${meta[point]}`;
744 last = i + 1;
745 } else if (point >= 0xd800 && point <= 0xdfff) {
746 if (point <= 0xdbff && i + 1 < str.length) {
747 const next = str.charCodeAt(i + 1);
748 if (next >= 0xdc00 && next <= 0xdfff) {
749 i++;
750 continue;
751 }
752 }
753 result += `${str.slice(last, i)}\\u${point.toString(16)}`;
754 last = i + 1;
755 }
756 }
757 if (last !== str.length) result += str.slice(last);
758 return addQuotes(result, singleQuote);
759 }
760
761 function addNumericSeparator(integerString) {
762 let result = '';
763 let i = integerString.length;
764 const start = integerString[0] === '-' ? 1 : 0;
765 for (; i >= start + 4; i -= 3) result = `_${integerString.slice(i - 3, i)}${result}`;
766 return i === integerString.length ? integerString : `${integerString.slice(0, i)}${result}`;
767 }
768
769 function addNumericSeparatorEnd(integerString) {
770 let result = '';
771 let i = 0;
772 for (; i < integerString.length - 3; i += 3) result += `${integerString.slice(i, i + 3)}_`;
773 return i === 0 ? integerString : `${result}${integerString.slice(i)}`;
774 }
775
776 const remainingText = (remaining) => `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
777
778 function formatNumber(number, numericSeparator) {
779 if (Object.is(number, -0)) return '-0';
780 if (!numericSeparator) return `${number}`;
781 const numberString = String(number);
782 const integer = Math.trunc(number);
783 if (integer === number) {
784 if (!Number.isFinite(number) || numberString.includes('e')) return numberString;
785 return addNumericSeparator(numberString);
786 }
787 if (Number.isNaN(number) || numberString.includes('e')) return numberString;
788 const decimalIndex = numberString.indexOf('.');
789 return `${addNumericSeparator(numberString.slice(0, decimalIndex))}.${addNumericSeparatorEnd(numberString.slice(decimalIndex + 1))}`;
790 }
791
792 function formatBigInt(bigint, numericSeparator) {
793 const string = String(bigint);
794 return numericSeparator ? `${addNumericSeparator(string)}n` : `${string}n`;
795 }
796
797 function formatPrimitive(value, ctx) {
798 if (typeof value === 'string') {
799 let trailer = '';
800 if (value.length > ctx.maxStringLength) {
801 const remaining = value.length - ctx.maxStringLength;
802 value = value.slice(0, ctx.maxStringLength);
803 trailer = `... ${remaining} more character${remaining > 1 ? 's' : ''}`;
804 }
805 if (ctx.compact !== true && value.length > kMinLineLength && value.length > ctx.breakLength - ctx.indentationLvl - 4) {
806 return value.split(/(?<=\n)/).map((line) => strEscape(line)).join(` +\n${' '.repeat(ctx.indentationLvl + 2)}`) + trailer;
807 }
808 return strEscape(value) + trailer;
809 }
810 if (typeof value === 'number') return formatNumber(value, ctx.numericSeparator);
811 if (typeof value === 'bigint') return formatBigInt(value, ctx.numericSeparator);
812 if (typeof value === 'boolean') return `${value}`;
813 if (typeof value === 'undefined') return 'undefined';
814 return Symbol.prototype.toString.call(value);
815 }
816
817 function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) {
818 const keys = Object.keys(value);
819 let index = i;
820 for (; i < keys.length && output.length < maxLength; i++) {
821 const key = keys[i];
822 const tmp = +key;
823 if (tmp > 2 ** 32 - 2) break;
824 if (`${index}` !== key) {
825 if (numberRegExp.exec(key) === null) break;
826 const emptyItems = tmp - index;
827 output.push(`<${emptyItems} empty item${emptyItems > 1 ? 's' : ''}>`);
828 index = tmp;
829 if (output.length === maxLength) break;
830 }
831 output.push(formatProperty(ctx, value, recurseTimes, key, kArrayType));
832 index++;
833 }
834 const remaining = value.length - index;
835 if (output.length !== maxLength) {
836 if (remaining > 0) output.push(`<${remaining} empty item${remaining > 1 ? 's' : ''}>`);
837 } else if (remaining > 0) {
838 output.push(remainingText(remaining));
839 }
840 return output;
841 }
842
843 function formatArrayBuffer(ctx, value) {
844 const buffer = new Uint8Array(value);
845 const shown = Array.from(buffer.subarray(0, Math.min(ctx.maxArrayLength, buffer.length)), (b) => b.toString(16).padStart(2, '0'));
846 let str = shown.join(' ');
847 const remaining = buffer.length - ctx.maxArrayLength;
848 if (remaining > 0) str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
849 return [`[Uint8Contents]: <${str}>`];
850 }
851
852 function formatArray(ctx, value, recurseTimes) {
853 const valLen = value.length;
854 const len = Math.min(Math.max(0, ctx.maxArrayLength), valLen);
855 const remaining = valLen - len;
856 const output = [];
857 for (let i = 0; i < len; i++) {
858 const desc = Object.getOwnPropertyDescriptor(value, i);
859 if (desc === undefined) return formatSpecialArray(ctx, value, recurseTimes, len, output, i);
860 output.push(formatProperty(ctx, value, recurseTimes, i, kArrayType, desc));
861 }
862 if (remaining > 0) output.push(remainingText(remaining));
863 return output;
864 }
865
866 function formatTypedArray(value, length, ctx) {
867 const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
868 const remaining = value.length - maxLength;
869 const output = new Array(maxLength);
870 const elementFormatter = value.length > 0 && typeof value[0] === 'number' ? formatNumber : formatBigInt;
871 for (let i = 0; i < maxLength; ++i) output[i] = elementFormatter(value[i], ctx.numericSeparator);
872 if (remaining > 0) output[maxLength] = remainingText(remaining);
873 return output;
874 }
875
876 function formatSet(value, ctx, recurseTimes) {
877 const length = value.size;
878 const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
879 const remaining = length - maxLength;
880 const output = [];
881 ctx.indentationLvl += 2;
882 let i = 0;
883 for (const v of Set.prototype.values.call(value)) {
884 if (i >= maxLength) break;
885 output.push(formatValue(ctx, v, recurseTimes));
886 i++;
887 }
888 if (remaining > 0) output.push(remainingText(remaining));
889 ctx.indentationLvl -= 2;
890 return output;
891 }
892
893 function formatMap(value, ctx, recurseTimes) {
894 const length = value.size;
895 const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), length);
896 const remaining = length - maxLength;
897 const output = [];
898 ctx.indentationLvl += 2;
899 let i = 0;
900 for (const { 0: k, 1: v } of Map.prototype.entries.call(value)) {
901 if (i >= maxLength) break;
902 output.push(`${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`);
903 i++;
904 }
905 if (remaining > 0) output.push(remainingText(remaining));
906 ctx.indentationLvl -= 2;
907 return output;
908 }
909
910 function formatExtraProperties(ctx, value, recurseTimes, key, typedArray) {
911 const extraValue = value[key];
912 ctx.indentationLvl += 2;
913 const str = formatValue(ctx, extraValue, recurseTimes, typedArray);
914 ctx.indentationLvl -= 2;
915 return `[${key}]: ${str}`;
916 }
917
918 function formatProperty(ctx, value, recurseTimes, key, type, desc, original = value) {
919 let name, str;
920 let extra = ' ';
921 desc ??= Object.getOwnPropertyDescriptor(value, key);
922 if (desc.value !== undefined) {
923 const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3;
924 ctx.indentationLvl += diff;
925 str = formatValue(ctx, desc.value, recurseTimes);
926 if (diff === 3 && ctx.breakLength < getStringWidth(str)) extra = `\n${' '.repeat(ctx.indentationLvl)}`;
927 ctx.indentationLvl -= diff;
928 } else if (desc.get !== undefined) {
929 const label = desc.set !== undefined ? 'Getter/Setter' : 'Getter';
930 if (ctx.getters && (ctx.getters === true || (ctx.getters === 'get' && desc.set === undefined) ||
931 (ctx.getters === 'set' && desc.set !== undefined))) {
932 ctx.indentationLvl += 2;
933 try {
934 const tmp = desc.get.call(original);
935 if (tmp === null) {
936 str = `[${label}: null]`;
937 } else if (typeof tmp === 'object' || typeof tmp === 'function') {
938 str = `[${label}] ${formatValue(ctx, tmp, recurseTimes)}`;
939 } else {
940 str = `[${label}: ${formatPrimitive(tmp, ctx)}]`;
941 }
942 } catch (err) {
943 str = `[${label}: <Inspection threw (${formatValue(ctx, err, recurseTimes)})>]`;
944 }
945 ctx.indentationLvl -= 2;
946 } else {
947 str = `[${label}]`;
948 }
949 } else if (desc.set !== undefined) {
950 str = '[Setter]';
951 } else {
952 str = 'undefined';
953 }
954 if (type === kArrayType) return str;
955 if (typeof key === 'symbol') {
956 name = Symbol.prototype.toString.call(key).replace(strEscapeSequencesReplacer, escapeFn);
957 } else if (keyStrRegExp.exec(key) !== null) {
958 name = key === '__proto__' ? "['__proto__']" : key;
959 } else {
960 name = strEscape(key);
961 }
962 if (desc.enumerable === false) name = `[${name}]`;
963 return `${name}:${extra}${str}`;
964 }
965
966 function groupArrayElements(ctx, output, value) {
967 let totalLength = 0;
968 let maxLength = 0;
969 let i = 0;
970 let outputLength = output.length;
971 if (ctx.maxArrayLength < output.length) outputLength--;
972 const separatorSpace = 2;
973 const dataLen = new Array(outputLength);
974 for (; i < outputLength; i++) {
975 const len = getStringWidth(output[i]);
976 dataLen[i] = len;
977 totalLength += len + separatorSpace;
978 if (maxLength < len) maxLength = len;
979 }
980 const actualMax = maxLength + separatorSpace;
981 if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength && (totalLength / actualMax > 5 || maxLength <= 6)) {
982 const approxCharHeights = 2.5;
983 const averageBias = Math.sqrt(actualMax - totalLength / output.length);
984 const biasedMax = Math.max(actualMax - 3 - averageBias, 1);
985 const columns = Math.min(
986 Math.round(Math.sqrt(approxCharHeights * biasedMax * outputLength) / biasedMax),
987 Math.floor((ctx.breakLength - ctx.indentationLvl) / actualMax),
988 ctx.compact * 4,
989 15,
990 );
991 if (columns <= 1) return output;
992 const tmp = [];
993 const maxLineLength = [];
994 for (let i = 0; i < columns; i++) {
995 let lineMaxLength = 0;
996 for (let j = i; j < output.length; j += columns) {
997 if (dataLen[j] > lineMaxLength) lineMaxLength = dataLen[j];
998 }
999 maxLineLength[i] = lineMaxLength + separatorSpace;
1000 }
1001 let padStart = true;
1002 if (value !== undefined) {
1003 for (let i = 0; i < output.length; i++) {
1004 if (typeof value[i] !== 'number' && typeof value[i] !== 'bigint') {
1005 padStart = false;
1006 break;
1007 }
1008 }
1009 }
1010 for (let i = 0; i < outputLength; i += columns) {
1011 const max = Math.min(i + columns, outputLength);
1012 let str = '';
1013 let j = i;
1014 for (; j < max - 1; j++) {
1015 const padding = maxLineLength[j - i] + output[j].length - dataLen[j];
1016 str += padStart ? `${output[j]}, `.padStart(padding, ' ') : `${output[j]}, `.padEnd(padding, ' ');
1017 }
1018 if (padStart) {
1019 str += output[j].padStart(maxLineLength[j - i] + output[j].length - dataLen[j] - separatorSpace, ' ');
1020 } else {
1021 str += output[j];
1022 }
1023 tmp.push(str);
1024 }
1025 if (ctx.maxArrayLength < output.length) tmp.push(output[outputLength]);
1026 output = tmp;
1027 }
1028 return output;
1029 }
1030
1031 function isBelowBreakLength(ctx, output, start, base) {
1032 if (ctx.breakLength === Infinity) {
1033 if (base !== '' && base.includes('\n')) return false;
1034 return !output.some((entry) => typeof entry === 'string' && entry.includes('\n'));
1035 }
1036 let totalLength = output.length + start;
1037 if (totalLength + output.length > ctx.breakLength) return false;
1038 for (let i = 0; i < output.length; i++) {
1039 totalLength += output[i].length;
1040 if (totalLength > ctx.breakLength) return false;
1041 }
1042 return base === '' || !base.includes('\n');
1043 }
1044
1045 function reduceToSingleString(ctx, output, base, braces, extrasType, recurseTimes, value) {
1046 if (ctx.compact !== true) {
1047 if (typeof ctx.compact === 'number' && ctx.compact >= 1) {
1048 const entries = output.length;
1049 if (extrasType === kArrayExtrasType && entries > 6) output = groupArrayElements(ctx, output, value);
1050 if (ctx.currentDepth - recurseTimes < ctx.compact && entries === output.length) {
1051 const start = output.length + ctx.indentationLvl + braces[0].length + base.length + 10;
1052 if (isBelowBreakLength(ctx, output, start, base)) {
1053 const joinedOutput = output.join(', ');
1054 if (!joinedOutput.includes('\n')) return `${base ? `${base} ` : ''}${braces[0]} ${joinedOutput}` + ` ${braces[1]}`;
1055 }
1056 }
1057 }
1058 const indentation = `\n${' '.repeat(ctx.indentationLvl)}`;
1059 return `${base ? `${base} ` : ''}${braces[0]}${indentation} ${output.join(`,${indentation} `)}${indentation}${braces[1]}`;
1060 }
1061 if (isBelowBreakLength(ctx, output, 0, base)) return `${braces[0]}${base ? ` ${base}` : ''} ${output.join(', ')} ` + braces[1];
1062 const indentation = ' '.repeat(ctx.indentationLvl);
1063 const ln = base === '' && braces[0].length === 1 ? ' ' : `${base ? ` ${base}` : ''}\n${indentation} `;
1064 return `${braces[0]}${ln}${output.join(`,\n${indentation} `)} ${braces[1]}`;
1065 }
1066
1067 function hasBuiltInToString(value) {
1068 let hasOwnToString = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1069 let hasOwnToPrimitive = hasOwnToString;
1070 if (typeof value.toString !== 'function') {
1071 if (typeof value[Symbol.toPrimitive] !== 'function') return true;
1072 if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) return false;
1073 hasOwnToString = () => false;
1074 } else if (Object.prototype.hasOwnProperty.call(value, 'toString')) {
1075 return false;
1076 } else if (typeof value[Symbol.toPrimitive] !== 'function') {
1077 hasOwnToPrimitive = () => false;
1078 } else if (Object.prototype.hasOwnProperty.call(value, Symbol.toPrimitive)) {
1079 return false;
1080 }
1081 let pointer = value;
1082 do {
1083 pointer = Object.getPrototypeOf(pointer);
1084 } while (!hasOwnToString(pointer, 'toString') && !hasOwnToPrimitive(pointer, Symbol.toPrimitive));
1085 const descriptor = Object.getOwnPropertyDescriptor(pointer, 'constructor');
1086 return descriptor !== undefined && typeof descriptor.value === 'function' && builtInObjects.has(descriptor.value.name);
1087 }
1088
1089 let circularErrorMessage;
1090 function tryStringify(arg) {
1091 try {
1092 return JSON.stringify(arg);
1093 } catch (err) {
1094 if (!circularErrorMessage) {
1095 try {
1096 const a = {};
1097 a.a = a;
1098 JSON.stringify(a);
1099 } catch (circularError) {
1100 circularErrorMessage = circularError.message.split('\n', 1)[0];
1101 }
1102 }
1103 if (err.name === 'TypeError' && err.message.split('\n', 1)[0] === circularErrorMessage) return '[Circular]';
1104 throw err;
1105 }
1106 }
1107
1108 function formatWithOptions(inspectOptions, args) {
1109 const first = args[0];
1110 let a = 0;
1111 let str = '';
1112 let join = '';
1113 if (typeof first === 'string') {
1114 if (args.length === 1) return first;
1115 let tempStr;
1116 let lastPos = 0;
1117 for (let i = 0; i < first.length - 1; i++) {
1118 if (first.charCodeAt(i) === 37) {
1119 const nextChar = first.charCodeAt(++i);
1120 if (a + 1 !== args.length) {
1121 switch (nextChar) {
1122 case 115: {
1123 const tempArg = args[++a];
1124 if (typeof tempArg === 'number') {
1125 tempStr = formatNumber(tempArg, inspectOptions?.numericSeparator);
1126 } else if (typeof tempArg === 'bigint') {
1127 tempStr = formatBigInt(tempArg, inspectOptions?.numericSeparator);
1128 } else if (typeof tempArg !== 'object' || tempArg === null || !hasBuiltInToString(tempArg)) {
1129 tempStr = String(tempArg);
1130 } else {
1131 tempStr = inspect(tempArg, { ...inspectOptions, compact: 3, colors: false, depth: 0 });
1132 }
1133 break;
1134 }
1135 case 106:
1136 tempStr = tryStringify(args[++a]);
1137 break;
1138 case 100: {
1139 const tempNum = args[++a];
1140 if (typeof tempNum === 'bigint') tempStr = formatBigInt(tempNum, inspectOptions?.numericSeparator);
1141 else if (typeof tempNum === 'symbol') tempStr = 'NaN';
1142 else tempStr = formatNumber(Number(tempNum), inspectOptions?.numericSeparator);
1143 break;
1144 }
1145 case 79:
1146 tempStr = inspect(args[++a], inspectOptions);
1147 break;
1148 case 111:
1149 tempStr = inspect(args[++a], { ...inspectOptions, showHidden: true, showProxy: true, depth: 4 });
1150 break;
1151 case 105: {
1152 const tempInteger = args[++a];
1153 if (typeof tempInteger === 'bigint') tempStr = formatBigInt(tempInteger, inspectOptions?.numericSeparator);
1154 else if (typeof tempInteger === 'symbol') tempStr = 'NaN';
1155 else tempStr = formatNumber(Number.parseInt(tempInteger), inspectOptions?.numericSeparator);
1156 break;
1157 }
1158 case 102: {
1159 const tempFloat = args[++a];
1160 if (typeof tempFloat === 'symbol') tempStr = 'NaN';
1161 else tempStr = formatNumber(Number.parseFloat(tempFloat), inspectOptions?.numericSeparator);
1162 break;
1163 }
1164 case 99:
1165 a += 1;
1166 tempStr = '';
1167 break;
1168 case 37:
1169 str += first.slice(lastPos, i);
1170 lastPos = i + 1;
1171 continue;
1172 default:
1173 continue;
1174 }
1175 if (lastPos !== i - 1) str += first.slice(lastPos, i - 1);
1176 str += tempStr;
1177 lastPos = i + 1;
1178 } else if (nextChar === 37) {
1179 str += first.slice(lastPos, i);
1180 lastPos = i + 1;
1181 }
1182 }
1183 }
1184 if (lastPos !== 0) {
1185 a++;
1186 join = ' ';
1187 if (lastPos < first.length) str += first.slice(lastPos);
1188 }
1189 }
1190 while (a < args.length) {
1191 const value = args[a];
1192 str += join;
1193 str += typeof value !== 'string' ? inspect(value, inspectOptions) : value;
1194 join = ' ';
1195 a++;
1196 }
1197 return str;
1198 }
1199
1200 // Node's globals, as far as they go without files, processes or the network.
1201 function stream(fd, name) {
1202 return guard({
1203 write(chunk, ...rest) {
1204 if (typeof chunk !== 'string' || rest.length !== 0) refuse(`${name}.write with anything but text`);
1205 out(fd, chunk);
1206 return true;
1207 },
1208 }, name);
1209 }
1210 const process = guard({ stdout: stream(1, 'process.stdout'), stderr: stream(2, 'process.stderr') }, 'process');
1211 const util = guard({
1212 inspect,
1213 format: (...args) => formatWithOptions(undefined, args),
1214 formatWithOptions: (options, ...args) => formatWithOptions(options, args),
1215 }, 'util');
1216 const modules = { process, util };
1217 function require(id) {
1218 const name = typeof id === 'string' && id.startsWith('node:') ? id.slice(5) : id;
1219 if (Object.prototype.hasOwnProperty.call(modules, name)) return modules[name];
1220 const error = new Error(`Cannot find module '${id}'`);
1221 error.code = 'MODULE_NOT_FOUND';
1222 throw error;
1223 }
1224 const print = (fd) => (...args) => out(fd, formatWithOptions(undefined, args) + '\n');
1225 const console = guard({
1226 log: print(1), info: print(1), debug: print(1), warn: print(2), error: print(2),
1227 dir(object, options) { out(1, inspect(object, { customInspect: false, ...options }) + '\n'); },
1228 }, 'console');
1229
1230 // Timers run after the script, in order of when they are due, as Node's event loop runs them.
1231 class Timeout {
1232 constructor(timer) { this[timerKey] = timer; }
1233 ref() { this[timerKey].ref = true; return this; }
1234 unref() { this[timerKey].ref = false; return this; }
1235 hasRef() { return this[timerKey].ref; }
1236 [Symbol.toPrimitive]() { return this[timerKey].id; }
1237 [customInspectSymbol]() { refuse('util.inspect of a Timeout'); }
1238 }
1239 const timerKey = Symbol('timer');
1240 function schedule(callback, delay, args, repeat) {
1241 if (typeof callback !== 'function') {
1242 const error = new TypeError(`The "callback" argument must be of type function. Received ${inspect(callback)}`);
1243 error.code = 'ERR_INVALID_ARG_TYPE';
1244 throw error;
1245 }
1246 delay *= 1;
1247 if (!(delay >= 1 && delay <= 2 ** 31 - 1)) delay = 1;
1248 const timer = { id: ++state.seq, seq: state.seq, due: state.now + delay, delay, callback, args, repeat, ref: true };
1249 timer.timeout = new Timeout(timer);
1250 state.timers.push(timer);
1251 return timer.timeout;
1252 }
1253 function clear(timeout) {
1254 const timer = timeout && typeof timeout === 'object' ? timeout[timerKey]
1255 : state.timers.find((t) => t.id === Number(timeout));
1256 state.timers = state.timers.filter((t) => t !== timer);
1257 }
1258 function uncaught(error) {
1259 if (state.error === undefined) state.error = describe(error);
1260 state.dead = true;
1261 }
1262 function describe(error) {
1263 if (error instanceof Error) {
1264 let message = String(error.message);
1265 const missing = /^Can't find variable: (.*)$/.exec(message);
1266 if (error.name === 'ReferenceError' && missing) message = `${missing[1]} is not defined`;
1267 return message === '' ? String(error.name) : `${error.name}: ${message}`;
1268 }
1269 try { return `Uncaught ${inspect(error)}`; } catch { return 'Uncaught exception'; }
1270 }
1271
1272 const globals = {
1273 require, console, process, global: globalThis, Proxy: ProxyConstructor, module: { exports: {} }, __filename: '[stdin]', __dirname: '.',
1274 setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false),
1275 setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true),
1276 clearTimeout: clear, clearInterval: clear,
1277 queueMicrotask(callback) {
1278 if (typeof callback !== 'function') throw new TypeError('The "callback" argument must be of type function.');
1279 Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } });
1280 },
1281 };
1282 globals.exports = globals.module.exports;
1283 for (const [name, value] of Object.entries(globals)) {
1284 Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
1285 }
1286 for (const name of ['Buffer', 'setImmediate', 'clearImmediate', 'structuredClone', 'atob', 'btoa', 'performance', 'fetch',
1287 'crypto', 'navigator', 'URL', 'URLSearchParams', 'TextEncoder', 'TextDecoder', 'AbortController', 'AbortSignal',
1288 'Event', 'EventTarget', 'Blob', 'Headers', 'Request', 'Response', 'FormData', 'WebSocket', 'MessageChannel',
1289 'BroadcastChannel']) {
1290 if (!(name in globalThis)) {
1291 Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true });
1292 }
1293 }
1294
1295 return {
1296 // A script run as `node` runs standard input; an uncaught error ends it.
1297 main(source) {
1298 try { evaluate(source); } catch (error) { uncaught(error); }
1299 },
1300 begin() {
1301 state.dead = false;
1302 state.error = undefined;
1303 state.refused = '';
1304 state.now = Date.now();
1305 },
1306 // After a session's script: its error, or its value as the session writes it.
1307 failed(error) { uncaught(error); },
1308 inspect(value) { return inspect(value); },
1309 // Runs the next timer that is due: the milliseconds until one is, 0 after running one,
1310 // or -1 when none is left to wait for.
1311 tick() {
1312 if (state.dead || !state.timers.some((t) => t.ref)) return -1;
1313 state.now = Date.now();
1314 const next = state.timers.reduce((a, b) => (b.due < a.due || (b.due === a.due && b.seq < a.seq) ? b : a));
1315 if (next.due > state.now) return next.due - state.now;
1316 if (next.repeat) {
1317 next.due = state.now + next.delay;
1318 next.seq = ++state.seq;
1319 } else {
1320 clear(next.timeout);
1321 }
1322 try { next.callback.apply(next.timeout, next.args); } catch (error) { uncaught(error); }
1323 return 0;
1324 },
1325 get error() { return state.error; },
1326 get refused() { return state.refused; },
1327 };
1328 })
1329 """#
1330 }
1331}
1332#endif
Sources/OrgPrograms/Programs.swift +8 −1
@@ -8,7 +8,14 @@ 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.
12 switch job.runner {
13 case .process(let executable, _), .session(_, let executable, _):
14 if !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
15 case .emacs:
16 break
17 }
18 return try await BabelRunner.run(job, fileDirectory: fileDirectory)
12 } 19 }
13 20
14 public func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String { 21 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 +181
@@ -0,0 +1,181 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// js blocks in JavaScriptCore, compared with node and with Emacs running node.
8struct JavaScriptBlocksTests {
9 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
10 static let nodeInstalled = (try? node("1", in: FileManager.default.temporaryDirectory))?.status == 0
11
12 static func plan(_ text: String) throws -> BabelJob {
13 let caret = (text as NSString).range(of: "#+begin_src").location + 2
14 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
15 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned: \(text)") }
16 return job
17 }
18
19 /// `node` reading `input` on standard input, as BabelRunner starts it.
20 static func node(_ input: String, in folder: URL) throws -> (stdout: String, status: Int32) {
21 let process = Process()
22 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
23 process.arguments = ["node"]
24 process.currentDirectoryURL = folder
25 let stdin = Pipe(), stdout = Pipe()
26 process.standardInput = stdin
27 process.standardOutput = stdout
28 process.standardError = FileHandle.nullDevice
29 try process.run()
30 stdin.fileHandleForWriting.write(Data(input.utf8))
31 try stdin.fileHandleForWriting.close()
32 let data = stdout.fileHandleForReading.readDataToEndOfFile()
33 process.waitUntilExit()
34 return (String(decoding: data, as: UTF8.self), process.terminationStatus)
35 }
36
37 static let values = [
38 "1", "-0", "1.5", "1e21", "NaN", "123n", "true", "null", "undefined", "'abc'", "\"it's\"", "'say \"hi\" it\\'s'",
39 "'tab\\there\\n'", "'é 日本'", "'x'.repeat(100)", "Symbol('s')", "[]", "[1, 'a', null, undefined]", "[[1, 2], [3, 4]]",
40 "[[[[1]]]]", "{a: {b: {c: {d: 1}}}}", "Array.from({length: 26}, (_, i) => i * 3)", "Array.from({length: 30}, (_, i) => 'item' + i)",
41 "Array.from({length: 120}, (_, i) => i)", "[-1, -22, 333, 4, -5, 6, 7, 8, 9, 10, 11]", "[1, , 3]", "new Array(5)",
42 "Object.assign([1, 2], {extra: true})", "{'a-b': 1, 2: 3, _x: 4}", "{[Symbol('k')]: 1}", "Object.create(null)",
43 "{f() {}, g: () => 1, h: class K {}}", "{longPropertyNameOne: 'value number one', longPropertyNameTwo: 'value number two', three: 3}",
44 "(() => { const o = {name: 'x'}; o.self = o; return o; })()", "new Map([['a', 1], ['b', {c: 2}]])", "new Set([1, 'two', [3]])",
45 "new (class Point { constructor() { this.x = 1; } })()", "new Date(0)", "/ab+c/gi", "new Uint8Array([1, 2, 3])",
46 "new ArrayBuffer(4)", "new Number(3)", "new WeakMap()", "(function () { return arguments; })(1, 2)",
47 "Object.defineProperty({}, 'x', {get() { return 1; }, enumerable: true})", "new Proxy(new Proxy([1], {}), {})",
48 "{[require('util').inspect.custom]() { return 'custom!'; }}",
49 "{data: Array.from({length: 12}, (_, i) => ({n: i, sq: i * i}))}",
50 ]
51
52 static let programs = [
53 "console.log('%s is %d years', 'Bob', 42)", "console.log('%i %f %j', '42.9px', '1.5e3', {a: [1]})",
54 "console.log('%o', [1, {a: 2}])", "console.log('%O', {a: {b: {c: {d: 1}}}})", "console.log('100%% sure', 5)",
55 "console.log('%s', [1, [2, [3]]], null, 3n)", "console.log('a', 1, 'b', {c: 1})", "console.log()",
56 "console.info('info'); console.error('err'); console.warn('warn')", "console.dir({a: {b: {c: {d: 1}}}}, {depth: 0})",
57 "process.stdout.write('a'); process.stdout.write('b')", "const util = require('util'); console.log(util.format('%s=%d', 'x', 5, 'rest'))",
58 "const {inspect} = require('node:util'); console.log(inspect({a: [1, {b: {c: {}}}]}, {depth: null, compact: false}))",
59 "console.log(require('util').inspect({s: 'a string', l: [1, 2, 3]}, {breakLength: 20, sorted: true}))",
60 "setTimeout(() => console.log('b'), 20); setTimeout(() => console.log('a'), 5); setTimeout(() => console.log('c'), 5)",
61 "Promise.resolve().then(() => console.log('micro')); setTimeout(() => console.log('macro'), 0); console.log('sync')",
62 "let n = 0; const t = setInterval(() => { console.log('tick', ++n); if (n === 3) clearInterval(t); }, 1)",
63 "queueMicrotask(() => console.log('q')); (async () => { await null; console.log('awaited'); })(); console.log('s')",
64 "console.log('before'); undefinedThing.x; console.log('after')",
65 "Promise.resolve().then(() => console.log('not printed')); throw new Error('sync')",
66 "setTimeout(() => { throw new TypeError('in timer'); }, 1); setTimeout(() => console.log('not reached'), 5)",
67 "var x = 5; console.log(globalThis.x, this === globalThis, typeof module, __filename, global === globalThis)",
68 "console.log(JSON.stringify({a: 1, b: [1, 2]}, null, 2), [3, 1, 2].sort(), 0.1 + 0.2)",
69 ]
70
71 /// The values a block returns, printed by `util.inspect`, and what `console` and timers
72 /// print, as node prints them.
73 @Test(.enabled(if: oracle && nodeInstalled))
74 func matchesNode() async throws {
75 let folder = FileManager.default.temporaryDirectory
76 let blocks = Self.values.map { "#+begin_src js\nreturn \($0)\n#+end_src\n" }
77 + Self.programs.map { "#+begin_src js :results output\n\($0)\n#+end_src\n" }
78 for block in blocks {
79 let job = try Self.plan(block)
80 let theirs = try Self.node(job.input, in: folder)
81 let ours = try await JavaScriptBlocks.run(job, directory: folder)
82 #expect(ours?.stdout == theirs.stdout && ours?.status == theirs.status, "\(block)\nours: \(ours?.stdout ?? "nil") \(ours?.stderr ?? "")\nnode: \(theirs.stdout)")
83 }
84 }
85
86 static let emacsCases: [String] = [
87 "#+begin_src js :var x=3\nreturn x * 2\n#+end_src\n",
88 "#+begin_src js :var x=3 :results output\nconsole.log(x + 1)\n#+end_src\n",
89 "#+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",
90 "#+NAME: tbl\n| 1 | 2 |\n| 3 | 4 |\n\n#+begin_src js :var t=tbl\nreturn t\n#+end_src\n",
91 "#+begin_src js :var s=\"two words\"\nreturn s.length\n#+end_src\n",
92 "#+begin_src js :prologue var k = 7; :epilogue return k;\nk = k * 6;\n#+end_src\n",
93 "#+begin_src js\nreturn 'abc'\n#+end_src\n",
94 "#+begin_src js :results output :epilogue console.log('end')\nconsole.log('body')\n#+end_src\n",
95 "#+begin_src js\nreturn {a: 1, b: [1, 2]}\n#+end_src\n",
96 "#+begin_src js :results output\nsetTimeout(() => console.log('later'), 10); console.log('now')\n#+end_src\n",
97 ]
98
99 /// The results the app inserts, as Emacs inserts them running the block with node.
100 @MainActor
101 @Test(.enabled(if: oracle && nodeInstalled))
102 func resultsMatchEmacs() async throws {
103 let folder = try Folder()
104 var forms: [String] = []
105 var ours: [String] = []
106 for text in Self.emacsCases {
107 let caret = (text as NSString).range(of: "#+begin_src").location + 2
108 let file = try folder.write("b.org", text)
109 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
110 session.open(file.path)
111 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) else {
112 Issue.record("not planned: \(text)")
113 return
114 }
115 #expect(await session.runBabel(job) == "Code block evaluation complete.")
116 ours.append(session.document?.text ?? "")
117 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
118 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (org-babel-execute-src-block) (princ (concat (buffer-string) \"\\f\")))")
119 }
120 let emacs = try DailiesTests.emacs("""
121 (progn (require 'org) (require 'ob-js)
122 (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" default-directory "\(folder.url.path)/")
123 \(forms.joined(separator: "\n")))
124 """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
125 for (i, text) in Self.emacsCases.enumerated() {
126 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
127 }
128 }
129
130 @Test func tableRulesAndModulesFailAsInNode() async throws {
131 let folder = FileManager.default.temporaryDirectory
132 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)
133 #expect(rule == BabelOutput(stdout: "", stderr: "ReferenceError: hline is not defined\n", status: 1))
134 let fs = try await JavaScriptBlocks.run(Self.plan("#+begin_src js\nreturn require('fs').readFileSync('x')\n#+end_src\n"), directory: folder)
135 #expect(fs == BabelOutput(stdout: "", stderr: "Error: Cannot find module 'fs'\n", status: 1))
136 }
137
138 @Test func whatNodeAloneHasIsRefused() async throws {
139 let folder = FileManager.default.temporaryDirectory
140 for (body, what) in [("return new Error('x')", "util.inspect of an Error"), ("return Promise.resolve(1)", "util.inspect of a Promise"),
141 ("return Buffer.from('a')", "Buffer"), ("return process.env.HOME", "process.env"),
142 ("console.table([1])", "console.table")] {
143 await #expect(throws: Babel.Failure.message("This block uses \(what), which runs only in node.")) {
144 try await JavaScriptBlocks.run(Self.plan("#+begin_src js\n\(body)\n#+end_src\n"), directory: folder)
145 }
146 }
147 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil)
148 await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) {
149 try await JavaScriptBlocks.run(Self.plan("#+begin_src js :dir nowhere\nreturn 1\n#+end_src\n"), directory: folder)
150 }
151 }
152
153 @Test func sessionsKeepTheirContext() async throws {
154 let folder = try Folder()
155 func run(_ header: String, _ body: String) async throws -> BabelOutput? {
156 try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\(header)\n\(body)\n#+end_src\n"), directory: folder.url)
157 }
158 #expect(try await run("", "var x = 41; let y = 2")?.resultFile == "undefined")
159 #expect(try await run("", "x + y")?.resultFile == "43")
160 #expect(try await run("", "throw new Error('boom')") == BabelOutput(stdout: "", stderr: "Error: boom\n", status: 1))
161 #expect(try await run("", "[x, {y}]")?.resultFile == "[ 41, { y: 2 } ]")
162 #expect(try await run(" :results output", "console.log(x); x") == BabelOutput(stdout: "41\n"))
163 let other = try Folder()
164 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'")
165 }
166
167 @Test func cancelAndTimeoutEndTheRun() async throws {
168 let folder = FileManager.default.temporaryDirectory
169 // Spins for seconds, as an endless loop would, but ends so the test leaves no thread busy.
170 let spin = try Self.plan("#+begin_src js\nconst end = Date.now() + 3000; while (Date.now() < end) {}\n#+end_src\n")
171 let start = ContinuousClock.now
172 let task = Task { try await JavaScriptBlocks.run(spin, directory: folder) }
173 try await Task.sleep(for: .milliseconds(100))
174 task.cancel()
175 await #expect(throws: CancellationError.self) { try await task.value }
176 await #expect(throws: JavaScriptBlocks.Stopped.self) { try await JavaScriptBlocks.run(spin, directory: folder, timeout: .milliseconds(100)) }
177 #expect(ContinuousClock.now - start < .seconds(2))
178 let interval = try Self.plan("#+begin_src js :results output\nsetInterval(() => {}, 10)\n#+end_src\n")
179 await #expect(throws: JavaScriptBlocks.Stopped.self) { try await JavaScriptBlocks.run(interval, directory: folder, timeout: .milliseconds(100)) }
180 }
181}
Tests/OrgProgramsTests/ProgramsTests.swift +19
@@ -173,3 +173,22 @@ 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 @Test(.enabled(if: BabelRunner.installed("node")))
191 func usesNodeWhenInstalled() async throws {
192 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
193 }
194}
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 block runs as =node= runs a program on standard input, and 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.
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= and =console= (=process.env=, =console.table=), Node's other globals (=Buffer=, =fetch=, =URL=, =TextEncoder=, =setImmediate=, =structuredClone=), and printing an =Error=, a =Promise= or an iterator 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.