Skip to content

@plinthjs/repl ​

The Plinth REPL. It is split into a testable engine and a thin interactive wrapper:

  • Repl runs snippets in a persistent node:vm context, returning the value of the last expression and carrying top-level declarations across calls (REPL scope semantics).
  • start() boots a node:repl whose evaluator delegates to a shared Repl, so the live REPL and Repl.evaluate() follow the same evaluation path.

Bindings (app, registered helpers, variables you set) are exposed to evaluated code as bare identifiers. The package depends only on Node built-ins, @plinthjs/core and @plinthjs/support.

Install ​

sh
npm install @plinthjs/repl

Usage ​

ts
import { Application } from '@plinthjs/core'
import { start } from '@plinthjs/repl'

const app = new Application({ config: { app: { env: 'local' } } })

// Launch an interactive session with `app` in scope.
start({ app, prompt: 'plinth> ' })
plinth> app.environment()
'local'
plinth> const total = [1, 2, 3].reduce((a, b) => a + b)
plinth> total * 2
12

start() returns the running repl.REPLServer. It throws when called under a test runner (when VITEST is set or NODE_ENV=test), so it never attaches to the process during tests.

The engine ​

ts
import { Repl } from '@plinthjs/repl'

const repl = new Repl({ context: { greet: (who: string) => `hi ${who}` } })

repl.evaluate('1 + 1') // 2
repl.evaluate('greet("ada")') // 'hi ada'

// Declarations persist across calls.
repl.evaluate('const x = 5')
repl.evaluate('function double(n) { return n * 2 }')
repl.evaluate('double(x)') // 10

// Statement-only snippets return undefined.
repl.evaluate('let y = 1') // undefined

// A returned promise can be awaited by the caller.
await (repl.evaluate('Promise.resolve(7)') as Promise<number>) // 7

The vm context is seeded with host standard globals (console, JSON, Promise, fetch, URL, timers, error constructors and so on), so snippets behave as they would in a normal Node REPL.

Bindings ​

ts
repl
  .register('users', usersRepository) // a helper or service
  .setVariable('limit', 10) // a plain variable

repl.evaluate('users.take(limit)')
repl.getVariable('limit') // 10
repl.evaluate('const created = 1')
repl.getVariable('created') // 1, top-level declarations land in the scope
repl.context() // the live bindings record

Pass an existing engine to start({ repl }) to open a REPL over a scope you have already prepared.

Errors ​

Errors are never swallowed. A malformed snippet throws a real SyntaxError, and runtime errors are host Error instances, so instanceof checks work on the caller side:

ts
repl.evaluate('null.foo') // throws TypeError
repl.evaluate('missingName') // throws ReferenceError
repl.evaluate('throw "oops"') // throws Error('oops'), with the original value as `cause`

Released under the MIT License.