# The libraries

The calls and options of the library in each build's package, in TypeScript, Go, and Rust, with their defaults, the failures they return, how they stream, and the threads they run on.

Each build's package is a library as well as the `dmog` command, and the command is built on it. A library does what the command does: it translates a document, lists the formats, and checks, explains, and runs programs. It reads from a reader and writes to a writer that the caller gives it, and it returns a failure where the command would exit. A guide shows each library in use, for [TypeScript](https://dmog.tabnas.dev/how-to/use-the-typescript-library.html), [Go](https://dmog.tabnas.dev/how-to/use-the-go-library.html), and [Rust](https://dmog.tabnas.dev/how-to/use-the-rust-library.html).

## Packages

| Language | Package | Name in code | API documentation |
|---|---|---|---|
| TypeScript | `@tabnas/dmog` on npm | `@tabnas/dmog`, by `import` or `require` | `dist/index.d.ts`, the declarations the package ships |
| Go | `github.com/tabnas/dmog/go` on the Go module proxy | package `dmog` | [pkg.go.dev](https://pkg.go.dev/github.com/tabnas/dmog/go) |
| Rust | `tabnas-dmog` on crates.io | crate `tabnas_dmog` | [docs.rs](https://docs.rs/tabnas-dmog) |

Each library needs Node.js 24, Go 1.24, or Rust 1.85, or later, as its build does. The TypeScript package takes alchemy, transduce, render, and the formats' packages as peer dependencies, which npm installs with it.

## Versions

The libraries are released with the command, at one version. This page describes version 0.4.0. The API is not yet stable: any release before 1.0 may change it. TypeScript exports the version as `VERSION`.

## Translation

A translation is compiled from its options once, and then runs over any number of documents. Compiling refuses a format that does not exist, a path that does not parse, and a program that does not check, before any input is read.

| Command option | TypeScript | Go | Rust | Default |
|---|---|---|---|---|
| `--from FORMAT` | `from` | `From` | `from` | none, required |
| `--to FORMAT` | `to` | `To` | `to` | none, required |
| `--path PATH` | `path` | `Path` | `path` | the whole document |
| `--key KEY` | `key` | `Key` | `key` | `items` |
| `--with PROGRAM` | `with` | `With` | `with` | no program |
| `--whole` | `whole` | `Whole` | `whole` | false |
| `--max-output-bytes N` | `limits` | `Limits` | `limits` | the limits under [Defaults](#defaults) |

The options are a `TranslateOptions` in every build. `with` takes a source: a program's name, which its failures cite, and its text. An empty key is a key. In Go, `Path` is empty for the whole document, and `Key`, `With`, and `Limits` are pointers, `nil` for the default. In Rust, `TranslateOptions::new(from, to)` sets every other field to its default, and `path`, `key`, and `with` are `Option`s.

| Call | TypeScript | Go | Rust |
|---|---|---|---|
| Compile | `Translation.compile(options)` | `NewTranslation(options)` | `Translation::new(options)` |
| Run from a reader to a writer | `run(input, output, { signal })`, `runSync(input, output, { deadline })` | `Run(ctx, r, w)` | `run(input, output)`, `run_with_abort(input, output, &abort)` |
| Run over a string, and answer a string | `runString(input, { signal })`, `runStringSync(input, { deadline })` | `RunString(ctx, input)` | `run_str(input)` |
| Compile and run once | `translate(input, output, options)`, `translateSync(input, output, options)` | `Translate(ctx, r, w, options)` | `translate(input, output, options)`, `translate_str(input, options)` |
| Check the options without compiling | none | none | `options.validate()` |

`translate` takes `signal` among its options, and `translateSync` takes `deadline`.

## Programs

| Command | TypeScript | Go | Rust |
|---|---|---|---|
| `dmog run` | `Program.compile(source, options)`, then `run`, `runString`, `runSync`, or `runStringSync` | `NewProgram(source, options)`, then `Run` or `RunString` | `Program::new(source, options)`, then `run`, `run_with_abort`, or `run_str` |
| `dmog canon` | `canon(source)` | `Canon(source)` | `canon(&source)` |
| `dmog format` | `format(source)` | `Format(source)` | `format(&source)` |
| `dmog check` | `check(source)` | `Check(source)` | `check(&source)` |
| `dmog explain` | `explain(source)` | `Explain(source)` | `explain(&source)` |
| none: the plan report as one JSON object | `explainJson(source)` | `ExplainJSON(source)` | `explain_json(&source)` |

A source, a `Source` in every build, is a program's name, which its failures cite, and its text: `{ name, text }` in TypeScript, `Source{Name, Text}` in Go, and `Source::new(name, text)` in Rust. A program runs as `dmog run` runs it, with the same run forms as a translation. `check` answers nothing for a program that checks, and fails as `dmog check` would for one that does not.

| Command option | TypeScript | Go | Rust | Default |
|---|---|---|---|---|
| `--render csv` | `render: 'csv'` | `Render: RenderCSV` | `render: Some(Render::Csv)` | a table as CSV, and JSON events as JSON |
| `--render json` | `render: 'json'` | `Render: RenderJSON` | `render: Some(Render::Json)` | as for `--render csv` |
| `--grammar FORMAT` | `grammar` | `Grammar` | `grammar` | the input is a JSON document |
| `--max-output-bytes N` | `limits` | `Limits` | `limits` | the limits under [Defaults](#defaults) |

The options are a `ProgramOptions` in every build. Compiling refuses a program that does not check, a grammar that is not a format whose documents are parsed, and a render the program's export cannot take, before any input is read. In Rust, `options.validate()` checks the grammar alone, without compiling the program.

## Formats

| Call | TypeScript | Go | Rust |
|---|---|---|---|
| The formats, as values | `formats()` | `Formats()` | `formats()` |
| The formats as `dmog formats` prints them | `formatsJson()` | `FormatsJSON()` | `formats_json()` |
| The formats a program's grammar may name | `parsedFormats()` | `ParsedFormats()` | `parsed_formats()` |

Each value is a `FormatInfo`, with the fields [Formats](https://dmog.tabnas.dev/reference/formats.html) describes, each in the case its language uses: `id`, `reads`, `writes`, `root`, `schema`, `whole`, `lift`, `embed`, `render`, `transduce`, and `loss`. Where `dmog formats` prints null, TypeScript gives `null`, Rust `None`, and Go an empty string. The JSON text ends without the line feed the command prints after it.

## Input and output

- **TypeScript, the asynchronous forms.** The input is an `Input`: a readable stream, an `AsyncIterable` of bytes, a string, or bytes. The output is an `Output`: a writable stream, which the run leaves open. A run resolves once the stream has taken everything written to it.
- **TypeScript, the synchronous forms.** The input is a `SyncInput`: a string, bytes, or a reader, an object whose `read(buf)` puts bytes in `buf` and answers how many, 0 at the end. The output is a `SyncOutput`: a writer, an object whose `write(bytes)` answers how many bytes it took, with an optional `flush()`.
- **Go.** The input is an `io.Reader`, and the output an `io.Writer`.
- **Rust.** The input implements `Read`, and the output `Write`. Both must be `Send` and `'static`, since they move to the run's thread.

The input is read as UTF-8. A reader that fails, and bytes that are not UTF-8, fail the run with `INPUT_INVALID` and a message that starts `unreadable: `. A writer that fails ends the run with `OUTPUT_FAILED`.

## Defaults

The defaults are the command's.

| Limit | Default | What it bounds |
|---|---|---|
| `max_depth` | 256 | How deeply the document's containers nest. |
| `max_key_bytes` | 64 KiB | The bytes of one object key. |
| `max_scalar_bytes` | 16 MiB | The bytes of one scalar: a string's text, or a number as written. |
| `max_metadata_bytes` | 16 MiB | The bytes a table keeps for the descriptions of its columns. |
| `max_columns` | 10,000 | The columns a table may have. |
| `max_record_bytes` | 64 MiB | The bytes a table keeps for one row before it writes the row. |
| `max_capture_bytes` | 64 MiB | The bytes kept for any one part of the document a program captures. |
| `max_output_bytes` | no limit | The bytes the run may write. |

TypeScript and Rust spell the limits as the table does, and Go as `MaxDepth`, `MaxKeyBytes`, and so on. A run that would pass a limit fails with `RESOURCE_LIMIT_EXCEEDED`, and the failure's `limit` names it as the table does.

- **TypeScript.** `limits` is a `Partial<Limits>`: it takes any of the limits by name, and the rest keep their defaults. `max_output_bytes: null` is no limit. `defaultLimits()` answers the defaults, as a `Limits`.
- **Go.** `Limits` takes a whole `Limits`, and `nil` stands for the defaults. A zero `Limits` is not the defaults, so change a copy of `DefaultLimits()`. `MaxOutputBytes` is a `*uint64`, `nil` for no limit. A translation or a program copies its limits when it is compiled.
- **Rust.** `limits` is a whole `Limits`. `TranslateOptions::new` and `ProgramOptions::default()` start from the defaults, which `default_limits()` and `Limits::default()` answer. `max_output_bytes` is an `Option<u64>`, `None` for no limit.

## Failures

A failure is the object the command writes on standard error, as a value of the library's language.

| Field | TypeScript | Go | Rust |
|---|---|---|---|
| The code | `code` | `Code` | `code` |
| The message | `message` | `Message` | `message` |
| Where in the document | `path` | `Path` | `path` |
| The limit reached | `limit`, with `name` and `value` | `Limit`, with `Name` and `Value` | `limit`, with `name` and `value` |
| Where in a program | `row`, `col` | `Row`, `Column` | `row`, `column` |
| The program's file | `file` | `File` | `file` |
| Whether output was written first | `committedOutput` | `CommittedOutput` | `committed_output` |
| As the command's JSON object | `JSON.stringify(fail)` | `json.Marshal(fail)` | `fail.to_json()` |

- **TypeScript.** A failure is a `Fail`, a subclass of `Error`, which a synchronous call throws and an asynchronous one rejects with. A field that does not apply is `undefined`. The codes are strings, which `Code` names: `Code.INPUT_INVALID`.
- **Go.** A failure is a `*Fail`, the only kind of `error` the package returns, which `errors.As` reads. A field that does not apply is empty, 0, or `nil`. The codes are constants: `CodeInputInvalid`.
- **Rust.** A failure is a `Fail`, in a `Result`'s `Err`, and implements `std::error::Error`. A field that does not apply is `None`. The codes are an enum: `Code::InputInvalid`. `Display` writes the code, the message, and where the failure was found.

[Failures](https://dmog.tabnas.dev/reference/failures.html) lists the codes and what each means. The exit statuses there are the command's: a library returns the failure instead. An option that is wrong fails with `INPUT_INVALID`, before anything is compiled or read. A message may name a command option, such as `--whole`: it means the library's option of the same name.

## Streaming

A translation streams as the command does. It writes as it reads, through the source format's transducer part, unless `whole` asks for the document whole or the format is read whole, as the `whole` field of [Formats](https://dmog.tabnas.dev/reference/formats.html) says. A program reads its input a window at a time and writes its output as it makes it.

The writer holds at most 32 KiB of a record still open, and writes a longer record as it comes. A failure drops what the writer holds, so output written before a failure ends with a whole record unless one record was longer than that. The run writes on the thread that reads, so a slow writer slows the reading.

An asynchronous TypeScript run passes its input to its worker through a buffer of 128 KiB, and lets at most 128 KiB of output wait for the stream to take it.

`runString`, `runStringSync`, `RunString`, and `run_str` hold the whole output in memory, and answer it at the end. After a failure, Go's `RunString` answers the text written before it, and the others answer none.

## Threads

- **TypeScript.** The synchronous forms, compiling, `canon`, `format`, `check`, `explain`, `explainJson`, and the formats take place on the calling thread. The first of them loads every format's package. The asynchronous forms run on a pool of worker threads, started on first use: at most four, and no more than `os.availableParallelism()` answers. Each run takes a worker of its own, and waits while every worker is busy. A worker compiles a translation or a program the first time it runs it, and keeps the 16 it ran most recently. A worker with no run does not keep the process alive. `closeWorkers()` ends the workers: a run under way or waiting fails with `ABORTED`, and a later run starts the pool again.
- **Go.** Every call runs where it is called, and returns when it is done.
- **Rust.** Every call that reads a program, compiles, or runs takes place on a thread it starts, with a stack of 64 MiB, and returns when the thread is done. The language's bounds on a program's nesting need that stack, whatever the caller's thread has. A thread that cannot be started fails the call with `RESOURCE_LIMIT_EXCEEDED`. `Translation`, `Program`, and `Abort` are `Send` and `Sync`, so one compiled translation can serve runs on several threads at once.

## Stopping a run

- **TypeScript.** An asynchronous run takes `signal`, an `AbortSignal`, and a synchronous one takes `deadline`, a time in milliseconds since the epoch. The run looks at either at every read and write, and once in every 64 checks it makes as it parses and evaluates. A signal also stops a run that waits for input, for its output to drain, or for a worker.
- **Go.** A run stops when its context ends. It looks at the context before every read, and as it parses and evaluates.
- **Rust.** A run given to `run_with_abort` stops when `abort()` is called on its `Abort`, or on a clone of it, from any thread. It looks at the `Abort` as it parses and evaluates.

A run stopped so fails with `ABORTED`. A run given a signal, context, or `Abort` that has already stopped, or a deadline that has passed, fails before it reads anything. A read that blocks holds the run until the read returns, except in an asynchronous TypeScript run, which its signal stops while it waits for input.

## Not offered yet

A library cannot yet be taken with only some of the formats. Each loads every format's package, so a program that needs one format carries them all.
