tsjs.cr

Runs TypeScript in Crystal.

tsjs.cr

Runs TypeScript in Crystal. Erasable TypeScript is stripped to JavaScript with Sucrase and run in an embedded QuickJS-ng engine, sandboxed and with limits: memory, stack, and a time budget per run. The bundled versions are in vendor/quickjs/VERSION and vendor/sucrase/PACKAGES, and at runtime in Radbas::TSJS.quickjs_version and Radbas::TSJS::Transformer::SUCRASE_VERSION.

Scripts see only standard JavaScript plus the host functions you define. There is no fs, process, fetch or setTimeout, and nothing is read from disk: modules come from a resolver callback.

Installation

dependencies:
  radbas-tsjs:
    github: radbas/tsjs.cr
    version: ~> 0.1

shards install compiles the vendored engine (make -C ext as postinstall), which needs only cc and ar. If ext/libquickjs.a is missing, the build stops with a message telling you to run make -C lib/radbas-tsjs/ext.

Requires Crystal >= 1.22. Linux and macOS-style toolchains with glibc or musl, x86_64 and aarch64. Static builds work (crystal build --static, e.g. on Alpine).

Usage

require "radbas-tsjs"

# Long-lived, one per worker fiber. Not thread-safe, not shareable between fibers.
runtime = Radbas::TSJS::Runtime.new(memory_limit: 64 * 1024 * 1024, stack_size: 1024 * 1024)

result = runtime.with_context(timeout: 5.seconds) do |ctx|
  ctx.module_loader = ->(name : String) : Radbas::TSJS::Source? {
    store.find(name).try { |s| Radbas::TSJS::Source.new(s.code, :typescript) }
  }

  ctx.define_function("__host_log") do |args| # Array(JSON::Any) -> anything to_json-able
    logs << args.map(&.to_s).join(" ")
    nil # undefined
  end

  mod = ctx.import("flows/notify.ts")       # loads, links and evaluates
  ctx.call(mod, "default", [event, config]) # awaits the promise; JSON::Any
end                                         # context freed here, always

runtime.close

Runtime and context

  • Runtime.new(memory_limit:, stack_size:): one QuickJS heap. Defaults: 64 MiB and 1 MiB; 0 disables a limit.
  • runtime.with_context(timeout: nil) { |ctx| … }: creates a fresh context (global scope and module cache), yields it and frees it, also when the block raises. A context never outlives the block. Returns the block's value.
  • timeout is the budget for the whole block. It is checked while JavaScript runs and while promises are awaited; time spent in host functions counts too, but host functions must bound their own I/O.
  • runtime.cancel stops the current run from another fiber or thread (CancelledError), e.g. when a job lease is lost.
  • runtime.on_unhandled_rejection { |error| … }: promise rejections that no handler caught by the end of a run. They don't fail the run; without a hook they are logged as warnings (Log source radbas.tsjs).
  • runtime.memory_usage, runtime.gc, runtime.close. Recycle a runtime after N runs or above a memory threshold if you like. A runtime that is never closed leaks its engine memory (a finalizer only warns).

Running code

  • ctx.eval(code, filename = "<eval>") runs a script and returns its completion value as JSON::Any. A promise completion value is awaited.
  • ctx.eval(code, filename, module: true) runs an ES module (imports relative to filename, top-level await); returns nil.
  • ctx.import(name) returns a Radbas::TSJS::Module. name is relative to the module root (flows/notify.ts) or an allowed bare specifier.
  • ctx.call(mod, export, args) and ctx.call(global_function, args) call a function with JSON arguments (anything with to_json) and return the result as JSON. A returned promise is awaited.

Values cross the boundary as JSON: undefined becomes nil, inside objects the rules of JSON.stringify apply (functions are dropped, NaN becomes null). A function, symbol, BigInt or cycle as a result raises ConversionError.

Promise jobs run only while something is awaited (eval, import, call). Jobs still queued when the context ends are discarded and never run.

Modules

Module names are POSIX-style paths below a virtual root. The resolver (ctx.module_loader) gets a name and returns a Radbas::TSJS::Source or nil:

  • Radbas::TSJS::Source.new(code, :typescript | :javascript | :json). The kind alone decides how a module is treated; its name doesn't. Radbas::TSJS::Source.for(name, code) picks the kind from .ts/.mts, .js/.mjs or .json and raises ArgumentError for any other name.
  • ./x and ../x resolve against the importing module; .. above the root is rejected.
  • Specifiers are used as written, as in browsers and Node: ./util.ts, not ./util. The resolver is asked for exactly that name. In the editor, "allowImportingTsExtensions": true lets TypeScript accept .ts imports.
  • Bare specifiers are rejected unless allowed with ctx.allow_module("radbas"), which is how you offer your own virtual modules.
  • Absolute paths, URLs and scheme specifiers (qjs:std, node:fs) are rejected.
  • JSON modules export the parsed value as default. The only accepted import attribute is with { type: "json" }. A module's identity includes its attributes: importing the same file with and without them yields two separate instances.
  • TypeScript modules are stripped with Sucrase; the results of the last 256 sources are cached. Modules are cached per context, so a new run always sees changed sources.

Host functions

ctx.define_function(name) { |args| … } defines a global function. Arguments arrive as Array(JSON::Any); the block's result is converted with to_json (nil is undefined, JSON::Any.new(nil) is null).

  • An exception in the block becomes a JavaScript Error named HostError that scripts can catch. Uncaught, it surfaces as a ScriptError whose cause is the original exception.
  • TimeoutError, CancelledError and MemoryError (e.g. from a nested ctx.call) can't be caught by scripts and are raised again in Crystal.
  • Host functions may call back into the context (ctx.call, ctx.eval).
  • They may block (HTTP, database): only the calling fiber waits.

Only flat global functions are offered. Wrap them in a nicer API with a JS/TS prelude module (e.g. import { http } from "radbas").

Transforming and checking

js = Radbas::TSJS.transform(source, filename: "flows/notify.ts") # raises Radbas::TSJS::SyntaxError
js = Radbas::TSJS.check(source, filename: "flows/notify.ts")     # transform + compile, no run

Radbas::TSJS.check also catches JavaScript syntax errors that Sucrase lets through; imports aren't resolved. Use it on save. Sucrase keeps line numbers, so stack traces point at the TypeScript lines.

There is no type checking: editors do that with .d.ts files. Only erasable TypeScript is accepted, the same as TypeScript's erasableSyntaxOnly with verbatimModuleSyntax and Node's type stripping: types are removed and no code is generated. These raise a SyntaxError with their location:

  • enum and const enum (use an object with as const)
  • parameter properties, constructor(private x: number)
  • namespaces with runtime code; namespaces that only hold types are fine
  • import x = require(…), import x = N.y and export =

Ambient declarations (declare enum, declare namespace, declare module) are types and are allowed. Imports are kept as written: an import is removed only when it is marked type (import type { T }, import { type T }), so importing a type without type fails when the module is linked (a ScriptError: "Could not find export"). Set "erasableSyntaxOnly": true and "verbatimModuleSyntax": true in the editor's tsconfig.json to see these errors while writing. JSX and CommonJS aren't supported.

Transforms run in their own QuickJS runtime, apart from user limits. A pool guarded by a channel serves Radbas::TSJS.transform/check; its size is Radbas::TSJS.transformer_pool_size (default 1, set before the first transform). Each transformer compiles the bundle once (about 25 ms).

Errors

Every public method raises a subclass of Radbas::TSJS::Error:

Error When
Radbas::TSJS::SyntaxError transform or compile failed; #filename, #line, #column (1-based)
Radbas::TSJS::ScriptError an uncaught JS exception; #name, #js_message, #stack
Radbas::TSJS::TimeoutError the time budget was exceeded
Radbas::TSJS::CancelledError Runtime#cancel stopped the run
Radbas::TSJS::MemoryError the memory limit was hit (scripts can't catch it)
Radbas::TSJS::StackOverflowError the stack limit was hit (scripts can catch it as a RangeError)
Radbas::TSJS::UnsettledPromiseError a promise stays pending and no jobs are left
Radbas::TSJS::ModuleNotFoundError the resolver returned nil, or the specifier isn't allowed; #specifier
Radbas::TSJS::ConversionError a value isn't JSON-representable
Radbas::TSJS::BusyError the runtime is already running a context, or is closed

Once a run timed out or was cancelled, every further call in that block raises the same error.

Threads and fibers

A runtime must only be used by one fiber at a time; a second with_context raises BusyError. Run scripts in a single-threaded execution context (Fiber::ExecutionContext::Concurrent or Isolated) with one runtime per worker fiber.

In a parallel execution context, a fiber may resume on another thread after a blocking host call. QuickJS-ng's core appears to keep no thread-local state (that lives in quickjs-libc, which isn't linked), and the specs run that setup, but it isn't guaranteed: prefer the single-threaded one.

Crystal fiber stacks are 8 MiB; the default 1 MiB JS stack leaves room for the Crystal frames of host functions that run on top of the engine's frames.

Context intrinsics

Contexts get Object, Function, Array, Error, Symbol, BigInt, Math, Reflect, Iterator, Date, RegExp, JSON, Proxy, Map/Set/WeakMap/WeakSet, typed arrays and Promise. Left out: WeakRef/FinalizationRegistry (behaviour depends on the GC), performance, DOMException and atob/btoa.

Development

make deps          # shards install, bin/ameba
make check         # format check, ameba, specs
make spec          # specs against ext/libquickjs-debug.a (-Dtsjs_debug)
make leakcheck     # RSS soak test (release build); SOAK_SCALE=0.1 for a quick run
make valgrind      # the soak test under valgrind, definite leaks only
make bench         # benchmarks
make sucrase       # rebuild src/radbas-tsjs/sucrase/bundle.js (needs Node)

Specs link the engine built with assertions on: JS_FreeRuntime then asserts that no JavaScript objects are left, so a reference leak fails the run.

Updating QuickJS-ng: tools/update-quickjs.sh v0.x.y, diff quickjs.h against the previous version, re-check the bindings in src/radbas-tsjs/lib_quickjs.cr and the inline helpers in src/radbas-tsjs/lib_quickjs/value.cr, run make check. Bump deliberately.

Updating Sucrase: bump the version in tools/sucrase/package.json, then make sucrase and make check. The bundle banner and Radbas::TSJS::Transformer::SUCRASE_VERSION follow the installed package. Commit the regenerated bundle, the lock file and vendor/sucrase/ (licences and versions of the bundled packages).

Licence

MIT. The vendored engine and the packages in the Sucrase bundle keep their licences: vendor/quickjs/LICENSE (MIT) and vendor/sucrase/ (MIT, and Apache-2.0 for ts-interface-checker; vendor/sucrase/PACKAGES lists them).

Repository

tsjs.cr

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 1
  • about 1 hour ago
  • December 4, 2026
License

MIT License

Links
Synced at

Fri, 04 Dec 2026 22:42:10 GMT

Languages