# Use the TypeScript library

Add @tabnas/dmog to a Node.js project, translate a string or a stream, run a program, read a failure, stop a run, and choose between the asynchronous and synchronous forms.

The `@tabnas/dmog` package is a library as well as the `dmog` command. A Node.js program that imports it can do everything the command does. The examples on this page are ES modules, which the package's tests run, and each prints what its `Output` comment shows. Every function and option is in [the library reference](https://dmog.tabnas.dev/reference/library.html).

## Add the package

You need Node.js 24 or later. Add the package to your project:

```sh
npm install @tabnas/dmog
```

npm installs the formats' packages with it, as its peer dependencies. `import` and `require` load the same library.

## Translate a document held in a string

`Translation.compile` takes the translation's options and compiles it, and `runString` runs it over a string:

```ts
import { Translation } from '@tabnas/dmog'

const translation = Translation.compile({ from: 'yaml', to: 'json' })
const json = await translation.runString('name: Ada\nlanguages: [en, fr]\n')
process.stdout.write(json)

// Output:
// {"name":"Ada","languages":["en","fr"]}
```

The options are the command's. `from` and `to` name formats by the ids `dmog formats` prints, and `path`, `key`, `with`, and `whole` stand for `--path`, `--key`, `--with`, and `--whole`. `limits` sets any of the limits, `max_output_bytes` among them, which is `--max-output-bytes`. A translation compiles once and runs as often as you like. A format that does not exist, or a path that does not parse, throws from `compile`.

## Stream from a file

`translate` compiles a translation and runs it once. It reads a readable stream, or any `AsyncIterable` of bytes, and writes to a writable stream as it reads:

```ts
import { createReadStream } from 'node:fs'

import { translate } from '@tabnas/dmog'

await translate(createReadStream('server.yaml'), process.stdout, { from: 'yaml', to: 'toml' })

// Output:
// "server" = { "host" = "example.com", "port" = 8080, "tls" = true }
// "paths" = [ "/api", "/health" ]
```

The promise resolves once the output stream has taken everything written to it. The stream is left open, so a file stream you opened is yours to end. A slow output stream holds the run back, so the input is read no faster than the output is written.

A document that cannot be streamed, such as an object that repeats a key, fails with a message that ends by naming `--whole`. Set `whole: true` to read it whole, as [Translate a document that cannot be streamed](https://dmog.tabnas.dev/how-to/read-whole.html) does with the command.

## Run a program

`Program.compile` takes an alchemy program as a source, its name and its text, with the options of `dmog run`. `run` runs it over a JSON document:

```ts
import { createReadStream, readFileSync } from 'node:fs'

import { Program } from '@tabnas/dmog'

const source = { name: 'table.alc', text: readFileSync('table.alc', 'utf8') }
const program = Program.compile(source, { render: 'json' })
await program.run(createReadStream('records.json'), process.stdout)

// Output:
// [{"Identifier":123,"Full name":"Alice","Balance":50.25},{"Identifier":456,"Full name":"Bob","Balance":72}]
```

`render` stands for `--render`, and `grammar` for `--grammar`. A program that does not check throws from `compile`, before any input is read. `canon`, `format`, `check`, `explain`, and `explainJson` answer what the commands of those names print, and run on the calling thread. To reshape a document while it is translated, give the program to a translation as its `with` option.

## Read a failure

A failure is a `Fail`. An asynchronous function rejects with it, and a synchronous one throws it. Its `code` is the failure's stable name, and `committedOutput` says whether output had been written before it:

```ts
import { Code, Fail, Translation } from '@tabnas/dmog'

const translation = Translation.compile({ from: 'json', to: 'yaml' })
try {
  await translation.runString('{"a":')
} catch (err) {
  if (!(err instanceof Fail)) throw err
  if (err.code === Code.INPUT_INVALID) console.log('not JSON, at line', err.row)
  console.log(err.committedOutput)
  console.log(JSON.stringify(err))
}

// Output:
// not JSON, at line 1
// false
// {"code":"INPUT_INVALID","message":"unexpected: unexpected character(s):","row":1,"col":6,"output":"none"}
```

Output written before a failure is a prefix of the answer, and ends with a whole record unless one record was longer than the 32 KiB the writer holds back. `runString` and `runStringSync` keep none of it. `JSON.stringify` writes a failure as the object the command writes on standard error, and [Failures](https://dmog.tabnas.dev/reference/failures.html) lists every code.

## Stop a run

An asynchronous run takes an `AbortSignal`, and a synchronous one takes a deadline, in milliseconds since the epoch. A run stopped either way fails with `ABORTED`:

```ts
import { PassThrough } from 'node:stream'

import { Fail, Translation } from '@tabnas/dmog'

const translation = Translation.compile({ from: 'json', to: 'yaml' })

// An input that never ends, such as a client that stops sending.
const input = new PassThrough()
try {
  await translation.run(input, process.stdout, { signal: AbortSignal.timeout(100) })
} catch (err) {
  if (!(err instanceof Fail)) throw err
  console.log(err.code)
}

// A reader of a JSON array that never ends: [0,0,0,...
const encoder = new TextEncoder()
let pending = encoder.encode('[')
const endless = {
  read(buf: Uint8Array): number {
    if (pending.length === 0) pending = encoder.encode('0,'.repeat(1024))
    const n = Math.min(buf.length, pending.length)
    buf.set(pending.subarray(0, n))
    pending = pending.subarray(n)
    return n
  },
}
const discard = { write: (bytes: Uint8Array) => bytes.length }
try {
  translation.runSync(endless, discard, { deadline: Date.now() + 100 })
} catch (err) {
  if (!(err instanceof Fail)) throw err
  console.log(err.code)
}

// Output:
// ABORTED
// ABORTED
```

A signal stops a run even while it waits for input. A deadline is checked as the run reads, as it writes, and as it parses, so a synchronous reader that blocks holds the run until it returns.

## Choose the synchronous forms

`runSync`, `runStringSync`, and `translateSync` run on the calling thread, and return when the run has ended. They take a string, bytes, or a reader with a `read(buf)` method that answers how many bytes it gave, and a writer with a `write(bytes)` method that answers how many it took:

```ts
import { closeSync, openSync, readSync, writeSync } from 'node:fs'

import { Translation, translateSync } from '@tabnas/dmog'

// A document held in a string.
const translation = Translation.compile({ from: 'csv', to: 'json' })
process.stdout.write(translation.runStringSync('title,year\nNotes on Formats,2021\n'))

// A reader and a writer over files, read and written as the run goes.
const input = openSync('books.csv', 'r')
const output = openSync('books.yaml', 'w')
try {
  translateSync(
    { read: (buf) => readSync(input, buf) },
    { write: (bytes) => writeSync(output, bytes) },
    { from: 'csv', to: 'yaml' },
  )
} finally {
  closeSync(input)
  closeSync(output)
}

// Output:
// [{"title":"Notes on Formats","year":"2021"}]
//
// books.yaml:
// - "title": "A Book of Examples"
//   "author": "A. N. Author"
//   "year": "1999"
// - "title": "Notes on Formats"
//   "author": "B. Writer"
//   "year": "2021"
```

Take the synchronous forms where nothing else needs the thread while the run lasts: a command-line tool, a one-off job, or a worker thread of your own. They start no worker, and the `dmog` command uses them. Take the asynchronous forms where the event loop must keep running, as in a server: each run takes place on a worker thread, and the calling thread only moves bytes between the streams and the worker.

## Close the workers

The asynchronous forms start up to four worker threads on first use and keep them for the runs that follow. A worker with no run does not keep the process alive, so a program that has finished exits without any clean-up. Call `closeWorkers()` to end the workers sooner: when a long-running process is done with the library and wants their memory back, or when it shuts down and wants every run stopped. A run still under way fails with `ABORTED`, and a later run starts the workers again:

```ts
import { Fail, Translation, closeWorkers } from '@tabnas/dmog'

const translation = Translation.compile({ from: 'csv', to: 'json' })

// Closing the workers stops the runs still under way: each fails with
// ABORTED.
const running = translation.runString('name\nAda\n').catch((err: unknown) => err)
await closeWorkers()
const stopped = await running
if (stopped instanceof Fail) console.log(stopped.code)

// A later run starts the workers again.
process.stdout.write(await translation.runString('name\nAlan\n'))

// Output:
// ABORTED
// [{"name":"Alan"}]
```

Give a run's promise its handler before closing the workers, as the example does with `catch`. A promise that rejects with no handler stops the process.
