REPL
Introduction
The REPL package lets you evaluate JavaScript against a live application: look up a record, call a service, try an expression, all without writing a throwaway script. It has two layers. The Repl class is the engine: it evaluates strings of code inside an isolated node:vm context that remembers variables between calls. The start() function wraps that engine in an interactive terminal session.
Because the engine is a plain class with no terminal attached, you can also use it directly from your own code and from tests.
pnpm add @plinthjs/replEvaluating code
Create a Repl and call evaluate() with a string. It returns the value of the last expression.
import { Repl } from '@plinthjs/repl'
const repl = new Repl()
repl.evaluate('1 + 2') // => 3
repl.evaluate('[1, 2, 3].map((x) => x * 2)') // => [2, 4, 6]The code runs in its own vm context rather than in your module's scope, so it cannot see your local variables. It can only see what you give it, plus a fixed set of standard globals.
Persistent scope
Variables you declare stay available to later calls on the same instance, which is what makes a session feel interactive.
repl.evaluate('var count = 1')
repl.evaluate('let name = "ann"')
repl.evaluate('const limit = 3')
repl.evaluate('count + 1') // => 2
repl.evaluate('name') // => 'ann'
repl.evaluate('limit * 2') // => 6Variables declared with var, and plain assignments to existing names, are also visible from the outside through getVariable(). Variables declared with let or const persist inside the session but are not exposed through getVariable().
repl.getVariable('count') // => 1
repl.evaluate('count = 10')
repl.getVariable('count') // => 10Promises
There is no top-level await. An expression that produces a promise returns that promise, so await it from your own code.
const result = await (repl.evaluate('Promise.resolve(5)') as Promise<number>)
// => 5Errors
An error thrown by the evaluated code is rethrown from evaluate() as an error of the matching built-in class in your realm, so instanceof checks work.
try {
repl.evaluate('nope.x')
} catch (error) {
error instanceof ReferenceError // => true
;(error as Error).message // => 'nope is not defined'
}A syntax error throws a SyntaxError before anything runs.
Providing variables
There are three ways to put your own values into a session: pass a context when you create it, or add values later with register() or setVariable().
const repl = new Repl({ context: { greeting: 'hi' } })
repl.evaluate('greeting + "!"') // => 'hi!'
repl.register('double', (n: number) => n * 2)
repl.evaluate('double(21)') // => 42
repl.setVariable('user', { id: 7 })
repl.evaluate('user.id') // => 7register() and setVariable() do the same thing and return the instance, so calls chain. Use whichever reads better: register() for functions and services, setVariable() for plain data. context() returns the current bindings object.
The standard globals
The sandbox starts with a fixed list of globals copied from the host: console, JSON, Math, Date, RegExp, Array, Object, Map, Set, WeakMap, WeakSet, Symbol, BigInt, Number, String, Boolean, Promise, Proxy, Reflect, the error classes, parseInt, parseFloat, isNaN, isFinite, encodeURIComponent, decodeURIComponent, structuredClone, the timer functions, queueMicrotask, fetch, URL, URLSearchParams, TextEncoder, TextDecoder and process.
require and import are not available, so evaluated code cannot load modules unless you pass them in. Register what you want to be reachable:
import { Str } from '@plinthjs/support'
repl.register('Str', Str)
repl.evaluate('Str.slug("Hello World")') // => 'hello-world'WARNING
The context is a convenience for exploring, not a security boundary. The process and fetch globals are the real ones, and anything you register is passed in by reference. Do not evaluate code from an untrusted source.
Using it with the application
Pass your Application as the app option and it is bound to the name app inside the session. From there you can read configuration and resolve bindings from the container with app.make().
import { Application } from '@plinthjs/core'
import { Repl } from '@plinthjs/repl'
const application = new Application()
const repl = new Repl({ app: application })
repl.evaluate('app') === application // => true
repl.evaluate('app.config.get("app.name")') // reads a configuration valueRegister the services and models you reach for most often next to it, so they are one word away:
repl.register('User', User).register('db', connection)See Service Container for how app.make() works.
Starting an interactive session
start() opens a terminal REPL backed by a Repl. It returns the Node REPLServer, and it reads from standard input, so call it from a script or a console command that you run in a terminal.
import { start } from '@plinthjs/repl'
start({ app: application, prompt: 'myapp> ', context: { greeting: 'hi' } })The prompt defaults to plinth> . You can pass the same app and context options as Repl, or hand in a repl you have already configured:
const repl = new Repl({ app: application })
repl.register('User', User)
start({ repl })The engine's bindings are copied onto the REPL context, so Node's .help and tab completion see the same names that your code can.
As a console command
The simplest way to expose it is a console command in your application:
import { Command } from '@plinthjs/console'
import { start } from '@plinthjs/repl'
export class ReplCommand extends Command {
static override signature = 'repl'
static override description = 'Open an interactive session with the application loaded'
override handle(): number {
start({ app: application })
return 0
}
}Register it on the kernel like any other command and run it with npx tsx src/console.ts repl. The generated project does not include this command, so you add it yourself.
Testing
start() refuses to run under a test runner. It throws when VITEST is set or NODE_ENV is test, because an interactive prompt would hang the run. Test through Repl.evaluate() instead. It needs no terminal.
import { Repl } from '@plinthjs/repl'
import { expect, it } from 'vitest'
it('evaluates against registered services', () => {
const repl = new Repl().register('users', { count: () => 3 })
expect(repl.evaluate('users.count()')).toBe(3)
})