Commit ea71ae826c

ea71ae826c3d74a17b301811f18cc4fe05aa0bd3

parent: 537216e8fd

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 18:52 UTC

Run js blocks as node FILE, as ob-js does

Layout: unified · split

Sources/OrgApp/JavaScriptBlocks.swift +6 −5
@@ -19,7 +19,7 @@ public enum JavaScriptBlocks {
19 switch job.runner { 19 switch job.runner {
20 case .process: 20 case .process:
21 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") } 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) } 22 return try await evaluate(timeout: timeout) { run in try Engine().main(job.script ?? job.input, run: run) }
23 case .session(let name, _, .node): 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.") } 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. 25 // One context per file folder and session name; a stopped run's context is dropped.
@@ -41,19 +41,20 @@ public enum JavaScriptBlocks {
41 /// and is still running is refused without starting another. 41 /// and is still running is refused without starting another.
42 public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? { 42 public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? {
43 guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } 43 guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil }
44 if abandoned.contains(job.input) { throw Stopped(description: "The block took too long before and is still running.") } 44 let source = job.script ?? job.input
45 if abandoned.contains(source) { throw Stopped(description: "The block took too long before and is still running.") }
45 let run = Run() 46 let run = Run()
46 let flag = Abandoned.Flag() 47 let flag = Abandoned.Flag()
47 let thread = Thread { 48 let thread = Thread {
48 run.end(Result { try Engine().main(job.input, run: run) }) 49 run.end(Result { try Engine().main(source, run: run) })
49 abandoned.ended(job.input, flag) 50 abandoned.ended(source, flag)
50 } 51 }
51 thread.stackSize = 8 << 20 52 thread.stackSize = 8 << 20
52 thread.start() 53 thread.start()
53 do { 54 do {
54 return try run.result(within: timeout) 55 return try run.result(within: timeout)
55 } catch let error as Stopped { 56 } catch let error as Stopped {
56 abandoned.add(job.input, flag) 57 abandoned.add(source, flag)
57 throw error 58 throw error
58 } 59 }
59 } 60 }
Sources/OrgCore/Compute/Babel.swift +8 −5
@@ -585,11 +585,14 @@ public enum Babel {
585 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true)) 585 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true))
586 )) 586 ))
587 } 587 }
588 return .success(BabelJob( 588 // `org-babel-execute:js`: the program in a file, run as `:cmd FILE`, with the
589 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments), 589 // newline `org-babel-eval` sends as its input.
590 input: output ? full : jsWrapper(full), directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, 590 var job = BabelJob(
591 finish: finishBase(.script(js: true)) 591 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: [scriptFileToken]),
592 )) 592 input: "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true))
593 )
594 job.script = output ? full : jsWrapper(full)
595 return .success(job)
593 case "awk": 596 case "awk":
594 // `org-babel-expand-body:awk`; the variables go on the command line. 597 // `org-babel-expand-body:awk`; the variables go on the command line.
595 let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "") 598 let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
Sources/OrgPrograms/BabelRunner.swift +6 −3
@@ -2,8 +2,8 @@
2import Foundation 2import Foundation
3import OrgCore 3import OrgCore
4 4
5/// Runs Babel jobs as processes: the interpreter reads the program on standard input, in the 5/// Runs Babel jobs as processes, in the file's folder or `:dir`: the interpreter reads the
6/// file's folder or `:dir`. 6/// program on standard input, or from the file `job.script` is written to.
7public enum BabelRunner { 7public enum BabelRunner {
8 public struct Failure: Error, CustomStringConvertible { 8 public struct Failure: Error, CustomStringConvertible {
9 public let description: String 9 public let description: String
@@ -51,7 +51,10 @@ public enum BabelRunner {
51 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) 51 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path)
52 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) } 52 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) }
53 } 53 }
54 process.arguments = [executable] + arguments 54 // A command with arguments, such as `:cmd "node --no-warnings"`, runs in the shell as
55 // Org runs it.
56 process.arguments = executable.contains(where: \.isWhitespace)
57 ? ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments : [executable] + arguments
55 case .emacs: 58 case .emacs:
56 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") } 59 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") }
57 let script = folder.appendingPathComponent("babel.el") 60 let script = folder.appendingPathComponent("babel.el")
Tests/OrgAppTests/JavaScriptBlocksTests.swift +1 −1
@@ -88,7 +88,7 @@ struct JavaScriptBlocksTests {
88 + Self.programs.map { "#+begin_src js :results output\n\($0)\n#+end_src\n" } 88 + Self.programs.map { "#+begin_src js :results output\n\($0)\n#+end_src\n" }
89 for block in blocks { 89 for block in blocks {
90 let job = try Self.plan(block) 90 let job = try Self.plan(block)
91 let theirs = try Self.node(job.input, in: folder) 91 let theirs = try Self.node(try #require(job.script), in: folder)
92 let ours = try await JavaScriptBlocks.run(job, directory: folder) 92 let ours = try await JavaScriptBlocks.run(job, directory: folder)
93 #expect(ours?.stdout == theirs.stdout && ours?.status == theirs.status, "\(block)\nours: \(ours?.stdout ?? "nil") \(ours?.stderr ?? "")\nnode: \(theirs.stdout)") 93 #expect(ours?.stdout == theirs.stdout && ours?.status == theirs.status, "\(block)\nours: \(ours?.stdout ?? "nil") \(ours?.stderr ?? "")\nnode: \(theirs.stdout)")
94 } 94 }
Tests/OrgProgramsTests/ProgramsTests.swift +70
@@ -256,6 +256,76 @@ struct JavaScriptFallbackTests {
256 } 256 }
257} 257}
258 258
259/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them.
260@MainActor
261@Suite(.programs)
262struct NodeFileTests {
263 static let cases = [
264 "#+begin_src js :results output\nconsole.log(typeof require, typeof module, typeof exports, process.argv.length, require.main === module)\n#+end_src\n",
265 "#+begin_src js :results output\nconst path = require('path'), fs = require('fs')\nconsole.log(path.dirname(__filename) === __dirname, __dirname === process.cwd(), "
266 + "path.dirname(__dirname) === fs.realpathSync(require('os').tmpdir()), path.basename(process.argv[1]) === path.basename(__filename))\n#+end_src\n",
267 "#+begin_src js\nreturn [typeof require, typeof module, process.argv.length, this === module.exports]\n#+end_src\n",
268 "#+begin_src js :results output\ntry { require('./helper'); console.log('found') } catch (e) { console.log(e.code) }\nconsole.log(require(process.cwd() + '/helper'))\n#+end_src\n",
269 "#+begin_src js :results output\nimport os from 'os'\nconsole.log(typeof require, typeof os.tmpdir)\n#+end_src\n",
270 "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n",
271 "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n",
272 "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n",
273 ]
274
275 /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs
276 /// sets it; `--batch` leaves it nil and writes the file straight into the temporary folder.
277 @Test(.enabled(if: EmacsRunner.executable() != nil && BabelRunner.installed("node") && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
278 func resultsMatchEmacs() async throws {
279 let folder = try Folder()
280 try folder.write("helper.js", "module.exports = 1\n")
281 var forms: [String] = []
282 var ours: [String] = []
283 for text in Self.cases {
284 let file = try folder.write("b.org", text)
285 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
286 session.open(file.path)
287 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
288 Issue.record("not planned: \(text)")
289 return
290 }
291 _ = await session.runBabel(job)
292 ours.append(session.document?.text ?? "")
293 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
294 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char 3) (org-babel-execute-src-block) (princ (concat (buffer-string) \"\\f\")))")
295 }
296 let process = Process()
297 process.executableURL = EmacsRunner.executable()
298 process.currentDirectoryURL = folder.url
299 process.arguments = ["-Q", "--batch", "--eval", """
300 (progn (require 'org) (require 'ob-js)
301 (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" org-babel-temporary-directory (make-temp-file "babel-" t))
302 \(forms.joined(separator: "\n"))
303 (delete-directory org-babel-temporary-directory t))
304 """]
305 let out = Pipe()
306 process.standardOutput = out
307 process.standardError = FileHandle.nullDevice
308 try process.run()
309 let emacs = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
310 .split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
311 process.waitUntilExit()
312 for (i, text) in Self.cases.enumerated() {
313 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
314 }
315 }
316
317 /// The file is gone once the block has run.
318 @Test(.enabled(if: BabelRunner.installed("node")))
319 func removesTheFile() async throws {
320 let text = "#+begin_src js :results output\nconsole.log(__filename)\n#+end_src\n"
321 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
322 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
323 let output = try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory)
324 let file = output.stdout.trimmingCharacters(in: .newlines)
325 #expect(file.hasPrefix("/") && !FileManager.default.fileExists(atPath: file))
326 }
327}
328
259/// Emacs Lisp runs in `Elisp` when Emacs isn't installed. 329/// Emacs Lisp runs in `Elisp` when Emacs isn't installed.
260struct EmacsLispFallbackTests { 330struct EmacsLispFallbackTests {
261 func run(_ text: String) async throws -> BabelOutput { 331 func run(_ text: String) async throws -> BabelOutput {
docs/manual/guide/11-code-blocks.org +2 −2
@@ -91,13 +91,13 @@ 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=, or the interpreter; see below | 92| =emacs-lisp=, =elisp= | =emacs -Q --batch=, or the interpreter; see below |
93| =ruby= | =ruby=, or the program in =:ruby= | 93| =ruby= | =ruby=, or the program in =:ruby= |
94| =js=, =javascript= | =node=, or JavaScriptCore without it; see below | 94| =js=, =javascript= | =node FILE=, the program written to a file, or JavaScriptCore without node; 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 |
98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below | 98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
99 99
100For =js=, =javascript= and =R=, =:cmd= names a different program. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads. 100For =js=, =javascript= and =R=, =:cmd= names a different program. A program given with options, such as =:cmd "node --no-warnings"=, runs through =/bin/sh=, as Org runs it. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
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