# JavaScript

> Use bytepeel from Node, Deno, Bun or the browser through its WebAssembly build, from npm or JSR.

The `bytepeel` package on npm (and `@pinta365/bytepeel` on JSR) includes a
WebAssembly build of the core with a small JS wrapper: one `bytepeel.wasm`
with no imports and no JS dependencies. It runs in Node (≥18), Deno, Bun and
browsers.

```sh
npm install bytepeel              # npm (Node, Bun, bundlers)
deno add jsr:@pinta365/bytepeel   # JSR (Deno; also npx jsr add for Node)
```

The JSR package imports from `"@pinta365/bytepeel"` and has the same API.
(The npm package also contains the `bytepeel` command; the JSR package is the
library only.)

```js
import { load, raw, BytepeelError } from "bytepeel";

const bp = await load();

bp.peel("ChRTR1ZzYkc4c0lIZHZjbXhrSVNFPRAq");   // the decoded tree (object)
bp.tree("1a03089601");                          // the text outline
bp.get(pem, "0.0.5.2.0.1").value;               // "ISRG Root X2"
bp.getRaw("1a03089601", "3.1");                 // Uint8Array [0x96, 0x01]
bp.getRaw(gzippedBase64);                       // all of the decoded text's bytes

// Edits return the data in its original outer format (hex stays hex, PEM
// stays PEM, ...), with every other byte preserved. Each edit is verified.
const out = bp.edit("08 96 01 12 03 66 6f 6f", [
  { add: "3", value: 42 },
  { del: "2" },
]);
new TextDecoder().decode(out);                  // "08 96 01 18 2a"
```

- **Options** (all methods): `{ in: "auto"|"hex"|"base64"|"raw", as:
  "protobuf"|"der"|"cbor"|"msgpack"|"text"|"bytes", depth, alts, max_items }`.
- **Input:** a string (UTF-8) or `Uint8Array`/`ArrayBuffer`/typed array.
- **Values** are typed: a string is text (never parsed, so `"42"` is the
  text `42`); an integer `number` or a `bigint` is an integer; other numbers
  are floats; `true`/`false`/`null`; a `Uint8Array` is bytes. Use
  `raw("sint:-2")`, `raw("float:1")` for the CLI value syntax.
- **64-bit integers are JSON strings** in `peel`/`get` output, so they never
  lose precision.
- **Errors** throw `BytepeelError` with the CLI's stable `code` (e.g.
  `PATH_NOT_FOUND`) and `offset`.
- **Loading:** from npm, `load()` reads `bytepeel.wasm` next to `index.js`
  (a file read in Node/Deno/Bun, `fetch` over HTTP). The JSR package embeds
  the module, so `load()` needs no file or network access (no Deno
  permissions). Pass the bytes, a URL, a `Response`, or a compiled
  `WebAssembly.Module` to load it yourself.

## WebAssembly ABI

`bytepeel-wasm` compiles the core (with `deflate` and `zstd`) to
`wasm32-unknown-unknown` with no imports and no generated glue. Its ABI:

| Export | Meaning |
|---|---|
| `bp_alloc(len) -> ptr` | allocate `len` bytes for the caller to fill |
| `bp_free(ptr, len)` | free a `bp_alloc` buffer or a `bp_call` result |
| `bp_call(op, in, in_len, arg, arg_len, opts, opts_len) -> ptr` | run one operation |

`op`: 0 peel (JSON), 1 tree, 2 get (JSON), 3 get raw payload, 4 edit. `arg`
is the path (get; for op 3 an empty path selects the innermost layer's whole
bytes, as `--format raw` without `--get` does) or the edits as NUL-separated `kind, path, value` triples
(`set`/`add`/`del`, values in the CLI syntax). `opts` is `key=value` lines
(`in`, `as`, `depth`, `alts`, `max_items`). The result is `[status u8][len u32 LE][len
bytes]`: status 0 is the output, 1 is `{"error":{...}}` JSON; free it with
`bp_free(ptr, 5 + len)`.

`npm/index.js` wraps this as `load() -> { peel, tree, get, getRaw, edit }`
with typed edit values (strings are text, numbers are numbers) and
`BytepeelError`. Build: `npm/build.sh` (`--profile wasm`: release, size-optimized).

The npm package also has a `bytepeel` command (`npm/bin/bytepeel.js`) that
runs the native CLI, unchanged, from an optional per-platform dependency
(`bytepeel-{linux,darwin}-{x64,arm64}`, `bytepeel-win32-x64`), passing
arguments, stdio and the exit code through. `npm/platforms.mjs` builds those
packages from a GitHub release's archives.
