Source: https://rcompat.repopack.app/packages/array # @rcompat/array This module provides common array operations for computing differences, checking emptiness, and normalizing values to arrays. ## Installation ```bash npm install @rcompat/array ``` ```bash pnpm add @rcompat/array ``` ```bash yarn add @rcompat/array ``` ```bash bun add @rcompat/array ``` ## Usage ### difference Returns elements from the first array that are not present in the second array (set difference). ```js import array from "@rcompat/array"; array.difference([1, 2, 3, 4], [2, 4]); // [1, 3] array.difference(["a", "b", "c"], ["b"]); // ["a", "c"] array.difference([1, 2], [1, 2]); // [] ``` ### empty Checks if an array is empty. ```js import array from "@rcompat/array"; array.empty([]); // true array.empty(["foo"]); // false array.empty([[]]); // false (contains one element, an empty array) ``` ### to Normalizes a value to an array. If the value is already an array, it is returned as-is. Otherwise, the value is wrapped in an array. ```js import array from "@rcompat/array"; array.to("hello"); // ["hello"] array.to(["hello"]); // ["hello"] array.to(42); // [42] array.to([1, 2, 3]); // [1, 2, 3] ``` ## Examples ### Processing user input ```js import array from "@rcompat/array"; function processIds(ids) { const idArray = array.to(ids); if (array.empty(idArray)) { return "No IDs provided"; } return `Processing ${idArray.length} ID(s)`; } processIds("user-1"); // "Processing 1 ID(s)" processIds(["user-1", "user-2"]); // "Processing 2 ID(s)" processIds([]); // "No IDs provided" ``` ### Finding new items ```js import array from "@rcompat/array"; const previousTags = ["javascript", "typescript", "node"]; const currentTags = ["javascript", "typescript", "deno", "bun"]; const newTags = array.difference(currentTags, previousTags); // ["deno", "bun"] const removedTags = array.difference(previousTags, currentTags); // ["node"] ``` ## Cross-Runtime Compatibility | Runtime | Supported | |---------|-----------| | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/assert # @rcompat/assert This module provides runtime type checking and validation with helpful error messages and TypeScript type narrowing. ## Installation ```bash npm install @rcompat/assert ``` ```bash pnpm add @rcompat/assert ``` ```bash yarn add @rcompat/assert ``` ```bash bun add @rcompat/assert ``` ## Usage ### Basic assertions Validates a value against a type and throws with a helpful message if validation fails. ```js import assert from "@rcompat/assert"; // primitives assert.bigint(x); assert.boolean(x); assert.function(x); assert.number(x); assert.string(x); assert.symbol(x); assert.undefined(x); // conditions assert.array(x); assert.date(x); assert.dict(x); // plain object (not array, Date, class instance, etc.) assert.error(x); assert.false(x); assert.finite(x); assert.int(x); assert.map(x); assert.nan(x); assert.newable(x); assert.null(x); assert.nullish(x); assert.object(x); // any non-null object assert.promise(x); assert.regexp(x); assert.safeint(x); assert.set(x); assert.true(x); assert.uint(x); // unsigned (non-negative) integer assert.url(x); // other assert.defined(x); assert.instance(x, MyClass); assert.uuid(x); // valid UUIDv4 string (lowercase, crypto.randomUUID format) ``` ### Custom error messages ```js import assert from "@rcompat/assert"; assert.string(input, new TypeError("Expected a string for username")); assert.number(input, new TypeError("Invalid count")); ``` ### Error codes Error-code values are available on the default aggregate. The corresponding `Code` type can be imported separately because type imports are removed at runtime. ```ts import assert from "@rcompat/assert"; import type { Code } from "@rcompat/assert"; const code: Code = assert.Code.invalid_string; ``` ### Instance checks ```js import assert from "@rcompat/assert"; class Animal {} class Dog extends Animal {} const dog = new Dog(); assert.instance(dog, Animal); // passes assert.instance(dog, Dog); // passes assert.instance(dog, Map); // throws ``` ### maybe Optional/nullable assertions. Returns without throwing for `null` or `undefined`, but validates non-nullish values. ```js import assert from "@rcompat/assert"; // returns without error for nullish assert.maybe.string(undefined); // ok assert.maybe.number(null); // ok // validates non-nullish values assert.maybe.string("hello"); // ok assert.maybe.string(42); // throws - 42 is not a string ``` ### every Ensures ALL values in an array satisfy a type condition. ```js import assert from "@rcompat/assert"; assert.every.string(["a", "b", "c"]); // ok - all strings assert.every.number([1, 2, 3]); // ok - all numbers assert.every.number([1, "2", 3]); // throws - "2" is not a number assert.every.instance([dog1, dog2], Animal); // ok - all Animal instances ``` ## Examples ### Validating function inputs ```js import assert from "@rcompat/assert"; function createUser(data) { assert.dict(data); assert.string(data.name); assert.uint(data.age); assert.maybe.string(data.nickname); return { ...data }; } ``` ### Parsing configuration ```js import assert from "@rcompat/assert"; function parseConfig(config) { assert.dict(config); assert.uint(config.port); assert.string(config.host); assert.maybe.boolean(config.debug); return { port: config.port, host: config.host, debug: config.debug ?? false, }; } ``` ### Validating arrays ```js import assert from "@rcompat/assert"; function processIds(ids) { assert.array(ids); assert.every.uuid(ids); return ids.map(id => lookup(id)); } ``` ## Cross-Runtime Compatibility | Runtime | Supported | |---------|-----------| | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/cli # @rcompat/cli This module provides foreground and background terminal colors, direct output, and common interactive prompts through one default utility aggregate. CLI utilities throw when accessed in a browser. ## Installation ```bash npm install @rcompat/cli ``` ```bash pnpm add @rcompat/cli ``` ```bash yarn add @rcompat/cli ``` ```bash bun add @rcompat/cli ``` ## Usage ### Colors Use [`cli.fg`](/api/cli#cli-fg) for foreground colors and text styles, and [`cli.bg`](/api/cli#cli-bg) for background colors: ```js import cli from "@rcompat/cli"; console.log(cli.fg.red("Error: something went wrong")); console.log(cli.fg.green("Success!")); console.log(cli.fg.bold(cli.fg.blue("Important information"))); console.log(cli.bg.yellow(cli.fg.black("Warning"))); ``` Foreground styles include `black`, `blue`, `bold`, `cyan`, `dim`, `gray`, `green`, `inverse`, `magenta`, `red`, `white`, and `yellow`. Background colors include the same colors except for the text-only styles `bold`, `dim`, and `inverse`. ### Output [`cli.print`](/api/cli#cli-print) writes messages to standard output, separated by spaces, without adding a newline: ```js import cli from "@rcompat/cli"; cli.print("Loading", "..."); cli.print("\n"); ``` ### Text and confirmation prompts Prompt methods live under [`cli.prompt`](/api/cli#cli-prompt). Text and confirmation prompts return a cancel symbol on end-of-input or interruption; use `isCancel` to distinguish it from a submitted value. ```js import cli from "@rcompat/cli"; const name = await cli.prompt.text({ message: "What is your name?", initial: "Anonymous", validate: value => value.length < 2 ? "Name must be at least 2 characters" : undefined, }); if (cli.prompt.isCancel(name)) { cli.prompt.cancel("Setup cancelled"); } else { const proceed = await cli.prompt.confirm({ message: `Continue as ${name}?`, initial: true, }); if (proceed === true) cli.prompt.outro("Setup complete"); } ``` ### Selection prompts ```js import cli from "@rcompat/cli"; const runtime = await cli.prompt.select({ message: "Select a runtime", options: [ { label: "Node", value: "node" }, { label: "Bun", value: "bun" }, { label: "Deno", value: "deno" }, ], initial: 0, }); const features = await cli.prompt.multiselect({ message: "Select features", options: [ { label: "TypeScript", value: "typescript" }, { label: "Linting", value: "lint" }, { label: "Testing", value: "test" }, ], initial: [0, 1], }); console.log(runtime, features); ``` ### Spinner ```js import cli from "@rcompat/cli"; const spinner = cli.prompt.spinner(); spinner.start("Installing dependencies"); await new Promise(resolve => setTimeout(resolve, 1000)); spinner.stop("Dependencies installed"); ``` The spinner animates on an interactive terminal and falls back to plain output when standard output is not a TTY. ## Runtime compatibility | Runtime | Supported | | ------- | --------- | | Node.js | Yes | | Bun | Yes | | Deno | Yes | | Browser | No | ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/dict # @rcompat/dict This module provides typed utilities for transforming, filtering, inflating, and querying JavaScript dictionaries. ## Installation ```bash npm install @rcompat/dict ``` ```bash pnpm add @rcompat/dict ``` ```bash yarn add @rcompat/dict ``` ```bash bun add @rcompat/dict ``` ## Usage ```js import dict from "@rcompat/dict"; const values = { a: 1, b: 2, c: 3 }; dict.keys(values); // ["a", "b", "c"] dict.values(values); // [1, 2, 3] dict.entries(values); // [["a", 1], ["b", 2], ["c", 3]] dict.has(values, "b"); // true dict.empty({}); // true ``` ### Filtering and mapping Callbacks receive the key followed by the value. ```js const values = { a: 1, b: 2, c: 3 }; dict.filter(values, (_, value) => value > 1); // { b: 2, c: 3 } dict.exclude(values, ["b"]); // { a: 1, c: 3 } dict.map(values, (_, value) => value * 10); // { a: 10, b: 20, c: 30 } dict.mapKey(values, key => key.toUpperCase()); // { A: 1, B: 2, C: 3 } dict.flatMap(values, (key, value) => value % 2 === 0 ? [key, value * 10] : [] ); // { b: 20 } ``` ### Nested dictionaries ```js const config = { server: { host: "localhost", port: 3000, }, }; dict.get(config, "server.port"); // 3000 dict.inflate("server.tls", { enabled: true }); // { server: { tls: { enabled: true } } } dict.override(config, { server: { port: 8080 } }); // { server: { host: "localhost", port: 8080 } } ``` [`dict.inflate`](/api/dict#dict-inflate) accepts dot-separated paths only. When migrating a custom separator, normalize the path first: ```js const path = "server/tls".replaceAll("/", "."); dict.inflate(path, { enabled: true }); // { server: { tls: { enabled: true } } } ``` `override` recursively merges dictionary values. Other values from the second dictionary replace values from the first. ### Frozen dictionaries [`dict.new`](/api/dict#dict-new) creates a frozen dictionary with a null prototype. ```js const config = dict.new({ mode: "production" }); Object.getPrototypeOf(config); // null Object.isFrozen(config); // true ``` ### Query strings ```js dict.toQueryString({ page: "1", sort: "name" }); // "page=1&sort=name" ``` [`toQueryString`](/api/dict#dict-toquerystring) joins string keys and values without URL-encoding them. ## Runtime compatibility | Runtime | Supported | | ------- | --------- | | Node.js | Yes | | Bun | Yes | | Deno | Yes | | Browser | Yes | ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/env # @rcompat/env This module provides required and optional access to environment variables. ## Installation ```bash npm install @rcompat/env ``` ```bash pnpm add @rcompat/env ``` ```bash yarn add @rcompat/env ``` ```bash bun add @rcompat/env ``` ## Usage ### Required variables Use [`env.get`](/api/env#env-get) when a variable must exist. Throws immediately if missing, so misconfigured environments fail early and explicitly: ```js import env from "@rcompat/env"; const url = env.get("DATABASE_URL"); // string, throws if missing const secret = env.get("API_SECRET"); // string, throws if missing ``` ### Optional variables Use [`env.try`](/api/env#env-try) when a variable may or may not be present: ```js import env from "@rcompat/env"; const debug = env.try("DEBUG"); // string | undefined const nodeEnv = env.try("NODE_ENV"); // string | undefined ``` ## Browsers Browser builds expose an empty environment so server environment variables are not included in client code. Consequently, `env.get(key)` throws and `env.try(key)` returns `undefined` in browsers. ## File loading The package looks for the first matching file in your project root: 1. `.env.{NODE_ENV}.local` 2. `.env.{NODE_ENV}` 3. `.env.local` 4. `.env` If `NODE_ENV` is not set, `JS_ENV` is used as a fallback. Local files (`.local` suffix) are typically gitignored and used for machine-specific secrets. ## Merging The runtime's native environment is always the base. Node and Bun read from `process.env`, while Deno reads from `Deno.env`. The first `.env` file found is layered on top, so file variables win over system variables. ## Substitution Variables can reference other variables: ``` FOO=world BAR=hello$FOO # helloworld BAZ=hello${FOO} # helloworld ESCAPED=hello\$FOO # hello$FOO WITH_DEFAULT=${FOO:-fallback} # uses fallback if FOO is undefined ``` Substitution resolves against the merged environment, so system variables are available too: ``` CONFIG=$HOME/.config/myapp DB_USERNAME=${DB_USERNAME:-myapp} # uses system DB_USERNAME or falls back to myapp ``` ## Deno permissions Deno requires `--allow-env` to read the system environment and `--allow-read` to discover and load dotenv files. Permission failures are reported by Deno during module initialization rather than being treated as missing variables. Single-quoted values skip substitution: ``` FOO='hello$BAR' # hello$BAR (literal) ``` ## Project structure ``` my-project/ ├── .env # Shared defaults ├── .env.development # Development settings ├── .env.development.local # Local dev secrets (gitignored) ├── .env.production # Production settings └── .gitignore ``` ```gitignore .env.local .env.*.local ``` ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/error # @rcompat/error This module creates structured errors from tagged templates while preserving their strings and interpolated values. Stable string codes support matching across package and realm boundaries. ## Installation ```bash npm install @rcompat/error ``` ```bash pnpm add @rcompat/error ``` ```bash yarn add @rcompat/error ``` ```bash bun add @rcompat/error ``` ## Usage ### Template errors Use [`error.template`](/api/error#error-template) as a tagged template to retain both the rendered message and its original values: ```js import error from "@rcompat/error"; const filename = "config.json"; const failure = error.template`Could not read ${filename}`; failure.message; // "Could not read config.json" failure.strings; // ["Could not read ", ""] failure.params; // ["config.json"] ``` ### Coded errors [`error.coded`](/api/error#error-coded) wraps an object of error factories. Each returned error carries the factory key as its stable `code`: ```js import error from "@rcompat/error"; const errors = error.coded({ missing: name => error.template`Missing ${name}`, invalid: name => error.template`Invalid ${name}`, }); const failure = errors.missing("token"); failure.code; // "missing" error.CodeError.is(failure); // true error.CodeError.matches(failure, "missing"); // true ``` ### Error names `error.names` creates a typed key-to-name object for sharing error codes without repeating string literals: ```ts import error from "@rcompat/error"; const names = error.names({ missing: null, invalid: null, }); names.missing; // "missing" names.invalid; // "invalid" ``` --- Source: https://rcompat.repopack.app/packages/fn # @rcompat/fn This module provides typed predicates, identity transforms, and concurrent asynchronous collection helpers. ## Installation ```bash npm install @rcompat/fn ``` ```bash pnpm add @rcompat/fn ``` ```bash yarn add @rcompat/fn ``` ```bash bun add @rcompat/fn ``` ## Usage ### defined A predicate function that checks if a value is not `undefined`. ```js import fn from "@rcompat/fn"; fn.defined("hello"); // true fn.defined(0); // true fn.defined(null); // true fn.defined(false); // true fn.defined(undefined); // false ``` Useful for filtering out undefined values: ```js import fn from "@rcompat/fn"; const values = [1, undefined, 2, undefined, 3]; const filtered = values.filter(fn.defined); // [1, 2, 3] ``` ### identity The identity function — returns its input unchanged. ```js import fn from "@rcompat/fn"; fn.identity(42); // 42 fn.identity("hello"); // "hello" fn.identity({ a: 1 }); // { a: 1 } ``` Useful as a default callback or no-op transformer: ```js import fn from "@rcompat/fn"; function transform(data, transformer = fn.identity) { return transformer(data); } transform({ name: "Bob" }); // { name: "Bob" } transform({ name: "Bob" }, x => ({ ...x, id: 1 })); // { name: "Bob", id: 1 } ``` ### async.map Async map over an array. With no options, it retains the original `Promise.all` behavior: every callback starts immediately and results preserve input order. ```js import fn from "@rcompat/fn"; const urls = ["/api/users/1", "/api/users/2", "/api/users/3"]; // fetch all users in parallel const users = await fn.async.map(urls, async (url) => { const response = await fetch(url); return response.json(); }); // [{ id: 1, ... }, { id: 2, ... }, { id: 3, ... }] ``` ```js import fn from "@rcompat/fn"; // with index parameter const results = await fn.async.map([10, 20, 30], async (value, index) => { return { index, doubled: value * 2 }; }); // [{ index: 0, doubled: 20 }, { index: 1, doubled: 40 }, { index: 2, doubled: 60 }] ``` Use `concurrency` to cap callbacks running at once, and pass a signal to stop queued callbacks: ```js const controller = new AbortController(); const results = await fn.async.map(urls, async (url, index, items) => { const response = await fetch(url, { signal: controller.signal }); return { index, total: items.length, data: await response.json() }; }, { concurrency: 4, signal: controller.signal, }); ``` `concurrency` must be a finite positive integer. Empty arrays resolve to `[]` unless their signal is already aborted. Rejection or abort prevents additional queued callbacks from starting. Abort rejects the map promptly, but callbacks already running are not forcibly stopped; pass the same signal to cooperative operations such as `fetch` when they also need cancellation. ## Examples ### Filter undefined from array ```js import fn from "@rcompat/fn"; const users = [ { name: "John" }, undefined, { name: "Bob" }, undefined, ]; users.filter(fn.defined); // [{ name: "John" }, { name: "Bob" }] ``` ### Optional transformation pipeline ```js import fn from "@rcompat/fn"; function processData(data, options = {}) { const { preProcess = fn.identity, postProcess = fn.identity, } = options; const prepared = preProcess(data); const result = doWork(prepared); return postProcess(result); } // use with default (no-op) transformations processData(myData); // use with custom transformations processData(myData, { preProcess: data => data.map(x => x * 2), postProcess: result => result.filter(x => x > 10), }); ``` ### Conditional mapping ```js import fn from "@rcompat/fn"; function conditionalMap(array, condition, mapper) { return array.map(condition ? mapper : fn.identity); } const numbers = [1, 2, 3]; conditionalMap(numbers, true, x => x * 2); // [2, 4, 6] conditionalMap(numbers, false, x => x * 2); // [1, 2, 3] ``` ### Parallel API requests ```js import fn from "@rcompat/fn"; async function fetchProducts(ids) { return fn.async.map(ids, async id => { const response = await fetch(`/api/products/${id}`); return response.json(); }); } const products = await fetchProducts([1, 2, 3, 4, 5]); ``` ## Cross-Runtime Compatibility | Runtime | Supported | |---------|-----------| | Browser | ✓ | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/fs # @rcompat/fs This module provides filesystem access through a Python pathlib-inspired API, including file operations, directory traversal, and project discovery. File-system routing is owned by consuming frameworks rather than this package. Primate applications use the routing implementation provided by `@primate/core`. ## Installation ```bash npm install @rcompat/fs ``` ```bash pnpm add @rcompat/fs ``` ```bash yarn add @rcompat/fs ``` ```bash bun add @rcompat/fs ``` ## Usage ### FileRef A pathlib-like class for file and directory operations. #### Creating a FileRef ```js import fs from "@rcompat/fs"; const file = fs.ref("./src/config.json"); // FileRef("./src/config.json") const absolute = fs.ref("/etc/hosts"); // FileRef("/etc/hosts") const from_url = fs.ref(new URL("file:///tmp/config.json")); // resolve relative to cwd const resolved = fs.resolve("./src"); ``` The exported `Path` type is the canonical complete-path input for `FileRef` and filesystem helpers: `string | URL | FileRef`. Native path strings and `file://` strings are accepted. Strings beginning with a non-file `://`, such as `https://example.com/file.txt`, are rejected before filesystem access; drive-letter paths (including doubled forward slashes such as `C://Temp/file.txt`) and ordinary filenames containing a colon remain native paths. URL objects must use the `file:` protocol. Filesystem helpers never fetch network resources. `join()` takes only **relative** strings or relative `FileRef`s: absolute, drive-qualified, and URL operands are rejected. Complete file URLs are accepted by `fs.ref()` and other complete-path inputs, not by `join()`. Empty join operands do nothing. #### Path manipulation ```js import fs from "@rcompat/fs"; const file = fs.ref("./src/components/Button.tsx"); file.path; // "./src/components/Button.tsx" file.name; // "Button.tsx" file.base; // "Button" file.extension; // ".tsx" file.directory; // FileRef("./src/components") file.webpath(); // "./src/components/Button.tsx" (forward slashes) file.toURL(); // URL("file:///current/directory/src/components/Button.tsx") // join paths file.directory.join("Input.tsx"); // FileRef("./src/components/Input.tsx") const route = fs.ref("./src/../assets"); route.path; // "./src/../assets" (spelling retained) route.join("./icons").path; // "./src/../assets/./icons" route.normalize().path; // "assets" (explicit lexical normalization) route.isAbsolute(); // false route.relativeTo("./src"); // "../assets" (portable / separators) fs.relativeTo(route, "./src"); // same result ``` `toURL()` synchronously converts the reference with the running host's native file-URL semantics. Relative paths are resolved from the current working directory, and reserved characters are escaped without changing their literal filesystem meaning. Use `.href` when a URL string is required. Browser bundles remain safe to import, but calling `toURL()` in a browser throws `fs is not available in the browser`. `relativeTo(base)` compares lexical locations, not filesystem identities. It returns `"."` for the same location and throws on incompatible roots or when an implicit cwd or Windows drive context would be needed. It is **not** a containment or symlink-security check. Windows drive letters compare without case while ordinary components retain their spelling and case. `fs.resolve()` still explicitly resolves against cwd; it does not resolve symlinks. #### Migrating from @rcompat/path The separate `@rcompat/path` workspace has been removed. Use the existing filesystem-reference operations without opening or accessing a file: ```js import fs from "@rcompat/fs"; fs.ref("a//b/../c/").normalize().webpath(); // "a/c/" fs.ref("/app/routes").isAbsolute(); // true fs.ref("app/assets/logo.svg").relativeTo("app/routes"); // "../assets/logo.svg" ``` Replace `path.posix.normalize(value)` with `fs.ref(value).normalize().path`, `path.posix.isAbsolute(value)` with `fs.ref(value).isAbsolute()`, and `path.relative(base, target)` with `fs.ref(target).relativeTo(base)`. This is a migration, not an identical compatibility layer. On servers, these operations use the running host's native path syntax, not a selectable POSIX or foreign Windows dialect. Browser references use slash syntax and preserve literal backslashes. `relativeTo` returns `"."` rather than `""` for equal paths and throws for incompatible roots or relationships requiring implicit context, rather than returning the normalized target. Its result always uses `/`. Previously published `@rcompat/path` artifacts are unaffected. There is no forwarding package or new filesystem API associated with this removal. #### Reading files ```js import fs from "@rcompat/fs"; const file = fs.ref("./config.json"); // read as text const text = await file.text(); // read and parse JSON const config = await file.json(); // read as binary const bytes = await file.bytes(); // Uint8Array const buffer = await file.arrayBuffer(); // ArrayBuffer // read as stream const stream = file.stream(); // get file size const size = await file.size(); ``` #### Writing files ```js import fs from "@rcompat/fs"; const file = fs.ref("./output.txt"); // write text (auto-adds trailing newline) await file.write("Hello, world!"); // write JSON (pretty-printed) await file.writeJSON({ name: "example", version: "1.0.0" }); // write binary await file.write(new Uint8Array([0x48, 0x69])); ``` #### Setting file permissions ```ts const script = fs.ref("./entrypoint.sh"); await script.write("#!/bin/sh\nexit 0"); await script.chmod(0o755); await script.chmod(0o644); ``` `await file.chmod(mode)` sets the permission bits of an existing regular file on POSIX with Node, Deno, or Bun. It accepts integers from `0o000` through `0o777`. Directories, symbolic links (including dangling links), and missing files are rejected. Filesystem errors propagate to the caller. Calls on Windows and in browsers reject. When the file can be opened for reading or writing, the operation opens it without following a final symlink and changes the mode through that handle. If access permissions prevent opening the file, the operation checks the path again and then changes the mode by path. A symlink substituted between that check and the change can be followed. Use this method only where you control the directory entries in the path. Parent symlinks are resolved normally. #### File info ```js import fs from "@rcompat/fs"; const file = fs.ref("./src"); await file.exists(); // true/false await file.empty(); // true for zero-byte files and directories without entries await file.modified(); // modification time (ms) await file.type(); // "file" | "directory" | "link" | null ``` `empty()` follows symbolic links. Missing paths and broken links return `false`. It is also available as `fs.empty(path)`. #### Directory operations ```js import fs from "@rcompat/fs"; const src = fs.ref("./src"); // list directory contents const files = await src.files(); // list with filter (shallow, non-recursive) const ts_files = await src.files({ filter: info => info.extension === ".ts" }); // recursive, with regex matcher const all_ts_files = await src.files({ recursive: true, filter: /\.ts$/ }); const dir = fs.ref("./dist/assets"); // create directory (recursive by default) await dir.createDirectory(); await fs.createDirectory("./dist/assets"); // remove directory await dir.remove(); // copy directory await dir.copy(fs.ref("./backup")); ``` #### Creating files and symbolic links ```js import fs from "@rcompat/fs"; // Create a new, empty file exclusively (unlike write, no parent creation). const empty = fs.ref("./existing/empty.txt"); await empty.createFile(); await fs.createFile("./existing/another.txt"); // The receiver/first argument is the new link's location, NOT its target. const current = fs.ref("./existing/current"); await current.createLink("../releases/v2"); await fs.createLink("./existing/next", "../releases/v3", { type: "symbolic", targetType: "directory", }); ``` `createDirectory` retains the old recursive-by-default directory behavior; `FileRef.directory` is still the parent reference, not a creation method. `createFile` fails rather than truncating or following an existing file, directory or symlink, and does not create missing parents. Use `write(content)` for content and its existing automatic parent-directory creation. `createLink` creates a symbolic link only: omitting `type` or specifying `{ type: "symbolic" }` has the same result. The target can be a path string or FileRef, relative or absolute. Its spelling (including `./` and `../`) is stored unchanged; relative targets are interpreted from **the link's directory** when followed. Targets can be missing (dangling links), but link parent directories must exist. Existing link locations, including dangling symlinks, fail rather than being replaced. URL objects and URL strings are not link targets, although file URLs are valid complete inputs for the link's location. `targetType: "file" | "directory"` supplies a Windows native target-kind hint; it has no filesystem effect on POSIX. Windows may require a hint for directory or dangling targets, and symlink creation can require platform privileges. Native Windows behavior has not been run here. Browsers can import and create references, but all three filesystem-creation methods throw when called. #### Other methods ```js import fs from "@rcompat/fs"; const file = fs.ref("./src/utils.ts"); // generate content hash const hash = await file.hash(); // SHA-256 by default const sha512 = await file.hash("SHA-512"); // dynamic import const module = await file.import(); const func = await file.import("default"); // find project root (walks up looking for package.json) const root = await file.discover("package.json"); ``` ### Lazy glob scanning `fs.glob()` lazily yields matching files as absolute `FileRef` values beneath a resolved working directory: ```js import fs from "@rcompat/fs"; const controller = new AbortController(); for await (const file of fs.glob("src/**/*.ts", { cwd: ".", signal: controller.signal, })) { console.log(file.path); } ``` The portable pattern syntax supports `*`, `?`, `**` as a complete path segment, and bracket classes such as `[a-z]` and `[!0-9]`. Patterns are relative to `cwd` and always use `/` separators. Absolute patterns, `.` and `..` segments, brace expansion, extglobs, and backslash separators are rejected. Wildcards do not match path segments beginning with `.` unless that segment is explicitly written with a leading dot. Symbolic links are neither followed nor returned, preventing loops and traversal outside the root. Missing or non-directory roots yield nothing; inaccessible roots and other I/O failures reject iteration. Results retain native directory iteration order, which is not guaranteed to be sorted. Iteration stops scanning after consumer exit and an abort signal is checked throughout traversal. Browser imports remain safe, but calling `fs.glob()` there throws `fs is not available in the browser`. ### Project utilities ```js import fs from "@rcompat/fs"; // find project root directory const project_root = await fs.cwd().discover("package.json"); // FileRef("/path/to/project") // get path to package.json const package_json = project_root.join("package.json"); // FileRef("/path/to/project/package.json") ``` ### Verified streamed snapshots [`fs.spool()`](/api/fs#fs-spool) copies a byte stream once to a private disposable file while incrementally computing SHA-256. It applies backpressure and does not buffer the complete input. When `expectedDigest` is supplied, it returns only after the saved bytes match that trusted digest; a mismatch, abort, or read/write failure removes the partial file and rejects without exposing a snapshot. ```js import fs from "@rcompat/fs"; const snapshot = await fs.spool(upstream.body, { expectedDigest: trusted_digest, signal: request.signal, }); return new Response(snapshot.stream(), { headers: { "content-length": String(snapshot.size) }, }); ``` The snapshot stream is one-shot and removes its backing file after EOF or cancellation. Call `await snapshot.dispose()` if the stream is not handed to a consumer, or to terminate an active read. Do not dispose immediately after constructing a streaming response; its host must finish or cancel the response body. Without `expectedDigest`, `snapshot.digest` is computed but not externally verified. Browser bundles are safe to import, but this disk-backed operation is unsupported in browsers and throws when called. ### Streamable values The root API recognizes blobs, readable streams, and objects implementing the shared [`fs.streamable`](/api/fs#fs-streamable) protocol. The symbol uses the global registry key `std:symbol/stream`, so separately loaded package copies share the same identity. ```js import fs from "@rcompat/fs"; // check if a value is streamable if (fs.isStream(value)) { const stream = fs.stream(value); } // check if named (has a name property) if (fs.isNamedStream(value)) { console.log(value.name); } // provide a stream through the shared protocol const source = { [fs.streamable]() { return new ReadableStream(); }, }; ``` Migrate existing implementations from `[symbol.stream]()` to `[fs.streamable]()`. Both properties address the same global symbol during the migration, so old and new consumers remain interoperable. ## Examples ### Build script ```js import fs from "@rcompat/fs"; const src = fs.ref("./src"); const dist = fs.ref("./dist"); // clean dist await dist.remove(); // copy source files await src.copy(dist, info => info.extension !== ".test.ts"); // process each file for (const file of await dist.list()) { const content = await file.text(); const transformed = content.replaceAll("__DEV__", "false"); await file.write(transformed); } ``` ### Config loader ```js import fs from "@rcompat/fs"; async function loadConfig() { const root = await fs.cwd().discover("package.json"); const config_path = root.join("config.json"); if (await config_path.exists()) return config_path.json(); return { /* defaults */ }; } ``` ### Asset fingerprinting ```js import fs from "@rcompat/fs"; async function fingerprint(file) { const hash = await file.hash(); const name = `${file.base}.${hash}${file.extension}`; return file.directory.join(name); } const original = fs.ref("./dist/bundle.js"); const fingerprinted = await fingerprint(original); await original.copy(fingerprinted); ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | Lexical references only; filesystem operations unsupported | Browser bundles can safely import the package. `fs.ref()`, `fs.join()`, `fs.normalize()`, `fs.relativeTo()`, `fs.isAbsolute()`, and reference methods that manipulate path text work with slash-based paths without guessing the host OS. Backslashes are literal characters. `fs.isRef()` recognizes browser references; stream predicates return `false`. Disk and cwd-dependent operations throw a clear error when called. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/html # @rcompat/html This module provides HTML text and quoted-attribute escaping for safely including untrusted strings in markup. ## Installation ```bash npm install @rcompat/html ``` ```bash pnpm add @rcompat/html ``` ```bash yarn add @rcompat/html ``` ```bash bun add @rcompat/html ``` ## Usage ### escape Escapes special characters for HTML text and quoted attribute values. This is one part of preventing Cross-Site Scripting (XSS), based on [OWASP recommendations](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#output-encoding-for-html-contexts). ```js import HTML from "@rcompat/html"; HTML.escape(""); // "<script>alert('xss')</script>" HTML.escape('Hello "world"'); // "Hello "world"" HTML.escape("Tom & Jerry"); // "Tom & Jerry" ``` ### Character escaping | Character | Escaped | |-----------|------------| | `&` | `&` | | `<` | `<` | | `>` | `>` | | `"` | `"` | | `'` | `'` | ## Examples ### Safe HTML templates ```js import HTML from "@rcompat/html"; function renderUser(user) { return `

${HTML.escape(user.name)}

${HTML.escape(user.bio)}

`; } renderUser({ name: "", bio: "I'm a user" }); //
//

<script>bad</script>

//

I'm a user

//
``` ### Escaping quoted attribute values ```js import HTML from "@rcompat/html"; function createLabel(text) { const escaped = HTML.escape(text); return `${escaped}`; } createLabel('Search "results"'); // Search "results" ``` ### Form input display ```js import HTML from "@rcompat/html"; function displayComment(comment) { return `
${HTML.escape(comment.text)}
`; } // Malicious input is safely escaped displayComment({ text: "" }); //
<img src=x onerror=alert(1)>
``` ## Cross-Runtime Compatibility | Runtime | Supported | |---------|-----------| | Browser | ✓ | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/http # @rcompat/http This module provides HTTP servers built around WHATWG `Request` and `Response`, with WebSocket, TLS, MIME, status, and timeout support. ## Installation ```bash npm install @rcompat/http ``` ```bash pnpm add @rcompat/http ``` ```bash yarn add @rcompat/http ``` ```bash bun add @rcompat/http ``` ## Usage ### Basic server ```js import http from "@rcompat/http"; const server = await http.serve(request => { return new Response("Hello, world!"); }, { host: "localhost", port: 3000 }); // stop the server server.stop(); ``` ### Routing ```js import http from "@rcompat/http"; await http.serve(request => { const { pathname } = new URL(request.url); if (pathname === "/") { return new Response("Home"); } if (pathname === "/api/users") { return Response.json([{ id: 1, name: "John" }]); } return new Response("Not Found", { status: 404 }); }, { host: "localhost", port: 3000 }); ``` ### HTTP methods ```js import http from "@rcompat/http"; await http.serve(async request => { const { pathname } = new URL(request.url); const { method } = request; if (pathname === "/api/data") { if (method === "GET") { return Response.json({ data: "value" }); } if (method === "POST") { const body = await request.json(); return Response.json({ received: body }, { status: 201 }); } return new Response("Method Not Allowed", { status: 405 }); } return new Response("Not Found", { status: 404 }); }, { host: "localhost", port: 3000 }); ``` ### Request cancellation `request.signal` is a stable `AbortSignal`. Pass it to downstream work so a client disconnect can cancel work even after the request body has been read: ```js import http from "@rcompat/http"; await http.serve(async request => { const body = await request.text(); return fetch("https://api.example.com/relay", { method: "POST", body, signal: request.signal, }); }, { host: "localhost", port: 3000 }); ``` On Node, premature client disconnection aborts the signal once with an `AbortError`. Finishing the request body does **not** abort it: cancellation remains observable while the handler waits and while the response streams. Normal response completion removes the transport listeners without aborting the signal. Later closure or reuse of that connection does not change a completed request's signal. A signal is a cancellation notification, not proof that response bytes were processed by the client. Pending Node WebSocket handshakes are observed until rejection completes or a successful upgrade transfers ownership. After upgrade, use WebSocket lifecycle events rather than the HTTP request signal. Bun and Deno use their native request signals. Bun supports the disconnect cases above. Deno detects an interrupted upload through rejection of the body read, but may defer its signal's cancellation until the handler returns; do not rely solely on that signal to detect an incomplete body. Deno's legacy request behavior may also abort a signal after a successful response. Across runtimes, do not treat the signal as a success/failure record after the response lifetime ends, and handle body-reading errors separately from downstream cancellation. HTTP servers remain unavailable in browsers. ### Streaming multipart forms `http.multipart(content_type, source, options?)` reads a Web `ReadableStream` in wire order on Node, Bun, Deno, and in browsers. Each part has a field `name`, an optional `filename` and `content_type`, and a `body` byte stream. The content type includes any parameters from the part header. Filenames have path components stripped. ```js import http from "@rcompat/http"; async function upload(request, open_file_sink) { const content_type = request.headers.get("content-type"); if (content_type === null || request.body === null) { return new Response("Expected a multipart body", { status: 400 }); } for await (const part of http.multipart(content_type, request.body, { max_parts: 32, max_part_bytes: 8 * 1024 * 1024, signal: request.signal, })) { if (part.filename !== undefined) { const sink = await open_file_sink(part); await part.body.pipeTo(sink); } } return new Response(null, { status: 204 }); } ``` - Read each body before advancing the iterator. The parser reads on demand, retaining framing lookbehind and any unconsumed bytes from the current source chunk. Advancing completes any in-flight read, closes the old body, and discards its unread content. Canceling a part stops its body reads. The next iterator step discards its unread content. - Breaking the loop or calling the iterator's `return()` cancels the input and releases its reader. Normal iteration through the end consumes the epilogue and releases the reader. - `max_parts` defaults to 128 and `max_part_bytes` defaults to 16 MiB. Both accept nonnegative safe integers and apply to skipped parts. The parser also bounds preamble and part headers at 64 KiB each and bounds individual lines and delimiter suffix lookbehind at approximately 16 KiB. Enforce any total upload limit on the source stream. - Malformed input raises `http.MultipartError`. Parser limits raise `http.MultipartLimitError`. Errors reject the body read or iterator step that encounters them. Source failures and the supplied signal's abort reason propagate unchanged. The package exports the TypeScript types `MultipartPart` and `MultipartOptions`. The existing `request.formData()` API continues to buffer fields and files. ### Status codes ```js import http from "@rcompat/http"; const { Status } = http; await http.serve(request => { return new Response("Created", { status: Status.CREATED }); }, { host: "localhost", port: 3000 }); // available status codes Status.OK; // 200 Status.CREATED; // 201 Status.NO_CONTENT; // 204 Status.MOVED_PERMANENTLY; // 301 Status.NOT_MODIFIED; // 304 Status.BAD_REQUEST; // 400 Status.UNAUTHORIZED; // 401 Status.FORBIDDEN; // 403 Status.NOT_FOUND; // 404 Status.INTERNAL_SERVER_ERROR; // 500 // ... and many more ``` ### WebSockets ```js import http from "@rcompat/http"; const server = await http.serve(request => { // check if it's a WebSocket upgrade request if (request.headers.get("upgrade") === "websocket") { return server.upgrade(request, { open(socket) { console.log("Client connected"); socket.send("Welcome!"); }, message(socket, message) { console.log("Received:", message); socket.send(`Echo: ${message}`); }, close(socket) { console.log("Client disconnected"); }, }); } return new Response("Hello!"); }, { host: "localhost", port: 3000 }); ``` ### SSL/HTTPS ```js import http from "@rcompat/http"; import fs from "@rcompat/fs"; await http.serve(request => { return new Response("Secure!"); }, { host: "localhost", port: 443, ssl: { cert: fs.ref("./certs/cert.pem"), key: fs.ref("./certs/key.pem"), }, }); ``` ### MIME types Get MIME types by extension or use predefined constants. ```js import http from "@rcompat/http"; http.toMIME("index.html"); // "text/html" http.toMIME("app.js"); // "text/javascript" http.toMIME("data.json"); // "application/json" http.toMIME("image.png"); // "image/png" http.MIME.APPLICATION_JSON; // "application/json" http.MIME.APPLICATION_X_WWW_FORM_URLENCODED; // "application/x-www-form-urlencoded" http.MIME.TEXT_EVENT_STREAM; // "text/event-stream" http.MIME.TEXT_HTML; // "text/html" ``` ### Serving static files ```js import http from "@rcompat/http"; import fs from "@rcompat/fs"; const publicFiles = fs.ref("./public"); const files = new Map([ ["/", publicFiles.join("index.html")], ["/app.js", publicFiles.join("app.js")], ]); await http.serve(async request => { const { pathname } = new URL(request.url); const file = files.get(pathname); if (file !== undefined && await file.exists()) { return new Response(file.stream(), { headers: { "content-type": http.toMIME(file.name) }, }); } return new Response("Not Found", { status: 404 }); }, { host: "localhost", port: 3000 }); ``` ## Timeout configuration Timeout members are configured as whole milliseconds: - `inactivity` is the maximum consecutive network inactivity during an in-flight request or response. Traffic resets it. It is not the keep-alive timeout after an exchange. - `request` is the maximum total time to receive the complete incoming request, including headers and body. Traffic does not reset it. Handler and response time are excluded. - `headers` is the maximum total time to receive complete request headers. | Member | Node | Bun | Deno | |--------|------|-----|------| | `inactivity` | Supported | Supported; rounded up to seconds | Unsupported | | `request` | Supported | Unsupported | Unsupported | | `headers` | Supported | Unsupported | Unsupported | Omitting `timeout`, or using an empty object, preserves the runtime defaults. Individual omitted members also preserve native defaults. Bun's current native inactivity default is 10 seconds. Node currently defaults to no inactivity timeout, a 300-second request timeout, and the lesser of 60 seconds or its request timeout for headers. In particular, Node derives an omitted header timeout as `0` when `request: 0` is configured. `0` disables a supported clock. Configuring any timeout member on Deno, or configuring `request` or `headers` on Bun, throws before the server binds—even when the value is `0`. Unsupported clocks are not silently ignored or emulated as handler deadlines. `inactivity` accepts values through `255000`, Bun's portable maximum. Node-only request and header clocks accept values through `2147483647`. When both are enabled, `headers` cannot exceed `request`; an explicit header timeout is also validated against Node's effective request default. The object is strict: unknown members and non-integer values are rejected. The previous numeric form is breaking and must be migrated: ```js // before timeout: 30_000 // now timeout: { inactivity: 30_000 } ``` ## WebSocket portability Text messages are strings and binary messages are `Uint8Array` values on every runtime. The portable socket supports `send()`, `close()`, and `readyState`. Node limits each assembled incoming or outgoing message to 16 MiB and does not negotiate WebSocket extensions. When clients offer subprotocols, Node selects the first offered protocol. Node caps queued outgoing data at 32 MiB; `bufferedAmount` reports the bytes currently waiting to be written. ## Examples ### REST API ```js import http from "@rcompat/http"; const { Status } = http; const users = new Map(); await http.serve(async request => { const { pathname } = new URL(request.url); const { method } = request; // GET /users if (method === "GET" && pathname === "/users") { return Response.json([...users.values()]); } // POST /users if (method === "POST" && pathname === "/users") { const user = await request.json(); user.id = crypto.randomUUID(); users.set(user.id, user); return Response.json(user, { status: Status.CREATED }); } // GET /users/:id const match = pathname.match(/^\/users\/(.+)$/); if (method === "GET" && match) { const user = users.get(match[1]); if (user) return Response.json(user); return Response.json({ error: "Not found" }, { status: Status.NOT_FOUND }); } return new Response("Not Found", { status: Status.NOT_FOUND }); }, { host: "localhost", port: 3000 }); ``` ### Chat server with WebSockets ```js import http from "@rcompat/http"; const clients = new Set(); const server = await http.serve(request => { if (request.headers.get("upgrade") === "websocket") { return server.upgrade(request, { open(socket) { clients.add(socket); broadcast(`User joined (${clients.size} online)`); }, message(socket, message) { broadcast(`User: ${message}`); }, close(socket) { clients.delete(socket); broadcast(`User left (${clients.size} online)`); }, }); } return new Response("WebSocket server"); }, { host: "localhost", port: 3000 }); function broadcast(message) { for (const client of clients) { client.send(message); } } ``` ## Cross-Runtime Compatibility | Runtime | Support | | ------- | ------------------------------------------------- | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | Constants, MIME resolution, and multipart parsing | Browser bundles can safely import the package. [`http.MIME`](/api/http#http-mime), [`http.Status`](/api/http#http-status), [`http.methods`](/api/http#http-methods), [`http.toMIME`](/api/http#http-tomime), and `http.multipart()` work in browsers. [`http.serve`](/api/http#http-serve) throws because browsers cannot listen for incoming HTTP connections. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/io # @rcompat/io This module provides standard input and output streams, asynchronous context, terminal detection, command execution, and child-process management. ## Installation ```bash npm install @rcompat/io ``` ```bash pnpm add @rcompat/io ``` ```bash yarn add @rcompat/io ``` ```bash bun add @rcompat/io ``` ## Usage ### Standard streams ```js import io from "@rcompat/io"; // write to stdout (no newline) io.stdout.write("Hello, "); io.stdout.write("World!\n"); // write to stderr io.stderr.write("Error: something went wrong\n"); ``` ### Check if running in a terminal ```js import io from "@rcompat/io"; if (io.isatty()) { // interactive terminal - show colors, prompts, etc. console.log("\x1b[32mGreen text!\x1b[0m"); } else { // piped or redirected - plain output console.log("Plain text"); } ``` ### Run a command ```js import io from "@rcompat/io"; // capture output and exit status const result = await io.run("echo hello"); console.log(result.stdout); // "hello\n" console.log(result.success); // true // with options const files = await io.run("ls -la", { cwd: "/tmp", timeout: 5_000 }); ``` ### Spawn a process ```js import io from "@rcompat/io"; const child = io.spawn("cat", { cwd: "." }); const { stdin, stdout } = child; // write to process stdin (Web WritableStream) const writer = stdin.getWriter(); await writer.write(new TextEncoder().encode("Hello from stdin!")); await writer.close(); // read from process stdout (Web ReadableStream) const reader = stdout.getReader(); const { value } = await reader.read(); console.log(new TextDecoder().decode(value)); // "Hello from stdin!" const status = await child.status; console.log(status.code); // 0 ``` Pass an executable and argument array separately to bypass the shell: ```js const child = io.spawn(process.execPath, ["--version"], { stdio: { stdin: "ignore", stdout: "pipe", stderr: "inherit", }, }); ``` ### Find an executable ```js import io from "@rcompat/io"; const node = await io.which("node"); console.log(node); // "/usr/local/bin/node" const bun = await io.which("bun"); console.log(bun); // "/home/user/.bun/bin/bun" ``` `which` invokes the platform locator directly without a shell and returns its first non-empty result. ## Process execution behavior The two-argument form treats `command` as a platform-shell command. Supplying an argument array selects direct execution: `executable` is launched without a shell and every argument is passed verbatim. String commands run through the platform shell. Executable-plus-argv calls do not invoke a shell. A single `stdio` string applies to all three streams; the object form configures them independently and omitted entries default to `"pipe"`. A stream property is available only when its mode is `"pipe"` and is otherwise `null`. Nonzero exits resolve `status` with `success: false`. A failure to start may be thrown by `spawn()` or reject `status`, depending on when the host runtime reports it. `@rcompat/io` does not install signal handlers in the parent process; applications may await `status` and forward signals with `kill()`. On POSIX platforms, spawned commands run in an isolated process group. `kill()` and timeout handling signal the entire group so descendant processes cannot continue working or keep captured output streams open after the command has been terminated. A `run()` timeout covers process exit and complete output capture, not only the lifetime of the wrapper shell. ## Examples ### Run a command and process output ```js import io from "@rcompat/io"; async function getBranch() { const result = await io.run("git branch --show-current"); return result.success ? result.stdout.trim() : null; } const branch = await getBranch(); console.log(`Current branch: ${branch ?? "not a git repo"}`); ``` ### Stream processing with spawn ```js import io from "@rcompat/io"; const child = io.spawn("ping -c 3 localhost", { cwd: "." }); const { stdout } = child; const reader = stdout.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; process.stdout.write(decoder.decode(value)); } const status = await child.status; if (!status.success) console.error(status); ``` ### Check for required tools ```js import io from "@rcompat/io"; async function checkDependencies(tools) { const missing = []; for (const tool of tools) { try { await io.which(tool); } catch { missing.push(tool); } } return missing; } const missing = await checkDependencies(["git", "node", "docker"]); if (missing.length > 0) { console.error(`Missing tools: ${missing.join(", ")}`); process.exit(1); } ``` ### Conditional formatting ```js import io from "@rcompat/io"; function log(message, color = 32) { if (io.isatty()) { io.stdout.write(`\x1b[${color}m${message}\x1b[0m\n`); } else { io.stdout.write(`${message}\n`); } } log("Success!", 32); // green in terminal, plain when piped log("Warning!", 33); // yellow in terminal log("Error!", 31); // red in terminal ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | Import only | Browser bundles can safely import the package, but every utility throws because standard streams, async process context, and child processes are unavailable. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/is # @rcompat/is This module provides boolean type guards for common value checks with TypeScript type narrowing. ## Installation ```bash npm install @rcompat/is ``` ```bash pnpm add @rcompat/is ``` ```bash yarn add @rcompat/is ``` ```bash bun add @rcompat/is ``` ## Usage ### nullish Checks if a value is `null` or `undefined`. ```js import is from "@rcompat/is"; is.nullish(null); // true is.nullish(undefined); // true is.nullish(0); // false is.nullish(""); // false is.nullish(false); // false ``` ### defined Checks if a value is not `undefined` and narrows its type accordingly. ```js import is from "@rcompat/is"; is.defined("hello"); // true is.defined(0); // true is.defined(null); // true is.defined(undefined); // false ``` ### truthy Checks if a value is truthy and excludes statically representable falsy values from its type. ```js import is from "@rcompat/is"; is.truthy(1); // true is.truthy("hello"); // true is.truthy([]); // true is.truthy(0); // false is.truthy(""); // false is.truthy(null); // false ``` ### falsy Checks if a value is falsy. ```js import is from "@rcompat/is"; is.falsy(0); // true is.falsy(""); // true is.falsy(null); // true is.falsy(undefined); // true is.falsy(false); // true is.falsy(NaN); // true is.falsy(1); // false ``` ### empty Checks if a value is empty (strings, arrays, Sets, Maps, objects). ```js import is from "@rcompat/is"; is.empty(""); // true is.empty([]); // true is.empty({}); // true is.empty(new Set()); // true is.empty(new Map()); // true is.empty("hello"); // false is.empty([1, 2]); // false is.empty({ a: 1 }); // false ``` ### blank Checks if a string is empty or contains only whitespace. ```js import is from "@rcompat/is"; is.blank(""); // true is.blank(" "); // true is.blank("\t\n"); // true is.blank("hello"); // false is.blank(" hi "); // false ``` ### numeric Checks if a string represents a valid number. ```js import is from "@rcompat/is"; is.numeric("123"); // true is.numeric("-45.67"); // true is.numeric("1e10"); // true is.numeric("+3.14"); // true is.numeric("abc"); // false is.numeric(""); // false is.numeric("12px"); // false ``` ### int Checks if a value is an integer number. ```js import is from "@rcompat/is"; is.int(42); // true is.int(-10); // true is.int(0); // true is.int(3.14); // false is.int(NaN); // false is.int("42"); // false ``` ### uint Checks if a value is a non-negative integer (unsigned). ```js import is from "@rcompat/is"; is.uint(1); // true is.uint(100); // true is.uint(0); // true is.uint(-1); // false is.uint(3.14); // false ``` ### safeint Checks if a value is a safe integer (within JavaScript's safe range). ```js import is from "@rcompat/is"; is.safeint(42); // true is.safeint(Number.MAX_SAFE_INTEGER); // true is.safeint(Number.MAX_SAFE_INTEGER + 1); // false is.safeint(3.14); // false ``` ### finite Checks if a number or bigint is finite. ```js import is from "@rcompat/is"; is.finite(42); // true is.finite(3.14); // true is.finite(100n); // true (bigints are always finite) is.finite(Infinity); // false is.finite(-Infinity); // false is.finite(NaN); // false ``` ### nan Checks if a value is `NaN`. ```js import is from "@rcompat/is"; is.nan(NaN); // true is.nan(Number.NaN); // true is.nan(0 / 0); // true is.nan(42); // false is.nan("NaN"); // false ``` ### primitive Checks if a value is a primitive type. ```js import is from "@rcompat/is"; is.primitive("hello"); // true is.primitive(42); // true is.primitive(true); // true is.primitive(null); // true is.primitive(undefined); // true is.primitive(Symbol()); // true is.primitive(100n); // true is.primitive({}); // false is.primitive([]); // false ``` ### dict Checks if a value is a plain object (not array, Date, class instance, etc.). ```js import is from "@rcompat/is"; is.dict({}); // true is.dict({ a: 1 }); // true is.dict(Object.create(null)); // true is.dict([]); // false is.dict(new Date()); // false is.dict(new Map()); // false is.dict(null); // false ``` ### newable Checks if a value is a constructor (can be called with `new`). ```js import is from "@rcompat/is"; is.newable(class {}); // true is.newable(function() {}); // true is.newable(Date); // true is.newable(() => {}); // false (arrow functions) is.newable({}); // false ``` ### boolish Checks if a value is the string `"true"` or `"false"`. ```js import is from "@rcompat/is"; is.boolish("true"); // true is.boolish("false"); // true is.boolish(true); // false (not a string) is.boolish("yes"); // false is.boolish("1"); // false ``` ## Examples ### Filter valid values ```js import is from "@rcompat/is"; const values = [1, null, 2, undefined, 3]; values.filter(is.defined); // [1, null, 2, 3] values.filter(v => !is.nullish(v)); // [1, 2, 3] ``` ### Parse configuration ```js import is from "@rcompat/is"; function parseEnvVar(value) { if (is.boolish(value)) return value === "true"; if (is.numeric(value)) return Number(value); return value; } parseEnvVar("true"); // true parseEnvVar("42"); // 42 parseEnvVar("hello"); // "hello" ``` ### Validate input ```js import is from "@rcompat/is"; function validateForm(data) { const errors = []; if (is.blank(data.name)) { errors.push("Name is required"); } if (!uint(data.age)) { errors.push("Age must be a positive integer"); } return errors; } ``` ### Type-safe guards ```js import is from "@rcompat/is"; function process(value) { if (is.primitive(value)) { // TypeScript knows: value is: // string | number | boolean | bigint | symbol | null | undefined return String(value); } if (is.dict(value)) { // TypeScript knows: value is Record return JSON.stringify(value); } return "[complex object]"; } ``` ## Cross-Runtime Compatibility | Runtime | Supported | |---------|-----------| | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/net # @rcompat/net This module opens raw TCP and Unix domain socket connections exposed through Web Streams. Each supported environment uses its native socket implementation without a shared polyfill or compatibility shim. Browser bundles can safely import the package, but calling [`net.open()`](/api/net#net-open) rejects because browsers do not expose raw TCP or Unix sockets. ## Installation ```bash npm install @rcompat/net ``` ```bash pnpm add @rcompat/net ``` ```bash yarn add @rcompat/net ``` ```bash bun add @rcompat/net ``` ## Usage ### Opening a connection ```js import net from "@rcompat/net"; // unix domain socket const unixSocket = await net.open({ path: "/var/run/example.sock" }); // tcp const tcpSocket = await net.open({ host: "127.0.0.1", port: 9999 }); ``` ### Writing and reading ```js import net from "@rcompat/net"; const socket = await net.open({ path: "/var/run/example.sock" }); await socket.write("ping\n"); await socket.end(); // half-close — stop writing, keep reading const response = await socket.text(); // drains readable to a string ``` ### Streaming chunks ```js import net from "@rcompat/net"; const socket = await net.open({ host: "127.0.0.1", port: 9999 }); await socket.write("subscribe\n"); for await (const chunk of socket) { console.log(new TextDecoder().decode(chunk)); } ``` ### Closing ```js import net from "@rcompat/net"; const socket = await net.open({ path: "/var/run/example.sock" }); await socket.write("hello\n"); await socket.close(); // closes both write and read sides ``` `end()` only closes the write side (sends FIN, server can still respond) — use it when you expect a response after writing. `close()` tears down both sides — use it when you're done with the connection entirely. ## Examples ### Talking to a control-plane socket (e.g. HAProxy) ```js import net from "@rcompat/net"; async function command(input) { const socket = await net.open({ path: "/var/run/haproxy.sock" }); await socket.write(`${input}\n`); await socket.end(); return socket.text(); } await command("show info"); ``` ### Simple TCP request/response ```js import net from "@rcompat/net"; const socket = await net.open({ host: "api.internal", port: 8080 }); await socket.write("STATUS\n"); await socket.end(); console.log(await socket.text()); ``` ## Cross-Runtime Compatibility | Runtime | Support | | ------- | -------------------------------- | | Browser | Import only; sockets unavailable | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | No configuration required — `@rcompat/net` resolves the correct native implementation per runtime via package export conditions. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/runtime # @rcompat/runtime This module identifies the current JavaScript environment and provides its executable path, current script, arguments, memory usage, and process controls. It uses [runtime keys](https://runtime-keys.proposal.wintercg.org) for accurate detection without any runtime overhead. ## Installation ```bash npm install @rcompat/runtime ``` ```bash pnpm add @rcompat/runtime ``` ```bash yarn add @rcompat/runtime ``` ```bash bun add @rcompat/runtime ``` ## Usage ### Basic detection ```js import runtime from "@rcompat/runtime"; console.log(runtime.name); // "node" | "bun" | "deno" | "browser" ``` ### Conditional logic ```js import runtime from "@rcompat/runtime"; if (runtime.name === "bun") { // Bun-specific code } else if (runtime.name === "deno") { // Deno-specific code } else if (runtime.name === "node") { // Node.js-specific code } ``` ### Executable path ```js import runtime from "@rcompat/runtime"; console.log(runtime.bin); // "/usr/local/bin/node" // "/home/user/.bun/bin/bun" // "/usr/bin/deno" ``` ### Current script ```js import runtime from "@rcompat/runtime"; console.log(runtime.script); // "/path/to/your/script.js" ``` ### Program arguments ```js import runtime from "@rcompat/runtime"; // running: node app.js foo bar console.log(runtime.args); // ["foo", "bar"] ``` [`runtime.args`](/api/runtime#runtime-args) always contains only your program's arguments — the runtime executable and script path are stripped away, consistently across all runtimes. ### Exiting the process ```js import runtime from "@rcompat/runtime"; runtime.exit(0); // success runtime.exit(1); // failure ``` In browsers, process operations such as `exit`, `cwd`, and `resolve` throw an `unimplemented` error. ### Current-process lifecycle On POSIX Node, Bun, and Deno, `runtime.on.interrupt(callback)`, `runtime.on.terminate(callback)`, and `runtime.on.hangup(callback)` subscribe to SIGINT, SIGTERM, and SIGHUP respectively. Each registration returns its own idempotent unsubscribe function, including when the same callback is registered twice. Subscriptions remain active until removed; callbacks run on each delivery. `runtime.interrupt()`, `runtime.terminate()`, and `runtime.hangup()` send the corresponding signal to this process without removing any listeners. All intercepting listeners (including listeners installed outside rcompat) must be removed before a re-signal can restore default termination. A signal listener alone does not keep the process alive. ```js import runtime from "@rcompat/runtime"; const timeout = ms => new Promise((_, reject) => { setTimeout(() => reject(new Error("shutdown timed out")), ms); }); const unsubscribe = runtime.on.terminate(() => { void (async () => { try { await Promise.race([closeResources(), timeout(2000)]); } catch (error) { console.error("cleanup failed", error); } finally { unsubscribe(); runtime.terminate(); } })(); }); ``` The application supplies `closeResources` and handles cleanup errors according to its policy. Use `finally` to remove its listener and re-signal even if cleanup rejects or times out. Re-signalling does not override other signal listeners. `runtime.before.exit(callback)` registers one callback for natural event-loop exhaustion. It removes itself **before** calling the callback, so scheduled asynchronous cleanup can finish without invoking the callback again. The subscription keeps the event loop alive until the callback's returned promise settles, even if its work has no referenced I/O or timer of its own. The returned unsubscribe is idempotent. Consumers must still bound cleanup: a promise that never settles keeps the process alive indefinitely. The callback is not invoked after `runtime.exit()`, forced exits, crashes, or `SIGKILL`. The runtime does not swallow callback exceptions or rejected promises; the consumer must handle errors and bound cleanup itself. These lifecycle operations throw `unimplemented` when called in browsers. Windows signal behavior is not supported by this contract. ### Module resolution ```js const filename = runtime.resolve("example", "/path/to/project"); ``` `runtime.resolve()` resolves relative and absolute paths directly. For bare package specifiers, it finds the owning `node_modules` package and applies ESM `exports` or `imports` using the running host's import conditions. Resolution preserves nested package ownership, package self references, subpath patterns, and legacy `main` packages. It returns a filesystem path; built-in `node:` specifiers remain unchanged. This is import resolution, not `require.resolve()`. Use `runtime.toRequire()` when CommonJS resolution is specifically required. Browsers do not have an npm package filesystem and throw `unimplemented` when `resolve()` is called. Node resolution observes startup conditions from command-line options and `NODE_OPTIONS`. Bun uses its native resolver first. Deno resolution observes its built-in conditions and readable `DENO_CONDITIONS`; Deno does not expose CLI `--conditions` after startup or reveal when those values override the environment, so `runtime.resolve()` cannot reproduce hidden CLI conditions. ### Process memory usage ```js const usage = runtime.memoryUsage(); if (usage) { console.log(usage.rss); console.log(usage.heapUsed); } ``` [`runtime.memoryUsage()`](/api/runtime#runtime-memoryusage) returns an instantaneous aggregate process-memory sample. Every available value is measured in bytes. It does not trigger garbage collection, enable an inspector or profiler, retain sample history, or start background sampling. Node and Bun provide all fields. Deno does not expose `arrayBuffers` through its native aggregate API, so that field is `undefined`. Browsers return `undefined` because there is no portable browser API with equivalent process memory categories. In particular, this package does not use the non-standard Chromium-only `performance.memory` API. ## Supported Runtimes | Runtime | Value | | ------- | ----------- | | Node.js | `"node"` | | Bun | `"bun"` | | Deno | `"deno"` | | Browser | `"browser"` | ## How It Works This package uses [runtime keys](https://runtime-keys.proposal.wintercg.org), a WinterCG proposal for runtime detection. The `exports` field in `package.json` routes to different files based on the runtime condition, meaning detection happens at import time with zero runtime overhead. ```json { "exports": { ".": { "bun": "./lib/public/bun.js", "deno": "./lib/public/deno.js", "browser": "./lib/public/browser.js", "node": "./lib/public/node.js" } } } ``` Each file simply exports the runtime object for that environment: ```ts // node.ts export default { name: "node", bin: process.execPath, script: process.argv[1], args: process.argv.slice(2), exit: (code?: number) => process.exit(code), }; ``` ## Examples ### Relaunching with custom flags ```js import runtime from "@rcompat/runtime"; import io from "@rcompat/io"; // relaunch self with --conditions=source const child = io.spawn(runtime.bin, [ "--conditions=@rcompat/source", runtime.script, ...runtime.args, ], { stdio: "inherit" }); const status = await child.status; runtime.exit(status.code ?? 1); ``` ### Runtime-specific logging ```js import runtime from "@rcompat/runtime"; const logger = { info(message) { console.log(`[${runtime.name}]`, message); } }; logger.info("Server started"); // [node] Server started // [bun] Server started ``` ### Environment checks ```js import runtime from "@rcompat/runtime"; const isServerRuntime = ["node", "bun", "deno"].includes(runtime.name); const isClientRuntime = runtime.name === "browser"; ``` ### Debug information ```js import runtime from "@rcompat/runtime"; function getDebugInfo() { return { runtime: runtime.name, script: runtime.script, args: runtime.args, timestamp: Date.now(), }; } ``` ### Reading active conditions ```ts import runtime from "@rcompat/runtime"; const conditions = await runtime.conditions(); ``` ## Cross-Runtime Compatibility | Runtime | Supported | |--------------------|-----------| | Node.js | ✓ | | Bun | ✓ | | Deno | ✓ | | Browser | Limited | Browser detection and argument flags work. Process, filesystem-project, and module-resolution operations are unavailable, and process memory usage returns `undefined`. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/source-map # @rcompat/source-map This module provides dependency-free Source Map v3 consumption through [`SourceMap`](/api/source-map#sourcemap), with validated mappings and normalized names, missing positions, and source roots. Native lookup is selected where available, with a shared VLQ decoder as the portable implementation. ## Installation ```bash npm install @rcompat/source-map ``` ```bash pnpm add @rcompat/source-map ``` ```bash yarn add @rcompat/source-map ``` ```bash bun add @rcompat/source-map ``` ## Usage ```ts import SourceMap from "@rcompat/source-map"; const map = new SourceMap({ version: 3, sources: ["src/app.ts"], names: ["start"], mappings: "AAAAA", }); map.original(1, 1); // { source: "src/app.ts", line: 1, column: 1, name: "start" } new SourceMap(JSON.stringify({ version: 3, sources: ["app.ts"], sourceRoot: "file:///project/src/", mappings: "AAAA", })).original(1, 1); // { source: "file:///project/src/app.ts", line: 1, column: 1 } ``` Both generated inputs and returned original line/column numbers are **one-based**. The closest preceding segment on the *same* generated line applies until the next segment. Unmapped segments, lines with no mapping, and invalid input positions return `undefined`. Invalid map payloads and malformed VLQ segments throw `TypeError` during construction instead of yielding invalid positions. `sourceRoot` is resolved against relative sources, normalizing `.` and `..` in URL, relative-path, and absolute-path roots. Absolute source URLs remain unchanged. The optional `name` belongs only to a segment explicitly carrying a name; native consumers may retain a previous name, and Deno omits names, so the package normalizes them through the validated mappings. No native `SourceMap` type is part of the public API. --- Source: https://rcompat.repopack.app/packages/sqlite # @rcompat/sqlite This module provides synchronous SQLite database connections, prepared statements, positional and named bindings, and change metadata through native SQLite implementations. Browser bundles can safely import the package, but constructing [`Database`](/api/sqlite#database) throws because no portable browser SQLite implementation is provided. ## Installation ```bash npm install @rcompat/sqlite ``` ```bash pnpm add @rcompat/sqlite ``` ```bash yarn add @rcompat/sqlite ``` ```bash bun add @rcompat/sqlite ``` ## Usage ### Opening a database ```js import Database from "@rcompat/sqlite"; // file-based database const db = new Database("./data.db"); // in-memory database const memDb = new Database(":memory:"); // read-only mode const readOnly = new Database("./data.db", { readonly: true }); // safe integers (returns BigInt for integers) const safeDb = new Database("./data.db", { safeIntegers: true }); ``` ### Executing queries ```js import Database from "@rcompat/sqlite"; const db = new Database(":memory:"); // create a table db.exec(` CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT, email TEXT ) `); // insert data db.exec("INSERT INTO users (name, email) VALUES (?, ?)", "Bob", "bob@web.com"); ``` ### Prepared statements ```js import Database from "@rcompat/sqlite"; const db = new Database(":memory:"); db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); // prepare a statement for reuse const insert = db.prepare("INSERT INTO users (name) VALUES (?)"); insert.run("John"); // { changes: 1, lastInsertRowid: 1 } insert.run("Bob"); // { changes: 1, lastInsertRowid: 2 } insert.run("Charlie"); // { changes: 1, lastInsertRowid: 3 } insert.close(); ``` ### Querying data ```js import Database from "@rcompat/sqlite"; const db = new Database(":memory:"); db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); db.exec("INSERT INTO users (name) VALUES (?)", "John"); db.exec("INSERT INTO users (name) VALUES (?)", "Bob"); const query = db.prepare("SELECT * FROM users"); // get first row query.get(); // { id: 1, name: "John" } // get all rows query.all(); // [{ id: 1, name: "John" }, { id: 2, name: "Bob" }] query.close(); ``` ### Closing statements Prepared statements are reusable until explicitly closed. Call `close()` when a statement is no longer needed so its native resources and schema locks can be released deterministically: ```js const query = db.prepare("SELECT * FROM users WHERE id = ?"); try { const user = query.get(1); } finally { query.close(); } ``` `close()` is synchronous and idempotent. Calling `get()`, `all()`, or `run()` afterward throws `SQLite statement is closed`. `Database.exec()` creates and closes its one-shot statement automatically, including when execution throws; it does not close statements returned by `prepare()`. Node and Bun close the native statement handle. Deno's current `node:sqlite` implementation does not expose native statement finalization, so `close()` invalidates the portable wrapper there but cannot explicitly finalize the inaccessible native handle. Consumed statements still permit the tested schema changes on Deno. ### Parameters #### Positional parameters ```js const stmt = db.prepare("SELECT * FROM users WHERE id = ? AND name = ?"); stmt.get(1, "Bob"); ``` #### Named parameters ```js // $-style const stmt1 = db.prepare("SELECT * FROM users WHERE id = $id AND name = $name"); stmt1.get({ $id: 1, $name: "Bob" }); // @-style const stmt2 = db.prepare("SELECT * FROM users WHERE id = @id"); stmt2.get({ "@id": 1 }); // :-style const stmt3 = db.prepare("SELECT * FROM users WHERE id = :id"); stmt3.get({ ":id": 1 }); ``` ### Closing the database ```js import Database from "@rcompat/sqlite"; const db = new Database("./data.db"); // ... do work ... db.close(); ``` ## Examples ### CRUD operations ```js import Database from "@rcompat/sqlite"; const db = new Database(":memory:"); // create db.exec(` CREATE TABLE products ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL ) `); // insert const insert = db.prepare("INSERT INTO products (name, price) VALUES (?, ?)"); insert.run("Widget", 9.99); insert.run("Gadget", 19.99); // read const findById = db.prepare("SELECT * FROM products WHERE id = ?"); const product = findById.get(1); // { id: 1, name: "Widget", price: 9.99 } // update const update = db.prepare("UPDATE products SET price = ? WHERE id = ?"); update.run(14.99, 1); // delete const remove = db.prepare("DELETE FROM products WHERE id = ?"); remove.run(2); // list all const all = db.prepare("SELECT * FROM products").all(); // [{ id: 1, name: "Widget", price: 14.99 }] ``` ### Transaction pattern ```js import Database from "@rcompat/sqlite"; const db = new Database("./app.db"); function transferFunds(fromId, toId, amount) { db.exec("BEGIN TRANSACTION"); try { db.exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, fromId); db.exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", amount, toId); db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } ``` ### Safe integers for large values ```js import Database from "@rcompat/sqlite"; const db = new Database(":memory:", { safeIntegers: true }); db.exec("CREATE TABLE big_numbers (id INTEGER PRIMARY KEY, value INTEGER)"); db.exec("INSERT INTO big_numbers (value) VALUES (?)", 9007199254740993n); const row = db.prepare("SELECT * FROM big_numbers").get(); // { id: 1n, value: 9007199254740993n } ``` ## Cross-Runtime Compatibility | Runtime | Support | Native module | | ------- | ----------- | ------------- | | Browser | Import only | — | | Node.js | ✓ | `node:sqlite` | | Bun | ✓ | `bun:sqlite` | | Deno | ✓ | `node:sqlite` | No configuration is required on Node, Deno, or Bun. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/string # @rcompat/string This module provides Base64 encoding, case conversion, dedentation, glob matching, SemVer range matching, slug generation, and UTF-8 byte measurement. ## Installation ```bash npm install @rcompat/string ``` ```bash pnpm add @rcompat/string ``` ```bash yarn add @rcompat/string ``` ```bash bun add @rcompat/string ``` ## Usage ### Base64 encoding/decoding ```js import string from "@rcompat/string"; // encode to Base64 const encoded = string.Base64.encode("Hello, World!"); console.log(encoded); // "SGVsbG8sIFdvcmxkIQ==" // decode from Base64 const decoded = string.Base64.decode(encoded); console.log(decoded); // "Hello, World!" ``` ### Convert to camelcase ```js import string from "@rcompat/string"; // from kebab case string.toCamelCase("hello-world"); // "helloWorld" string.toCamelCase("my-component"); // "myComponent" // from snake case string.toCamelCase("hello_world"); // "helloWorld" string.toCamelCase("user_profile"); // "userProfile" // mixed string.toCamelCase("my-user_name"); // "myUserName" ``` ### Dedent multi-line strings ```js import string from "@rcompat/string"; // as a template tag const sql = string.dedent` SELECT * FROM users WHERE active = true `; // "SELECT *\nFROM users\nWHERE active = true" // with interpolation const table = "users"; const query = string.dedent` SELECT * FROM ${table} WHERE id = 1 `; ``` ### Convert glob to RegExp ```js import string from "@rcompat/string"; // simple wildcards const pattern = string.glob("*.js"); pattern.test("app.js"); // true pattern.test("app.ts"); // false pattern.test("dir/app.js"); // false // double wildcard (recursive) const recursive = string.glob("**/*.js"); recursive.test("app.js"); // true recursive.test("src/app.js"); // true recursive.test("src/lib/app.js"); // true // single character wildcard const single = string.glob("file?.txt"); single.test("file1.txt"); // true single.test("fileA.txt"); // true single.test("file10.txt"); // false ``` ### Match a SemVer range `string.semver(version, range)` tests a concrete semantic version against an exact version or a range. It follows [Deno's SemVer range grammar](https://docs.deno.com/runtime/reference/std/semver/), including comparators, carets, tildes, partial versions, wildcards, hyphen ranges, and `||`. An empty range matches any stable version. Build metadata does not affect matching. A prerelease matches only if a satisfied comparator set includes a prerelease comparator with the same major, minor, and patch. Malformed inputs return `false`. ```js import string from "@rcompat/string"; string.semver("1.4.2", "^1.2.0 || 2.0.x"); // true string.semver("2.1.0", "^1.2.0 || 2.0.x"); // false string.semver("1.2.3+ci.7", "1.2.3"); // true string.semver("1.3.0-beta.2", ">=1.3.0-beta.1 <2"); // true ``` ### Convert to slug ```js import string from "@rcompat/string"; string.toSlug("Hello World"); // "hello-world" string.toSlug("café"); // "cafe" string.toSlug("naïve"); // "naive" string.toSlug("foo bar"); // "foo-bar" ``` ### Capitalize first letter ```js import string from "@rcompat/string"; string.upperfirst("hello"); // "Hello" string.upperfirst("world"); // "World" string.upperfirst("javaScript"); // "JavaScript" ``` ### Get UTF-8 byte length ```js import string from "@rcompat/string"; // ASCII (1 byte per character) string.utf8.bytelength("hello"); // 5 // unicode (variable bytes) string.utf8.bytelength("héllo"); // 6 (é = 2 bytes) string.utf8.bytelength("日本語"); // 9 (3 bytes each) string.utf8.bytelength("🎉"); // 4 (emoji = 4 bytes) ``` ### Get UTF-8 size ```js import string from "@rcompat/string"; string.utf8.size("hello"); // 5 string.utf8.size("héllo"); // 6 string.utf8.size("日本語"); // 9 string.utf8.size("🎉"); // 4 ``` ## Examples ### Generate component names ```js import string from "@rcompat/string"; function toComponentName(filename) { // "my-button.svelte" -> "MyButton" const name = filename.replace(/\.\w+$/, ""); return string.upperfirst(string.toCamelCase(name)); } toComponentName("my-button.svelte"); // "MyButton" toComponentName("user_profile.vue"); // "UserProfile" ``` ### Build SQL queries ```js import string from "@rcompat/string"; function buildQuery(table, conditions) { return string.dedent` SELECT * FROM ${table} WHERE ${conditions.join(" AND ")} ORDER BY created_at DESC `; } const query = buildQuery("users", ["active = true", "role = 'admin'"]); ``` ### File matching ```js import string from "@rcompat/string"; function matchFiles(files, pattern) { const regex = string.glob(pattern); return files.filter((file) => regex.test(file)); } const files = ["app.js", "app.ts", "src/utils.js", "src/lib/helper.js"]; matchFiles(files, "*.js"); // ["app.js"] matchFiles(files, "**/*.js"); // ["app.js", "src/utils.js", "src/lib/helper.js"] matchFiles(files, "src/**/*.js"); // ["src/utils.js", "src/lib/helper.js"] ``` ### Validate content length ```js import string from "@rcompat/string"; function validateContent(content, maxBytes = 1024) { const bytes = string.utf8.bytelength(content); if (bytes > maxBytes) { throw new Error(`Content exceeds ${maxBytes} bytes (got ${bytes})`); } return content; } validateContent("Hello"); // OK validateContent("日本語".repeat(500)); // Error: exceeds limit ``` ### Encode data for URL ```js import string from "@rcompat/string"; function encodeState(state) { const json = JSON.stringify(state); return string.Base64.encode(json); } function decodeState(encoded) { const json = string.Base64.decode(encoded); return JSON.parse(json); } const state = { page: 1, filter: "active" }; const encoded = encodeState(state); // "eyJwYWdlIjoxLCJmaWx0ZXIiOiJhY3RpdmUifQ==" const decoded = decodeState(encoded); // { page: 1, filter: "active" } ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Browser | ✓ | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/test # @rcompat/test This module provides test definition and execution with fluent assertions, deep equality, type and exception checks, fetch interception, spies, and module mocking. It integrates with the `proby` test runner. ## Installation ```bash npm install @rcompat/test ``` ```bash pnpm add @rcompat/test ``` ```bash yarn add @rcompat/test ``` ```bash bun add @rcompat/test ``` ## Usage ### Writing tests Create a `.spec.ts` or `.spec.js` file: ```ts import test from "@rcompat/test"; test.case("addition works", assert => { assert(1 + 1).equals(2); }); test.case("string concatenation", assert => { assert("hello" + " " + "world").equals("hello world"); }); ``` ### Running tests Use the `proby` test runner: ```bash npx proby ``` ### Configuring test discovery Test tools share the neutral `spec.config.ts` and `spec.config.js` contract. Define a configuration with the identity helper on the default test aggregate: ```ts import test from "@rcompat/test"; export default test.config({ monorepo: true, packages: "packages", include: ["src", "test"], loaders: ["loader.ts"], }); ``` The helper only provides typing and returns the same object; it does not register or execute tests. A type-only plain-object form is equivalent: ```ts import type { TestConfig } from "@rcompat/test"; export default { monorepo: true, } satisfies TestConfig; ``` `monorepo` defaults to `false`, `packages` to `"packages"`, `include` to `["src", "test"]`, and `loaders` to `[]`. Package and loader paths are relative to the project root. Include paths are relative to the project root, or to each selected package directory in monorepo mode. Proby also accepts legacy `proby.config.ts` and `proby.config.js` files and its existing `config(...)` helper. Keep exactly one supported configuration file; coexisting new or legacy names are rejected as ambiguous. ### Equality assertions ```js import test from "@rcompat/test"; test.case("equals", assert => { // primitives assert(42).equals(42); assert("hello").equals("hello"); assert(true).equals(true); // objects (deep equality) assert({ a: 1, b: 2 }).equals({ a: 1, b: 2 }); assert([1, 2, 3]).equals([1, 2, 3]); // nested structures assert({ users: [{ name: "Alice" }] }).equals({ users: [{ name: "Alice" }], }); }); test.case("nequals", assert => { assert(1).nequals(2); assert("foo").nequals("bar"); assert({ a: 1 }).nequals({ a: 2 }); }); ``` ### Boolean assertions ```js import test from "@rcompat/test"; test.case("boolean checks", assert => { assert(1 === 1).true(); assert(1 === 2).false(); assert(null).null(); assert(undefined).undefined(); }); ``` ### Instance assertions ```js import test from "@rcompat/test"; test.case("instanceof", assert => { assert(new Date()).instance(Date); assert(new Map()).instance(Map); assert([1, 2, 3]).instance(Array); }); ``` ### Exception assertions ```js import test from "@rcompat/test"; test.case("throws", assert => { // check that any error is thrown assert(() => { throw new Error("oops"); }).throws(); // check a specific error code assert(() => { throw Object.assign(new Error("oops"), { code: "oops" }); }).throws("oops"); // Check specific error type assert(() => { throw new TypeError("invalid input"); }).throws(TypeError); // check a specific error message assert(() => { throw new Error("invalid input"); }).throws("invalid input"); }); test.case("throws asynchronously", async assert => { await assert(async () => { throw new TypeError("invalid input"); }).throws(TypeError); }); test.case("tries (does not throw)", assert => { assert(() => { return 42; }).tries(); }); test.case("tries asynchronously", async assert => { await assert(async () => { await save(); }).tries(); }); ``` Asynchronous `throws()` and `tries()` assertions must be awaited. ### Type assertions ```ts import test from "@rcompat/test"; test.case("type checking", assert => { // compile-time type checks assert().type(); assert("hello").type(); // check types don't match assert().nottype(); assert(42).nottype(); // literal types assert<"foo">().type<"foo">(); assert<"foo">().nottype<"bar">(); }); ``` ### Async tests ```js import test from "@rcompat/test"; test.case("async operations", async assert => { const result = await Promise.resolve(42); assert(result).equals(42); }); ``` ### Cleanup with ended ```js import test from "@rcompat/test"; test.case("database test", async assert => { const db = await openDatabase(); const user = await db.createUser({ name: "Alice" }); assert(user.name).equals("Alice"); }); test.ended(async () => { // runs after all tests in this file await closeDatabase(); }); ``` ### Grouping tests Use [`test.group`](/api/test#test-group) to cluster related test cases together. Groups can be run individually via proby. ```js import test from "@rcompat/test"; test.group("addition", () => { test.case("integers", assert => { assert(1 + 1).equals(2); }); test.case("floats", assert => { assert(0.1 + 0.2).equals(0.3); }); }); test.group("subtraction", () => { test.case("integers", assert => { assert(3 - 1).equals(2); }); }); ``` Run a specific group: ```bash npx proby math.spec.ts addition ``` ### Mocking modules Use `test.mock` to replace a module's exports and `test.import` to import the mocked module. ```js import test from "@rcompat/test"; using math = test.mock("./math.ts", () => ({ add: (a, b) => 99, })); const { add } = await test.import("./math.ts"); test.case("returns mocked value", assert => { assert(add(1, 2)).equals(99); }); test.case("tracks calls", assert => { add(1, 2); assert(math.add.calls.length).equals(1); assert(math.add.calls[0]).equals([1, 2]); assert(math.add.called).true(); }); ``` Tracked mock functions record each call as a tuple of arguments in `calls`. Call tracking resets between test cases. ### Static mocks with proby When running tests with `proby`, you can preload mocks before a spec file is evaluated by adding a sibling mock file. - `foo.spec.ts` pairs with `foo.mock.ts` - `foo.spec.js` pairs with `foo.mock.js` `proby` loads the mock file before the spec file, so the spec's static imports see the mocked module immediately. ```ts // math.ts export function add(a: number, b: number) { return a + b; } ``` ```ts // math.mock.ts import test from "@rcompat/test"; test.mock("./math.ts", () => ({ add: (a: number, b: number) => 99, })); ``` ```ts // math.spec.ts import test from "@rcompat/test"; import { add } from "./math.ts"; test.case("static mock is loaded before the spec", assert => { assert(add(1, 2)).equals(99); }); ``` Static mocks are file-scoped when run through `proby`; they do not leak into later spec files. Module mocking currently requires Node.js `module.registerHooks`; other runtimes throw a descriptive unsupported error. ### Spying on functions Use `spy` to wrap a function and record every call made to it. The wrapped function behaves identically to the original but tracks its arguments. ```ts import test from "@rcompat/test"; const add = (a: number, b: number) => a + b; const tracked = test.spy(add); tracked(1, 2); tracked(3, 4); tracked.called; // true tracked.calls; // [[1, 2], [3, 4]] tracked.calls[0]; // [1, 2] ``` Use `spy` inside a test case to make call-tracking assertions: ```ts import test from "@rcompat/test"; test.case("tracks calls", assert => { const tracked = test.spy((a: number, b: number) => a + b); assert(tracked.called).false(); assert(tracked.calls).equals([]); tracked(1, 2); assert(tracked.called).true(); assert(tracked.calls).equals([[1, 2]]); assert(tracked(3, 4)).equals(7); }); ``` Pass a second argument to replace the implementation while still tracking calls: ```ts import test from "@rcompat/test"; test.case("mocks implementation", assert => { const tracked = test.spy( (a: number, b: number) => a + b, (a: number, b: number) => a * b, ); assert(tracked(2, 3)).equals(6); // mocker runs, not original assert(tracked.calls).equals([[2, 3]]); }); ``` ### Intercepting fetch Use `test.intercept` to block outbound fetch calls to a specific origin and replace them with fake responses. Calls to other origins pass through untouched. The intercept records every request so you can assert on what was called and how. ```js import test from "@rcompat/test"; using telegram = test.intercept("https://api.telegram.org", setup => { setup.post("/sendMessage", () => ({ ok: true, result: { message_id: 42 }, })); }); test.case("notifies user via telegram on signup", async assert => { await fetch("http://localhost:6161/signup", { method: "POST", body: JSON.stringify({ email: "foo@bar.com" }), }); // assert the path was hit the right number of times assert(telegram.calls("/sendMessage")).equals(1); // assert on the actual request that came in assert(telegram.requests("/sendMessage")[0].method).equals("POST"); }); ``` `using` restores the original fetch automatically when the file scope exits. For long-lived intercepts that need manual control, use `restore()` with `test.ended`: ```js const telegram = test.intercept("https://api.telegram.org", setup => { setup.post("/sendMessage", () => ({ ok: true, result: { message_id: 42 } })); }); test.case("first case", async assert => { // ... }); test.case("second case", async assert => { // ... }); test.ended(() => telegram.restore()); ``` Hitting a path on an intercepted origin that has no registered handler throws immediately, catching accidental unhandled calls early. ### Extending the asserter Use `test.extend` to attach custom assertion methods to the asserter. Useful for domain-specific assertions shared across many test cases. ```js import test from "@rcompat/test"; // create an extended test with custom assertions const myTest = test.extend((assert, subject) => ({ even() { const passed = subject % 2 === 0; // use the base asserter to report the result assert(passed).true(); return this; }, })); myTest.case("even numbers", assert => { assert(2).even(); assert(4).even(); }); ``` The factory receives the base `assert` function and the current `subject` (the value passed to `assert()`). Return an object whose methods will be mixed into every `Assert` instance for that test. The extended test keeps the full base surface — `group`, `mock`, `spy`, `import`, and `intercept` all keep working on it, so you can group, mock, and intercept exactly as you would on `test` itself. ```js import test from "@rcompat/test"; const myTest = test.extend((assert, subject) => ({ even() { assert(subject % 2 === 0).true(); return this; }, })); myTest.group("arithmetic", () => { myTest.case("even numbers", assert => { assert(2).even(); assert(4).even(); }); }); ``` An extended test is itself extendable: chain `test.extend(...)` calls to compose assertions. Later `extend` calls win on overlapping keys, just as if you had merged the factories into a single `test.extend(...)`. ```js import test from "@rcompat/test"; const chained = test.extend((assert, subject) => ({ even() { assert(subject % 2 === 0).true(); return this; }, })).extend((assert, subject) => ({ odd() { assert(subject % 2 === 1).true(); return this; }, })); chained.case("parity", assert => { assert(2).even(); assert(3).odd(); }); ``` ## Examples ### Testing a utility function ```js // sum.ts export default (a, b) => a + b; // sum.spec.ts import test from "@rcompat/test"; import sum from "./sum.js"; test.case("sum adds two numbers", assert => { assert(sum(1, 2)).equals(3); assert(sum(-1, 1)).equals(0); assert(sum(0, 0)).equals(0); }); ``` ### Testing a class ```js import test from "@rcompat/test"; class Calculator { #value = 0; add(n) { this.#value += n; return this; } subtract(n) { this.#value -= n; return this; } get value() { return this.#value; } } test.case("calculator operations", assert => { const calc = new Calculator(); calc.add(10).subtract(3); assert(calc.value).equals(7); }); test.case("calculator is instance", assert => { assert(new Calculator()).instance(Calculator); }); ``` ### Testing error handling ```js import test from "@rcompat/test"; function divide(a, b) { if (b === 0) throw new Error("Division by zero"); return a / b; } test.case("divide throws on zero", assert => { assert(() => divide(10, 0)).throws("Division by zero"); }); test.case("divide works normally", assert => { assert(() => divide(10, 2)).tries(); assert(divide(10, 2)).equals(5); }); ``` ### Testing code that calls external APIs ```js import test from "@rcompat/test"; using openai = test.intercept("https://api.openai.com", setup => { setup.post("/v1/chat/completions", () => ({ choices: [{ message: { content: "Hello!" } }], })); }); test.case("generates a reply", async assert => { const reply = await myService.generateReply("hi"); assert(reply).equals("Hello!"); assert(openai.calls("/v1/chat/completions")).equals(1); }); ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | ----------- | | Node.js | Yes | | Deno | Yes | | Bun | Yes | | Browser | Import only | Module mocking is currently available only on Node.js. Test registration, assertions, spies, fetch interception, and dynamic imports work on Node, Deno, and Bun. Browser bundles can import the package and use `test.config`. Accessing any other root utility throws because test registration is unavailable. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/type # @rcompat/type This module provides TypeScript predicates, transformations, structural contracts, and common aliases for type-level programming. ## Installation ```bash npm install @rcompat/type ``` ```bash pnpm add @rcompat/type ``` ```bash yarn add @rcompat/type ``` ```bash bun add @rcompat/type ``` ## Usage ### Basic types ```ts import type { Dict, Maybe, Nullish, Primitive } from "@rcompat/type"; // Dict = Record const config: Dict = { host: "localhost", port: "3000" }; // Maybe = T | undefined function find(id: number): Maybe { return users.get(id); } // Nullish = null | undefined function isNullish(value: unknown): value is Nullish { return value == null; } // Primitive = bigint | boolean | null | number | string | symbol | undefined function isPrimitive(value: unknown): value is Primitive { return value !== Object(value); } ``` ### Type predicates ```ts import type { IsAny, IsNever, IsUnion, IsTuple, IsArray } from "@rcompat/type"; // check if type is `any` type A = IsAny; // true type B = IsAny; // false // check if type is `never` type C = IsNever; // true type D = IsNever; // false // check if type is a union type E = IsUnion; // true type F = IsUnion; // false // check if type is a tuple type G = IsTuple<[string, number]>; // true type H = IsTuple; // false // check if type is a non-tuple array type I = IsArray; // true type J = IsArray<[string]>; // false ``` ### Type transformations ```ts import type { Mutable, DeepMutable, Not, UnionToTuple, TupleToUnion, } from "@rcompat/type"; // remove readonly modifier type Writable = Mutable>; // { a: string } // recursively remove readonly type DeepWritable = DeepMutable< Readonly<{ nested: Readonly<{ value: number }> }> >; // { nested: { value: number } } // boolean negation type Yes = Not; // true type No = Not; // false // convert union to tuple type Tuple = UnionToTuple<"a" | "b" | "c">; // Contains "a", "b", and "c"; union ordering is compiler-dependent. // convert tuple to union type Union = TupleToUnion<["a", "b", "c"]>; // "a" | "b" | "c" ``` ### Function types ```ts import type { Newable, UnknownFunction } from "@rcompat/type"; // constructor type function createInstance(Ctor: Newable): T { return new Ctor(); } // generic function signature function wrap(fn: UnknownFunction) { return (...args: unknown[]) => fn(...args); } ``` ### JSON types ```ts import type { JSONValue, Serializable } from "@rcompat/type"; // valid JSON value const data: JSONValue = { name: "Bob", age: 30, active: true, tags: ["admin", "user"], }; // implement custom serialization class User implements Serializable { constructor(private id: number, private name: string) {} toJSON(): JSONValue { return { id: this.id, name: this.name }; } } ``` ### Async types ```ts import type { MaybePromise } from "@rcompat/type"; // value or Promise of value async function process(input: MaybePromise): Promise { const value = await input; return value.toUpperCase(); } process("hello"); // works process(Promise.resolve("hello")); // also works ``` ## Examples ### Type-safe event emitter ```ts import type { Dict, UnknownFunction } from "@rcompat/type"; type Events = Dict; class Emitter { #events: Partial = {}; on(event: K, handler: E[K][number]) { (this.#events[event] ??= [] as E[K]).push(handler); } } ``` ### Conditional type utilities ```ts import type { IsUnion, UnionToTuple } from "@rcompat/type"; type UnionLength = UnionToTuple["length"]; type A = UnionLength<"a" | "b" | "c">; // 3 type B = UnionLength; // 1 ``` ### JSON validation ```ts import type { JSONValue } from "@rcompat/type"; function parseJSON(text: string): JSONValue { return JSON.parse(text); } function stringify(value: JSONValue): string { return JSON.stringify(value); } ``` ### Optional undefined properties ```ts import type { UndefinedToOptional } from "@rcompat/type"; type Input = { required: string; optional: string | undefined; }; type Output = UndefinedToOptional; // { required: string; optional?: string } ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | ✓ | No configuration required — just import and use. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/webview # @rcompat/webview This module creates lightweight native desktop applications with web technologies, using WebKit on macOS and Linux and WebView2 on Windows. > **Note:** Node.js is unsupported; constructing a Webview there throws. ## Installation ### Linux system requirements The Linux x64 sidecar uses WebKitGTK 6.0, GTK 4, and libsoup 3. Install the runtime packages supplied by your distribution before starting a webview: ```bash # Arch Linux sudo pacman -S webkitgtk-6.0 # Debian and Ubuntu sudo apt install libgtk-4-1 libwebkitgtk-6.0-4 # Fedora sudo dnf install gtk4 webkitgtk6.0 ``` WebKitGTK 4.0, GTK 3, and libsoup 2 do not satisfy this requirement and must not be substituted with ABI symlinks. The package provides Linux x64 and arm64 sidecars. ```bash npm install @rcompat/webview ``` ```bash pnpm add @rcompat/webview ``` ```bash yarn add @rcompat/webview ``` ```bash bun add @rcompat/webview ``` ## Usage ### Basic webview ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform }); webview.navigate("https://example.com"); webview.run(); ``` ### Set HTML content directly ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform }); webview.html = `

Hello from Webview!

`; webview.run(); ``` ### Custom window size ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform }); webview.size = { width: 800, height: 600, hint: 0, // 0=none, 1=min, 2=max, 3=fixed }; webview.navigate("https://example.com"); webview.run(); ``` ### Debug mode ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; // enable developer tools const webview = new Webview({ platform, debug: true }); webview.navigate("https://example.com"); webview.run(); ``` ### Server with webview in worker Create a local server and open it in a webview using a worker for non-blocking operation: **worker.ts** ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform }); webview.navigate("http://localhost:8181"); webview.run(); ``` **app.ts** ```ts import http from "@rcompat/http"; const headers = { "Content-Type": "text/html" }; const html = `

Desktop App

GitHub `; http.serve(() => new Response(html, { headers }), { host: "localhost", port: 8181, }); // Bun new Worker("worker.ts"); // Deno new Worker(new URL("worker.ts", import.meta.url).href, { type: "module" }); ``` ## Platform selection Auto-detect the current platform: ```ts import platform from "@rcompat/webview/default"; ``` Or replace that import with exactly one explicit target: ```ts import platform from "@rcompat/webview/darwin-arm64"; // macOS ARM ``` ```ts import platform from "@rcompat/webview/darwin-x64"; // macOS Intel ``` ```ts import platform from "@rcompat/webview/linux-arm64"; // Linux ARM64 ``` ```ts import platform from "@rcompat/webview/linux-x64"; // Linux x64 ``` ```ts import platform from "@rcompat/webview/windows-x64"; // Windows x64 ``` Only the six platform paths shown above are exported. Platform selection is kept explicit so Bun and Deno compilers can include the selected sidecar. ## Compiling to Executable ### Bun ```bash bun build app.ts worker.ts --compile --minify ``` ### Deno ```bash deno compile --no-check --include worker.ts app.ts ``` ## Cross-Compilation Generate platform-specific builds for distribution: **build.ts** ```ts import fs from "@rcompat/fs"; import runtime from "@rcompat/runtime"; const prefix = "--platform="; const platform = runtime.args .find(argument => argument.startsWith(prefix)) ?.slice(prefix.length) ?? "default"; await fs.ref(import.meta.dirname).join("worker.ts").write(` import platform from "@rcompat/webview/${platform}"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform }); webview.navigate("http://localhost:8181"); webview.run(); `); ``` ### Build for Linux from macOS ```bash # Bun bun build.ts --platform=linux-x64 bun build app.ts worker.ts --compile --target=bun-linux-x64 --minify # Deno deno -A build.ts --platform=linux-x64 deno compile --no-check --include worker.ts --target=x86_64-unknown-linux-gnu app.ts ``` ## Examples ### Desktop app with graceful shutdown ```ts // app.ts import http from "@rcompat/http"; const html = `

My Desktop App

`; const server = await http.serve( () => new Response(html, { headers: { "Content-Type": "text/html" } }), { host: "localhost", port: 8181 } ); // Bun const worker = new Worker("worker.ts"); // Deno const worker = new Worker(new URL("worker.ts", import.meta.url).href, { type: "module", }); // graceful shutdown when webview closes worker.addEventListener("message", (event) => { if (event.data === "destroyed") { server.stop(); } }); ``` ### Static HTML app ```ts import platform from "@rcompat/webview/default"; import Webview from "@rcompat/webview"; const webview = new Webview({ platform, debug: true }); webview.size = { width: 400, height: 300, hint: 3 }; // Fixed size webview.html = `

Hello, Desktop!

`; webview.run(); ``` ## Supported Platforms | Platform | Architecture | Export | | -------- | ------------ | -------------- | | macOS | ARM64 | `darwin-arm64` | | macOS | x64 | `darwin-x64` | | Linux | ARM64 | `linux-arm64` | | Linux | x64 | `linux-x64` | | Windows | x64 | `windows-x64` | ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Bun | ✓ | | Deno | ✓ | | Node.js | Unsupported (constructor throws) | | Browser | Unsupported (constructor throws) | ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/packages/worker # @rcompat/worker This module provides portable module workers with the Web Worker event and messaging contract. ## Installation ```bash npm install @rcompat/worker ``` ```bash pnpm add @rcompat/worker ``` ```bash yarn add @rcompat/worker ``` ```bash bun add @rcompat/worker ``` ## Usage ```js import Worker from "@rcompat/worker"; const worker = new Worker(new URL("./worker.js", import.meta.url), { name: "example", }); worker.addEventListener("message", event => { console.log(event.data); }); worker.postMessage("hello"); ``` The package exposes the [`Worker`](/api/worker#worker-constructor) interface in browsers, Bun, Deno, and Node. Node workers are bootstrapped with `self`, `postMessage`, `onmessage`, and the standard event-target methods so the same module worker can run in every supported runtime. Workers are always ES modules, so the module mode can normally be omitted from the optional constructor options. Worker scripts should use the Web Worker messaging API rather than runtime-specific APIs such as Node's `parentPort`. --- Source: https://rcompat.repopack.app/packages/proby # proby This module provides a test runner that discovers test files in single repositories and monorepos. It can execute TypeScript package sources without a build step when they expose a custom source condition, and uses `@rcompat/test` for test definitions. ## Installation ```bash npm install proby @rcompat/test ``` ```bash pnpm add proby @rcompat/test ``` ```bash yarn add proby @rcompat/test ``` ```bash bun add proby @rcompat/test ``` ## Usage ### Running tests Run proby from your project root: ```bash npx proby ``` Run a single file: ```bash npx proby math.spec.ts ``` Run a single group within a file: ```bash npx proby math.spec.ts addition ``` When invoking Proby through Deno, grant the permissions required by the test runner and the tests. Proby preserves full permissions when it relaunches Deno: ```bash deno run -A node_modules/proby/lib/bin.js ``` ## How proby resolves source files Proby reads `compilerOptions.customConditions` from your `tsconfig.json` and relaunches itself with those conditions active before running tests. This lets Node resolve package `imports` and `exports` to your TypeScript source files instead of built JavaScript — no build step required. Use a condition scoped to your project to avoid conflicts when multiple monorepos share `node_modules`: ```json { "compilerOptions": { "customConditions": ["@myproject/source"] } } ``` Then expose matching entries in your packages: ```json { "imports": { "#*": { "@myproject/source": "./src/private/*.ts", "default": "./lib/private/*.js" } }, "exports": { ".": { "@myproject/source": "./src/public/index.ts", "default": "./lib/public/index.js" } } } ``` Because TypeScript reads the same `customConditions`, your editor's jump-to-source also lands on the `.ts` source file — not compiled output. The opt-in is per package and entirely additive. Packages without the condition fall back to built output as normal. ## Configuration Create `spec.config.ts` or `spec.config.js` in your project root. The preferred helper is part of the test-authoring API, so the configuration contract does not depend on Proby: ```ts import test from "@rcompat/test"; export default test.config({ monorepo: true, packages: "packages", include: ["src"], }); ``` A plain default-exported object is also valid. For type checking without the helper, use the erased `TestConfig` type: ```ts import type { TestConfig } from "@rcompat/test"; export default { monorepo: true, } satisfies TestConfig; ``` Proby searches the project root for `spec.config.ts`, `spec.config.js`, `proby.config.ts`, and `proby.config.js`. There is no silent filename precedence: more than one supported file is an error, and the diagnostic lists every match. With no configuration file, all defaults below apply. The `proby.config.*` names and the default helper exported by `proby` remain supported for existing projects. Migrate by renaming the file to `spec.config.*` and changing `import config from "proby"` to `import test from "@rcompat/test"`, then replace `config(...)` with `test.config(...)`. Configuration is imported by the active runtime. Current Node, Deno, and Bun can load the erasable TypeScript used in these examples. Use `spec.config.js` on a runtime that cannot load TypeScript directly; Proby does not transpile configuration files. ## Project structure ### Single repository ```text my-project/ ├── src/ │ ├── utils.ts │ ├── utils.spec.ts │ ├── math.ts │ └── math.spec.ts └── package.json ``` ### Monorepo ```text my-monorepo/ ├── packages/ │ ├── core/ │ │ └── src/ │ │ ├── index.ts │ │ └── index.spec.ts │ └── utils/ │ └── src/ │ ├── helpers.ts │ └── helpers.spec.ts └── package.json ``` ## Test file conventions - Files must end with `.spec.ts` or `.spec.js` - Files must be in one of the configured include directories - Use `@rcompat/test` to write tests - Use `test.group` to organize cases into named groups targetable by proby Within each configured include directory, discovered specs run sequentially in lexicographic order of their full paths with forward-slash separators, without locale-dependent comparison. Each spec's async `test.ended()` hooks finish before the next spec runs. Configured include directories retain their configured order. ## Static mock files Proby supports preloading sibling mock files before a spec file is evaluated. This allows module mocks to be registered before the spec's static imports are resolved. Pair files by matching the spec extension exactly: - `math.spec.ts` pairs with `math.mock.ts` - `math.spec.js` pairs with `math.mock.js` If a sibling mock file exists, proby loads it before the spec file. ```ts // math.mock.ts import test from "@rcompat/test"; test.mock("./math.ts", () => ({ add: (a: number, b: number) => 99, })); ``` ```ts // math.spec.ts import test from "@rcompat/test"; import { add } from "./math.ts"; test.case("uses the preloaded mock", assert => { assert(add(1, 2)).equals(99); }); ``` Static mocks are file-scoped — they do not leak into later spec files. ## Grouping tests Use `test.group` to cluster related cases. Groups can be targeted individually when running proby: ```ts import test from "@rcompat/test"; test.group("addition", () => { test.case("integers", assert => { assert(1 + 1).equals(2); }); }); test.group("multiplication", () => { test.case("integers", assert => { assert(2 * 3).equals(6); }); }); ``` ```bash npx proby math.spec.ts addition ``` ## Writing tests Create test files with `.spec.ts` or `.spec.js`: ```js import test from "@rcompat/test"; test.case("addition", assert => { assert(1 + 1).equals(2); assert(2 + 2).equals(4); }); test.case("multiplication", assert => { assert(2 * 3).equals(6); assert(4 * 5).equals(20); }); ``` ## Test output Proby displays colored output: - Green `o` for passing tests - Red `x` for failing tests ```text oooooxoo src/math.spec.ts division expected 5 actual 4 ``` ## npm scripts Add proby to your `package.json`: ```json { "scripts": { "test": "npx proby" } } ``` Then run: ```bash npm test ``` ## Examples ### Basic assertions ```ts import test from "@rcompat/test"; test.case("basic assertions", assert => { assert(value).equals(expected); assert(condition).true(); assert(condition).false(); assert(value).type(); assert(() => throwingFunction()).throws(); assert(() => safeFunction()).tries(); }); ``` ### Async tests ```js import test from "@rcompat/test"; test.case("async operations", async assert => { const result = await fetchData(); assert(result.status).equals(200); }); ``` ### Testing modules ```ts // src/calculator.ts export function add(a: number, b: number) { return a + b; } ``` ```ts // src/calculator.spec.ts import test from "@rcompat/test"; import { add } from "./calculator.js"; test.case("add function", assert => { assert(add(1, 2)).equals(3); assert(add(-1, 1)).equals(0); assert(add(0, 0)).equals(0); }); ``` ## Cross-Runtime Compatibility | Runtime | Supported | | ------- | --------- | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ | | Browser | Unsupported | Proby is a command-line test runner and does not run in browsers. Browser-safe test configuration is available separately through `@rcompat/test`. ## License MIT ## Contributing See [CONTRIBUTING.md](../../CONTRIBUTING.md) in the repository root. --- Source: https://rcompat.repopack.app/api/array # @rcompat/array API Utilities for comparing, inspecting, and normalizing arrays. Methods requiring array inputs validate them consistently with [`assert.array()`](/api/assert#assert-array). These utilities work in current browsers, Node, Deno, and Bun. ```ts import array from "@rcompat/array"; ``` ## array.difference Returns elements from the first array that the second does not include. Membership uses the same SameValueZero comparison as `Array.includes`. The input arrays are not modified. ```ts array.difference(a: unknown[], b: unknown[]): unknown[]; ``` **Example** ```ts array.difference([1, 2, 2, 3], [2]); // [1, 3] ``` ## array.empty Returns whether an array contains no elements. ```ts array.empty(array: unknown[]): boolean; ``` **Example** ```ts array.empty([]); // true array.empty([0]); // false ``` ## array.to Returns an array unchanged or wraps a non-array value in an array. ```ts array.to(value: T | T[]): T[]; ``` **Example** ```ts array.to("value"); // ["value"] const values = ["value"]; array.to(values) === values; // true ``` --- Source: https://rcompat.repopack.app/api/assert # @rcompat/assert API Runtime assertions that return their validated input. Each method throws its optional custom `Error`, or a coded default error, when validation fails. Successful calls return a narrowed value rather than using TypeScript's `asserts` return type. ```ts import assert from "@rcompat/assert"; import type { Code } from "@rcompat/assert"; ``` ## assert.bigint Requires a bigint value. ```ts assert.bigint(x: unknown, error?: Error): bigint; ``` **Example** ```ts assert.bigint(1n); // passes assert.bigint(1); // throws ``` ## assert.boolean Requires a boolean value. ```ts assert.boolean(x: unknown, error?: Error): boolean; ``` **Example** ```ts assert.boolean(false); // passes assert.boolean(0); // throws ``` ## assert.function Requires a callable value. ```ts api-types=eyJVbmtub3duRnVuY3Rpb24iOnsiaHJlZiI6Ii9hcGkvdHlwZSN1bmtub3duZnVuY3Rpb24iLCJ0aXRsZSI6IiguLi5wYXJhbXM6IGFueVtdKSA9PiB1bmtub3duIn19 assert.function(x: unknown, error?: Error): UnknownFunction; ``` **Example** ```ts assert.function(() => undefined); // passes assert.function({}); // throws ``` ## assert.number Requires a number value, including `NaN`. ```ts assert.number(x: unknown, error?: Error): number; ``` **Example** ```ts assert.number(NaN); // passes assert.number("1"); // throws ``` ## assert.string Requires a string value. ```ts assert.string(x: unknown, error?: Error): string; ``` **Example** ```ts assert.string(""); // passes assert.string(1); // throws ``` ## assert.symbol Requires a symbol value. ```ts assert.symbol(x: unknown, error?: Error): symbol; ``` **Example** ```ts assert.symbol(Symbol("id")); // passes assert.symbol("id"); // throws ``` ## assert.undefined Requires an `undefined` value. ```ts assert.undefined(x: unknown, error?: Error): undefined; ``` **Example** ```ts assert.undefined(undefined); // passes assert.undefined(null); // throws ``` ## assert.array Requires an array value. ```ts assert.array(x: unknown, error?: Error): unknown[]; ``` **Example** ```ts assert.array([]); // passes assert.array({}); // throws ``` ## assert.date Requires a `Date` value. ```ts assert.date(x: unknown, error?: Error): Date; ``` **Example** ```ts assert.date(new Date()); // passes assert.date(Date.now()); // throws ``` ## assert.dict Requires a plain object while preserving a narrower input type. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 assert.dict(x: T, error?: Error): T extends Dict ? T : Dict; ``` **Example** ```ts assert.dict({ name: "Ada" }); // passes assert.dict([]); // throws ``` ## assert.error Requires an `Error` value. ```ts assert.error(x: unknown, error?: Error): Error; ``` **Example** ```ts assert.error(new Error("failed")); // passes assert.error("failed"); // throws ``` ## assert.false Requires the literal value `false`. ```ts assert.false(x: unknown, error?: Error): false; ``` **Example** ```ts assert.false(false); // passes assert.false(true); // throws ``` ## assert.finite Requires a finite number or bigint. ```ts assert.finite(x: unknown, error?: Error): bigint | number; ``` **Example** ```ts assert.finite(42); // passes assert.finite(Infinity); // throws ``` ## assert.int Requires an integer number or bigint. ```ts assert.int(x: unknown, error?: Error): bigint | number; ``` **Example** ```ts assert.int(-1n); // passes assert.int(1.5); // throws ``` ## assert.map Requires a `Map` value. ```ts assert.map(x: unknown, error?: Error): Map; ``` **Example** ```ts assert.map(new Map()); // passes assert.map({}); // throws ``` ## assert.nan Requires the number value `NaN`. ```ts assert.nan(x: unknown, error?: Error): number; ``` **Example** ```ts assert.nan(NaN); // passes assert.nan(0); // throws ``` ## assert.newable Requires a value constructible with `new`. ```ts api-types=eyJOZXdhYmxlIjp7ImhyZWYiOiIvYXBpL3R5cGUjbmV3YWJsZSIsInRpdGxlIjoibmV3ICguLi5hcmdzOiBBKSA9PiBJIn19 assert.newable(x: unknown, error?: Error): Newable; ``` **Example** ```ts assert.newable(Date); // passes assert.newable(() => undefined); // throws ``` ## assert.null Requires the value `null`. ```ts assert.null(x: unknown, error?: Error): null; ``` **Example** ```ts assert.null(null); // passes assert.null(undefined); // throws ``` ## assert.nullish Requires `null` or `undefined`. ```ts api-types=eyJOdWxsaXNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjbnVsbGlzaCIsInRpdGxlIjoibnVsbCB8IHVuZGVmaW5lZCJ9fQ assert.nullish(x: unknown, error?: Error): Nullish; ``` **Example** ```ts assert.nullish(undefined); // passes assert.nullish(0); // throws ``` ## assert.object Requires a non-null object. ```ts assert.object(x: unknown, error?: Error): object; ``` **Example** ```ts assert.object({}); // passes assert.object(null); // throws ``` ## assert.promise Requires a `Promise` value. ```ts assert.promise(x: unknown, error?: Error): Promise; ``` **Example** ```ts assert.promise(Promise.resolve()); // passes assert.promise({}); // throws ``` ## assert.regexp Requires a regular expression. ```ts assert.regexp(x: unknown, error?: Error): RegExp; ``` **Example** ```ts assert.regexp(/value/); // passes assert.regexp("value"); // throws ``` ## assert.safeint Requires a number for which `Number.isSafeInteger` returns `true`. Safe integers are whole numbers from `Number.MIN_SAFE_INTEGER` (`-(2 ** 53 - 1)`) through `Number.MAX_SAFE_INTEGER` (`2 ** 53 - 1`), inclusive. `NaN`, infinities, fractional numbers, numeric strings, and `bigint` values are not safe integer numbers. ```ts assert.safeint(x: unknown, error?: Error): number; ``` **Example** ```ts assert.safeint(Number.MAX_SAFE_INTEGER); // passes assert.safeint(Number.MAX_SAFE_INTEGER + 1); // throws ``` ## assert.set Requires a `Set` value. ```ts assert.set(x: unknown, error?: Error): Set; ``` **Example** ```ts assert.set(new Set()); // passes assert.set([]); // throws ``` ## assert.true Requires the literal value `true`. ```ts assert.true(x: unknown, error?: Error): true; ``` **Example** ```ts assert.true(true); // passes assert.true(false); // throws ``` ## assert.uint Requires a non-negative integer number or bigint. ```ts assert.uint(x: unknown, error?: Error): bigint | number; ``` **Example** ```ts assert.uint(0); // passes assert.uint(-1); // throws ``` ## assert.url Requires a `URL` value. ```ts assert.url(x: unknown, error?: Error): URL; ``` **Example** ```ts assert.url(new URL("https://example.com")); // passes assert.url("https://example.com"); // throws ``` ## assert.empty Requires an empty string, collection, or object. ```ts assert.empty(x: T, error?: Error): T; ``` **Example** ```ts assert.empty(""); // passes assert.empty("value"); // throws ``` ## assert.nonempty Requires a nonempty value. ```ts assert.nonempty(x: T, error?: Error): T; ``` **Example** ```ts assert.nonempty("value"); // passes assert.nonempty(""); // throws ``` ## assert.shape Requires a plain object matching a property type descriptor. A descriptor value ending in `?` permits the property to be absent or `undefined`. Properties not named by the descriptor are ignored. ```ts api-types=eyJTaGFwZURlc2NyaXB0b3IiOnsiaHJlZiI6IiNzaGFwZWRlc2NyaXB0b3IiLCJ0aXRsZSI6IkEgbWFwIGZyb20gcHJvcGVydHkgbmFtZXMgdG8gcmVxdWlyZWQgb3IgYD9gLXN1ZmZpeGVkIG9wdGlvbmFsIHR5cGVzLiJ9fQ assert.shape(x: unknown, descriptor: ShapeDescriptor, error?: Error): T; ``` **Example** ```ts type User = { name: string; age?: number }; const input: unknown = { name: "Ada" }; const user = assert.shape(input, { name: "string", age: "number?", }); // passes assert.shape(input, { name: "number" }); // throws ``` ## assert.defined Requires a value other than `undefined`. ```ts assert.defined(x: T, error?: Error): Exclude; ``` **Example** ```ts assert.defined(null); // passes assert.defined(undefined); // throws ``` ## assert.instance Requires an instance of the given constructor. ```ts api-types=eyJOZXdhYmxlIjp7ImhyZWYiOiIvYXBpL3R5cGUjbmV3YWJsZSIsInRpdGxlIjoibmV3ICguLi5hcmdzOiBBKSA9PiBJIn19 assert.instance(x: unknown, N: T, error?: Error): InstanceType; ``` **Example** ```ts assert.instance(new Date(), Date); // passes assert.instance({}, Date); // throws ``` ## assert.uuid Requires a lowercase UUIDv4 string. ```ts assert.uuid(x: unknown, error?: Error): string; ``` **Example** ```ts assert.uuid("3b12f1df-5232-4e3c-8bf2-32c1e3b7c1a3"); // passes assert.uuid("not-a-uuid"); // throws ``` ## assert.Code Error-code values keyed by the corresponding `Code` string. ```ts api-types=eyJDb2RlIjp7ImhyZWYiOiIjY29kZSIsInRpdGxlIjoiQW4gZXJyb3IgY29kZSBlbWl0dGVkIGJ5IGEgYnVpbHQtaW4gYXNzZXJ0aW9uLiJ9fQ assert.Code: { [K in Code]: K }; ``` ## assert.every Modifier namespace that applies an assertion to every value in an array. Supports every top-level assertion except `shape`. Call the corresponding method on `assert.every`; for example, `assert.every.number(values)` applies `assert.number` to each value. Each method returns the original array after all elements pass validation and throws when an element fails. The `instance` method also accepts the constructor and optional custom error used by `assert.instance`. **Call forms** - `assert.every.(values)` for checks except `instance` and `shape` - `assert.every.instance(values, Constructor, error?)` for instances **Example** ```ts assert.every.number([1, 2, 3]); // passes assert.every.number([1, "2"]); // throws ``` ## assert.maybe Modifier namespace that permits `null` and `undefined` values. Supports every top-level assertion. Call the corresponding method on `assert.maybe`; for example, `assert.maybe.number(value)` returns `null` or `undefined` unchanged and applies `assert.number` to any other value. The `instance` and `shape` methods also accept the additional arguments and optional custom error used by their top-level counterparts. **Call forms** - `assert.maybe.(value)` for checks except `instance` and `shape` - `assert.maybe.instance(value, Constructor, error?)` for instances - `assert.maybe.shape(value, descriptor, error?)` for object shapes **Example** ```ts assert.maybe.safeint(null); // passes assert.maybe.safeint("8080"); // throws ``` ## Types ### Code An error code emitted by a built-in assertion. ```ts type Code = | "invalid_bigint" | "invalid_boolean" | "invalid_function" | "invalid_number" | "invalid_string" | "invalid_symbol" | "invalid_undefined" | "invalid_defined" | "invalid_array" | "invalid_date" | "invalid_dict" | "invalid_error" | "invalid_false" | "invalid_finite" | "invalid_int" | "invalid_map" | "invalid_nan" | "invalid_newable" | "invalid_null" | "invalid_nullish" | "invalid_object" | "invalid_promise" | "invalid_regexp" | "invalid_safeint" | "invalid_set" | "invalid_true" | "invalid_uint" | "invalid_url" | "invalid_uuid" | "invalid_empty" | "invalid_nonempty" | "invalid_instance" | "invalid_shape_dict" | "invalid_shape_property"; ``` ### ShapeDescriptor A map from property names to required or `?`-suffixed optional types. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 type ShapeDescriptor = Dict< `${"bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol"}${"?" | ""}` >; ``` --- Source: https://rcompat.repopack.app/api/cli # @rcompat/cli API Terminal styling, output, and interactive prompts for Node, Deno, and Bun. Browser bundles can import this package, but accessing any CLI utility throws because terminals and standard streams are not available through the browser entry. ```js import cli from "@rcompat/cli"; ``` The default CLI utility aggregate. ## cli.bg Background ANSI colors. ```ts cli.bg: { black(message: string): string; blue(message: string): string; cyan(message: string): string; gray(message: string): string; green(message: string): string; magenta(message: string): string; red(message: string): string; white(message: string): string; yellow(message: string): string; }; ``` ## cli.fg Foreground ANSI colors and text styles. ```ts cli.fg: { black(message: string): string; blue(message: string): string; bold(message: string): string; cyan(message: string): string; dim(message: string): string; gray(message: string): string; green(message: string): string; inverse(message: string): string; magenta(message: string): string; red(message: string): string; white(message: string): string; yellow(message: string): string; }; ``` ## cli.print() Writes messages to standard output, separated by spaces, without appending a newline. **Parameters** - `messages` — Text fragments to write. **Returns:** Whether the standard-output stream can accept more data. ```ts cli.print(...messages: string[]): boolean; ``` ## cli.prompt Interactive prompt and prompt-output utilities. ### Prompt methods #### cli.prompt.cancel() Writes a styled cancellation message and returns the cancellation symbol. **Parameters** - `message` — Message to write. **Returns:** The symbol recognized by `cli.prompt.isCancel`. ```ts api-types=eyJDYW5jZWxTeW1ib2wiOnsiaHJlZiI6IiNjYW5jZWxzeW1ib2wiLCJ0aXRsZSI6InN5bWJvbCJ9fQ cli.prompt.cancel(message?: string): CancelSymbol; ``` #### cli.prompt.confirm() Prompts for a yes-or-no response. **Parameters** - `args` — Message and optional initial response. **Returns:** The submitted boolean or the cancellation symbol. ```ts api-types=eyJDYW5jZWxTeW1ib2wiOnsiaHJlZiI6IiNjYW5jZWxzeW1ib2wiLCJ0aXRsZSI6InN5bWJvbCJ9LCJDb25maXJtT3B0aW9ucyI6eyJocmVmIjoiI2NvbmZpcm1vcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBgY2xpLnByb21wdC5jb25maXJtYC4ifX0 cli.prompt.confirm( args: ConfirmOptions, ): Promise; ``` #### cli.prompt.intro() Writes a styled introductory message when one is provided. **Parameters** - `message` — Message to write. ```ts cli.prompt.intro(message?: string): void; ``` #### cli.prompt.isCancel() Tests whether a prompt result is the cancellation symbol. **Parameters** - `value` — Prompt result to test. ```ts api-types=eyJDYW5jZWxTeW1ib2wiOnsiaHJlZiI6IiNjYW5jZWxzeW1ib2wiLCJ0aXRsZSI6InN5bWJvbCJ9fQ cli.prompt.isCancel(value: unknown): value is CancelSymbol; ``` #### cli.prompt.multiselect() Prompts for one or more comma-separated numbered options. **Type parameters** - `T` — Option value type. **Parameters** - `args` — Message, options, and initial option indexes. **Returns:** Selected values in input order, without duplicates. ```ts api-types=eyJNdWx0aXNlbGVjdE9wdGlvbnMiOnsiaHJlZiI6IiNtdWx0aXNlbGVjdG9wdGlvbnMiLCJ0aXRsZSI6Ik9wdGlvbnMgZm9yIGBjbGkucHJvbXB0Lm11bHRpc2VsZWN0YC4ifX0 cli.prompt.multiselect( args: MultiselectOptions, ): Promise; ``` #### cli.prompt.outro() Writes a styled completion message when one is provided. **Parameters** - `message` — Message to write. ```ts cli.prompt.outro(message?: string): void; ``` #### cli.prompt.readline() Reads one line from standard input. **Returns:** The line without its newline, or `null` on interruption or end-of-input. ```ts cli.prompt.readline(): Promise; ``` #### cli.prompt.select() Prompts for one numbered option. **Type parameters** - `T` — Option value type. **Parameters** - `args` — Message, options, and initial option index. **Returns:** The selected option value. End-of-input selects the initial option. ```ts api-types=eyJTZWxlY3RPcHRpb25zIjp7ImhyZWYiOiIjc2VsZWN0b3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyBmb3IgYGNsaS5wcm9tcHQuc2VsZWN0YC4ifX0 cli.prompt.select(args: SelectOptions): Promise; ``` **Example** ```ts const runtime = await cli.prompt.select({ message: "Choose a runtime", options: [ { label: "Node", value: "node" }, { label: "Deno", value: "deno" }, ], }); // runtime is "node" or "deno" ``` #### cli.prompt.spinner() Creates a terminal progress spinner. Non-interactive output uses plain start and stop messages. **Returns:** Controls for starting, updating, and stopping the spinner. ```ts api-types=eyJTcGlubmVyIjp7ImhyZWYiOiIjc3Bpbm5lciIsInRpdGxlIjoiQ29udHJvbHMgZm9yIGEgdGVybWluYWwgcHJvZ3Jlc3Mgc3Bpbm5lci4ifX0 cli.prompt.spinner(): Spinner; ``` #### cli.prompt.text() Prompts for text until validation succeeds or input is cancelled. **Parameters** - `args` — Message, initial value, and optional validator. **Returns:** The submitted text or the cancellation symbol. ```ts api-types=eyJDYW5jZWxTeW1ib2wiOnsiaHJlZiI6IiNjYW5jZWxzeW1ib2wiLCJ0aXRsZSI6InN5bWJvbCJ9LCJUZXh0T3B0aW9ucyI6eyJocmVmIjoiI3RleHRvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBgY2xpLnByb21wdC50ZXh0YC4ifX0 cli.prompt.text( args: TextOptions, ): Promise; ``` ## Supporting contracts These contracts describe the default aggregate but are not named root exports. ### CancelSymbol Symbol returned when a cancellable prompt is interrupted. ```ts type CancelSymbol = symbol; ``` ### ConfirmOptions Options for `cli.prompt.confirm`. ```ts type ConfirmOptions = { // Response used when the submitted line is empty. initial?: boolean; // Prompt message. message: string; }; ``` ### MultiselectOptions Options for `cli.prompt.multiselect`. ```ts api-types=eyJTZWxlY3RPcHRpb24iOnsiaHJlZiI6IiNzZWxlY3RvcHRpb24iLCJ0aXRsZSI6Ik9uZSBsYWJlbGVkIHNlbGVjdGlvbiB2YWx1ZS4ifX0 type MultiselectOptions = { // Zero-based option indexes selected by default. initial?: number[]; // Prompt message. message: string; // Available labeled values. options: Array>; }; ``` ### SelectOption One labeled selection value. ```ts type SelectOption = { // Label shown to the user. label: string; // Value returned when selected. value: T; }; ``` ### SelectOptions Options for `cli.prompt.select`. ```ts api-types=eyJTZWxlY3RPcHRpb24iOnsiaHJlZiI6IiNzZWxlY3RvcHRpb24iLCJ0aXRsZSI6Ik9uZSBsYWJlbGVkIHNlbGVjdGlvbiB2YWx1ZS4ifX0 type SelectOptions = { // Zero-based option selected on end-of-input. // Default: `0` initial?: number; // Prompt message. message: string; // Available labeled values. options: Array>; }; ``` ### Spinner Controls for a terminal progress spinner. ```ts interface Spinner { // Updates the message shown by an active spinner. message(text: string): void; // Starts the spinner with a message. start(text: string): void; // Stops the spinner and optionally replaces its final message. stop(text?: string): void; } ``` ### TextOptions Options for `cli.prompt.text`. ```ts type TextOptions = { // Value used when the submitted line is empty. initial?: string; // Prompt message. message: string; // Returns an error message to reject input, or nothing to accept it. validate?: (input: string) => Promise | string | void; }; ``` --- Source: https://rcompat.repopack.app/api/dict # @rcompat/dict API Typed utilities for string-keyed dictionaries. Inputs requiring plain objects are validated consistently with [`assert.dict()`](/api/assert#assert-dict). Methods return new dictionaries unless their documentation states that the input itself is returned. ```ts import dict from "@rcompat/dict"; ``` ## dict.empty Returns whether a dictionary has no own enumerable keys. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.empty(dict: Dict): boolean; ``` **Example** ```ts dict.empty({}); // true dict.empty({ ready: true }); // false ``` ## dict.entries Returns typed own enumerable key/value pairs. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.entries(dict: T): [keyof T, T[keyof T]][]; ``` **Example** ```ts dict.entries({ north: 1, south: 2 }); // [["north", 1], ["south", 2]] ``` ## dict.exclude Returns a copy without the selected keys. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.exclude( dict: T, excludes: readonly E[], ): Omit; ``` **Example** ```ts dict.exclude({ name: "Ada", password: "secret" }, ["password"]); // { name: "Ada" } ``` ## dict.filter Returns entries accepted by a key/value predicate. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.filter( dict: T, predicate: (key: keyof T, value: T[keyof T]) => boolean, ): Partial; ``` **Example** ```ts dict.filter({ a: 1, b: 2 }, (_key, value) => value > 1); // { b: 2 } ``` ## dict.flatMap Maps entries and omits entries whose mapper returns an empty tuple. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.flatMap( dict: T, mapper: (key: keyof T, value: T[keyof T]) => [string, unknown] | [], ): Dict; ``` **Example** ```ts dict.flatMap({ a: 1, b: 2 }, (key, value) => value > 1 ? [key.toUpperCase(), value * 10] : []); // { B: 20 } ``` ## dict.get Reads a value from a dot-separated nested path. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiR2V0UmVzdWx0VHlwZSI6eyJocmVmIjoiI2dldHJlc3VsdHR5cGUiLCJ0aXRsZSI6IlJlc29sdmVzIHRoZSB2YWx1ZSB0eXBlIGF0IGEgZG90LXNlcGFyYXRlZCBkaWN0aW9uYXJ5IHBhdGguIn19 dict.get( dict: T, path: P, ): GetResultType["result"]; ``` **Example** ```ts dict.get({ server: { port: 8080 } }, "server.port"); // 8080 ``` ## dict.has Checks for an own property and narrows the key to the dictionary keys. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.has(dict: D, key: PropertyKey): key is keyof D; ``` **Example** ```ts dict.has({ name: "Ada" }, "name"); // true dict.has({ name: "Ada" }, "age"); // false ``` ## dict.inflate Creates a nested dictionary from a path. Paths are always separated by dots. Callers migrating from another separator can normalize their path before calling `inflate()`. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiSW5mbGF0ZWQiOnsiaHJlZiI6IiNpbmZsYXRlZCIsInRpdGxlIjoiQnVpbGRzIGEgbmVzdGVkIGRpY3Rpb25hcnkgdHlwZSBmcm9tIGEgZG90LXNlcGFyYXRlZCBwYXRoLiJ9fQ dict.inflate

(path: P): Inflated; dict.inflate

(path: P, initial: T): Inflated; ``` **Example** ```ts dict.inflate("server.tls", { enabled: true }); // { server: { tls: { enabled: true } } } const path = "server/tls".replaceAll("/", "."); dict.inflate(path, { enabled: true }); // { server: { tls: { enabled: true } } } ``` ## dict.keys Returns typed own enumerable keys. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.keys(dict: T): (keyof T)[]; ``` **Example** ```ts dict.keys({ north: 1, south: 2 }); // ["north", "south"] ``` ## dict.new Creates a frozen, null-prototype copy of a plain object. ```ts dict.new(dict: T): T; ``` **Example** ```ts const config = dict.new({ mode: "production" }); Object.isFrozen(config); // true Object.getPrototypeOf(config); // null ``` ## dict.map Maps values while preserving keys. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.map( dict: T, mapper: (key: keyof T, value: T[keyof T]) => U, ): { [K in keyof T]: U }; ``` **Example** ```ts dict.map({ a: 1, b: 2 }, (_key, value) => value * 10); // { a: 10, b: 20 } ``` ## dict.mapKey Maps keys while preserving values. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.mapKey( dict: T, mapper: (key: keyof T, value: T[keyof T]) => string, ): Dict; ``` **Example** ```ts dict.mapKey({ north: 1, south: 2 }, key => key.toUpperCase()); // { NORTH: 1, SOUTH: 2 } ``` ## dict.override Recursively overlays one dictionary with another. Values recognized by [`is.dict()`](/api/is#is-dict) are merged recursively; other overriding values replace their base values. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.override(base: T, over: U): T & U; ``` **Example** ```ts dict.override( { server: { host: "localhost", port: 3000 } }, { server: { port: 8080 } }, ); // { server: { host: "localhost", port: 8080 } } ``` ## dict.toQueryString Joins string entries as unencoded `key=value` pairs. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.toQueryString(dict: Dict): string; ``` **Example** ```ts dict.toQueryString({ page: "1", sort: "name" }); // "page=1&sort=name" ``` ## dict.values Returns typed own enumerable values. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 dict.values(dict: T): T[keyof T][]; ``` **Example** ```ts dict.values({ north: 1, south: 2 }); // [1, 2] ``` ## Supporting contracts ### GetResultType Resolves the value type at a dot-separated dictionary path. **Type parameters** - `T` — Dictionary type to traverse. - `P` — Dot-separated path. - `D` — Internal recursion-depth counter. ```ts interface GetResultType { result: D["length"] extends 6 ? unknown : P extends `${infer P1}.${infer Rest}` ? P1 extends keyof T ? GetResultType, Rest, [...D, 0]>["result"] | (T[P1] & undefined) : undefined : P extends keyof T ? T[P] : undefined; } ``` ### Inflated Builds a nested dictionary type from a dot-separated path. **Type parameters** - `P` — Path to expand. - `T` — Leaf value type. ```ts type Inflated

= P extends `${infer P1}.${infer Rest}` ? { [K in P1]: Inflated } : { [K in P]: T }; ``` --- Source: https://rcompat.repopack.app/api/env # @rcompat/env API Read-only access to the merged runtime environment. Node and Bun use `process.env`; Deno uses `Deno.env`. The first matching dotenv file is layered over that native environment. Browser imports use an empty environment and never include server variables in client code. ```ts import env from "@rcompat/env"; ``` ## env.get Returns a required environment variable. **Parameters** - `key` — Environment variable name. **Throws:** `Error` when the variable is not defined. ```ts env.get(key: string): string; ``` ## env.try Returns an optional environment variable. **Parameters** - `key` — Environment variable name. **Returns:** The value, or `undefined` when it is not defined. ```ts env.try(key: string): string | undefined; ``` ## env.toJSON Returns a detached, mutable snapshot with a null prototype. **Returns:** All loaded environment variables as a new dictionary. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 env.toJSON(): Dict; ``` --- Source: https://rcompat.repopack.app/api/error # @rcompat/error API Utilities for creating structured errors with stable runtime contracts. Template and coded errors retain their original interpolation values. Symbol-based branding, detected consistently with [`is.branded()`](/api/is#is-branded), allows the supplied guards to recognize errors across package instances and JavaScript realms. ```ts import error from "@rcompat/error"; import type { CodeError, TemplateError } from "@rcompat/error"; ``` ## error.CodeError Structured template error carrying a stable string code. **Type parameters** - `Code` — String literal type of the error code. ```ts api-types=eyJUZW1wbGF0ZUVycm9yIjp7ImhyZWYiOiIjdGVtcGxhdGVlcnJvciIsInRpdGxlIjoiRXJyb3IgY3JlYXRlZCBmcm9tIGEgdGFnZ2VkIHRlbXBsYXRlIHdpdGggaXRzIHNvdXJjZSB2YWx1ZXMgcmV0YWluZWQuIn19 declare class CodeError extends TemplateError {} ``` ### CodeError constructor #### new error.CodeError() Creates a coded error from template segments and interpolation values. **Parameters** - `code` — Stable error code. - `strings` — Template string segments. - `params` — Interpolated template values. ```ts constructor(code: Code, strings: TemplateStringsArray, ...params: unknown[]) ``` ### CodeError static methods #### error.CodeError.is() Checks whether a value carries the global `CodeError` brand. **Parameters** - `value` — Value to inspect. ```ts api-types=eyJDb2RlRXJyb3IiOnsiaHJlZiI6IiNlcnJvci1jb2RlZXJyb3IiLCJ0aXRsZSI6IlN0cnVjdHVyZWQgdGVtcGxhdGUgZXJyb3IgY2FycnlpbmcgYSBzdGFibGUgc3RyaW5nIGNvZGUuIn19 error.CodeError.is(value: unknown): value is CodeError ``` #### error.CodeError.matches() Checks for a coded error and narrows it to one code. **Parameters** - `value` — Value to inspect. - `code` — Required error code. ```ts api-types=eyJDb2RlRXJyb3IiOnsiaHJlZiI6IiNlcnJvci1jb2RlZXJyb3IiLCJ0aXRsZSI6IlN0cnVjdHVyZWQgdGVtcGxhdGUgZXJyb3IgY2FycnlpbmcgYSBzdGFibGUgc3RyaW5nIGNvZGUuIn19 error.CodeError.matches( value: unknown, code: Code, ): value is CodeError ``` ### CodeError instance properties #### codedError.code Stable string code carried by this error. ```ts get code(): Code ``` ## error.coded Wraps template-error factories with their keys as stable error codes. **Type parameters** - `T` — Dictionary of named template-error factories. **Parameters** - `factories` — Factories to wrap. **Returns:** Factories with the same parameters that return coded errors. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiQ29kZUVycm9yIjp7ImhyZWYiOiIjZXJyb3ItY29kZWVycm9yIiwidGl0bGUiOiJTdHJ1Y3R1cmVkIHRlbXBsYXRlIGVycm9yIGNhcnJ5aW5nIGEgc3RhYmxlIHN0cmluZyBjb2RlLiJ9LCJFcnJvckZ1bmN0aW9uIjp7ImhyZWYiOiIjZXJyb3JmdW5jdGlvbiIsInRpdGxlIjoiKC4uLmFyZ3M6IGFueVtdKSA9PiBUZW1wbGF0ZUVycm9yIn19 error.coded>(factories: T): { [K in keyof T]: (...args: Parameters) => CodeError; }; ``` **Example** ```ts const E = error.coded({ missing: (name: string) => error.template`Missing ${name}`, }); const failure = E.missing("config.json"); failure.code; // "missing" failure.message; // "Missing config.json" ``` ## error.names Maps every own enumerable key of an object to its own name. **Type parameters** - `T` — Object whose keys become names. **Parameters** - `object` — Object supplying the keys. **Returns:** A typed key-to-name object. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 error.names(object: T): { [K in keyof T]: K }; ``` ## error.template Creates a structured error from a tagged template. **Parameters** - `strings` — Template string segments supplied by the tag call. - `params` — Interpolated template values. **Returns:** An error retaining the segments and values. ```ts api-types=eyJUZW1wbGF0ZUVycm9yIjp7ImhyZWYiOiIjdGVtcGxhdGVlcnJvciIsInRpdGxlIjoiRXJyb3IgY3JlYXRlZCBmcm9tIGEgdGFnZ2VkIHRlbXBsYXRlIHdpdGggaXRzIHNvdXJjZSB2YWx1ZXMgcmV0YWluZWQuIn19 error.template( strings: TemplateStringsArray, ...params: unknown[] ): TemplateError; ``` ## TemplateError Error created from a tagged template with its source values retained. Import this class as a type. Create instances with `error.template`. ```ts declare class TemplateError extends Error {} ``` ### TemplateError instance properties #### templateError.strings Template string segments from the original tagged-template call. ```ts get strings(): TemplateStringsArray ``` #### templateError.params Interpolated values from the original tagged-template call. ```ts get params(): unknown[] ``` ## Supporting contracts ### ErrorFunction Factory that creates a structured template error. ```ts api-types=eyJUZW1wbGF0ZUVycm9yIjp7ImhyZWYiOiIjdGVtcGxhdGVlcnJvciIsInRpdGxlIjoiRXJyb3IgY3JlYXRlZCBmcm9tIGEgdGFnZ2VkIHRlbXBsYXRlIHdpdGggaXRzIHNvdXJjZSB2YWx1ZXMgcmV0YWluZWQuIn19 type ErrorFunction = (...args: any[]) => TemplateError; ``` ### Coded Converts template-error factories to coded-error factories. **Type parameters** - `T` — Dictionary of template-error factories. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiQ29kZUVycm9yIjp7ImhyZWYiOiIjZXJyb3ItY29kZWVycm9yIiwidGl0bGUiOiJTdHJ1Y3R1cmVkIHRlbXBsYXRlIGVycm9yIGNhcnJ5aW5nIGEgc3RhYmxlIHN0cmluZyBjb2RlLiJ9LCJFcnJvckZ1bmN0aW9uIjp7ImhyZWYiOiIjZXJyb3JmdW5jdGlvbiIsInRpdGxlIjoiKC4uLmFyZ3M6IGFueVtdKSA9PiBUZW1wbGF0ZUVycm9yIn19 type Coded> = { [K in keyof T]: (...args: Parameters) => CodeError; }; ``` --- Source: https://rcompat.repopack.app/api/fn # @rcompat/fn API Utilities for predicates, identity transforms, and asynchronous callbacks. These dependency-free utilities work in current browsers, Node, Deno, and Bun. ```ts import fn from "@rcompat/fn"; ``` ## fn.defined Checks that a value is not `undefined` and narrows its type. **Type parameters** - `T` — Input value type. **Parameters** - `value` — Value to inspect. ```ts fn.defined(value: T): value is Exclude; ``` ## fn.identity Returns a value unchanged while preserving its type and identity. **Type parameters** - `T` — Input value type. **Parameters** - `value` — Value to return. ```ts fn.identity(value: T): T; ``` ## fn.async Concurrent asynchronous collection operations. ```ts api-types=eyJBc3luY1V0aWxpdGllcyI6eyJocmVmIjoiI2FzeW5jdXRpbGl0aWVzIiwidGl0bGUiOiJDb25jdXJyZW50IGFzeW5jaHJvbm91cyBjb2xsZWN0aW9uIG9wZXJhdGlvbnMuIn19 fn.async: AsyncUtilities; ``` ### Async methods #### fn.async.map() Maps all array elements concurrently and preserves their result order. Without options, the mapper is invoked through `Array.map` and all returned promises are awaited together with `Promise.all`. A concurrency limit bounds simultaneously running callbacks. Results always retain input order. Rejection or cancellation stops new callbacks from starting. Cancellation rejects promptly, but callbacks already running must observe the supplied signal themselves if they need to stop their own work. `concurrency`, when supplied, must be a finite positive integer. Empty arrays resolve to `[]`, except that an already-aborted signal rejects before any callback starts. **Type parameters** - `T` — Input element type. - `U` — Resolved output element type. **Parameters** - `array` — Array to map. - `mapper` — Asynchronous mapping callback. - `options` — Concurrency and cancellation controls. **Returns:** A promise for mapped results in input order. **Throws:** A `RangeError` when `concurrency` is invalid, or the signal's reason when cancellation occurs. ```ts api-types=eyJBc3luY01hcHBlciI6eyJocmVmIjoiI2FzeW5jbWFwcGVyIiwidGl0bGUiOiJDYWxsYmFjayB1c2VkIGJ5IGBmbi5hc3luYy5tYXBgLiJ9LCJBc3luY01hcE9wdGlvbnMiOnsiaHJlZiI6IiNhc3luY21hcG9wdGlvbnMiLCJ0aXRsZSI6Ik9wdGlvbnMgZm9yIGBmbi5hc3luYy5tYXBgLiJ9fQ fn.async.map( array: T[], mapper: AsyncMapper, options?: AsyncMapOptions, ): Promise; ``` **Example** ```ts await fn.async.map([1, 2], async value => value * 2); // [2, 4] ``` ## Supporting contracts ### AsyncUtilities Concurrent asynchronous collection operations. ```ts api-types=eyJBc3luY01hcHBlciI6eyJocmVmIjoiI2FzeW5jbWFwcGVyIiwidGl0bGUiOiJDYWxsYmFjayB1c2VkIGJ5IGBmbi5hc3luYy5tYXBgLiJ9LCJBc3luY01hcE9wdGlvbnMiOnsiaHJlZiI6IiNhc3luY21hcG9wdGlvbnMiLCJ0aXRsZSI6Ik9wdGlvbnMgZm9yIGBmbi5hc3luYy5tYXBgLiJ9fQ interface AsyncUtilities { // Maps all array elements concurrently and preserves their result order. map( array: T[], mapper: AsyncMapper, options?: AsyncMapOptions, ): Promise; } ``` ### AsyncMapper Callback used by `fn.async.map`. **Type parameters** - `T` — Input element type. - `U` — Resolved output element type. **Parameters** - `value` — Current array element. - `index` — Current zero-based index. - `array` — Array being mapped. **Returns:** A promise for the mapped value. ```ts interface AsyncMapper { (value: T, index: number, array: T[]): Promise; } ``` ### AsyncMapOptions Options for `fn.async.map`. ```ts interface AsyncMapOptions { // Maximum number of mapper callbacks running at once. concurrency?: number; // Cancels scheduling and rejects the map operation. signal?: AbortSignal; } ``` --- Source: https://rcompat.repopack.app/api/fs # @rcompat/fs API Portable filesystem operations and `FileRef` construction. Node, Deno, and Bun use native filesystem implementations. Browser bundles are safe to import: reference construction and lexical operations work, while disk operations throw when called. ```ts import fs from "@rcompat/fs"; import type { DirectoryOptions, FileInfo, FileRef, FileType, Filter, ListOptions, GlobOptions, LinkOptions, NamedStreamable, Path, RemoveOptions, SpoolOptions, SpoolSnapshot, Streamable, WritableInput, } from "@rcompat/fs"; ``` ## fs.streamable Protocol key for objects that provide a web `ReadableStream`. Registered globally as `Symbol.for("std:symbol/stream")`, preserving identity across runtimes, separately loaded copies, and the legacy `@rcompat/symbol.stream` export. ```ts fs.streamable: unique symbol; ``` ## fs.ref Creates a [FileRef](#fileref) for a filesystem path. **Parameters** - `path` — A native path, file URL, or existing reference. **Returns:** A `FileRef` preserving the supplied native path spelling. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.ref(path: Path): FileRef; ``` **Example** ```ts const config = fs.ref("config.json"); await config.writeJSON({ enabled: true }); await config.json(); // { enabled: true } ``` ## fs.isRef Checks whether a value is a compatible `FileRef`. **Parameters** - `value` — The value to inspect. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ fs.isRef(value: unknown): value is FileRef; ``` ## fs.isStream Checks whether a value can provide a readable stream. **Parameters** - `value` — The value to inspect. ```ts api-types=eyJTdHJlYW1hYmxlIjp7ImhyZWYiOiIjc3RyZWFtYWJsZSIsInRpdGxlIjoiQSB2YWx1ZSB0aGF0IGNhbiBwcm92aWRlIGEgd2ViIGBSZWFkYWJsZVN0cmVhbWAuIn19 fs.isStream(value: unknown): value is Streamable; ``` ## fs.isNamedStream Checks whether a streamable value also has a name. **Parameters** - `value` — The value to inspect. ```ts api-types=eyJOYW1lZFN0cmVhbWFibGUiOnsiaHJlZiI6IiNuYW1lZHN0cmVhbWFibGUiLCJ0aXRsZSI6IkEgc3RyZWFtYWJsZSB2YWx1ZSB3aXRoIGEgZmlsZW5hbWUgb3Igb3RoZXIgZGlzcGxheSBuYW1lLiJ9fQ fs.isNamedStream(value: unknown): value is NamedStreamable; ``` ## fs.cwd Returns the current working directory as an absolute reference. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ fs.cwd(): FileRef; ``` ## fs.createDirectory Creates a directory. **Parameters** - `path` — Directory path to create. - `options` — Directory creation options. **Default:** `options.recursive` is `true`. ```ts api-types=eyJEaXJlY3RvcnlPcHRpb25zIjp7ImhyZWYiOiIjZGlyZWN0b3J5b3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyBmb3IgY3JlYXRpbmcgYSBkaXJlY3RvcnkuIn0sIlBhdGgiOnsiaHJlZiI6IiNwYXRoIiwidGl0bGUiOiJGaWxlUmVmIHwgVVJMIHwgc3RyaW5nIn19 fs.createDirectory(path: Path, options?: DirectoryOptions): Promise; ``` ## fs.createFile Creates an empty file exclusively, without creating parents. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.createFile(path: Path): Promise; ``` ## fs.createLink Creates a symbolic link at `linkPath`, storing `target`. ```ts api-types=eyJMaW5rT3B0aW9ucyI6eyJocmVmIjoiI2xpbmtvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBjcmVhdGluZyBhIHN5bWJvbGljIGxpbmsuIn0sIlBhdGgiOnsiaHJlZiI6IiNwYXRoIiwidGl0bGUiOiJGaWxlUmVmIHwgVVJMIHwgc3RyaW5nIn19 fs.createLink( linkPath: Path, target: Exclude, options?: LinkOptions, ): Promise; ``` ## fs.resolve Resolves a path from the current working directory. **Parameters** - `path` — Path to resolve, or the current directory when omitted. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.resolve(path?: Path): FileRef; ``` ## fs.list Lists immediate or recursive directory entries. **Parameters** - `path` — Directory to list. - `options` — Recursion and filtering options. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.list(path: Path, options?: ListOptions): Promise; ``` ## fs.files Lists file entries in a directory. **Parameters** - `path` — Directory to list. - `options` — Recursion and filtering options. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.files(path: Path, options?: ListOptions): Promise; ``` ## fs.dirs Lists directory entries in a directory. **Parameters** - `path` — Directory to list. - `options` — Recursion and filtering options. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.dirs(path: Path, options?: ListOptions): Promise; ``` ## fs.glob Lazily yields files matching a portable relative glob pattern. Supports `*`, `?`, `**` path segments, and bracket classes. Brace expansion and extglobs are not supported. `/` is always the pattern separator. Wildcards do not match a leading dot in a path segment unless that segment starts with `.`. Symbolic links are not followed or yielded. Results are absolute references beneath the resolved `cwd` and retain the runtime's native directory iteration order. Missing or non-directory roots produce no results; other filesystem errors reject iteration. **Parameters** - `pattern` — Relative portable glob pattern. - `options` — Root directory and cancellation options. **Throws:** A `SyntaxError` for malformed or unsupported patterns. Iteration also rejects on cancellation or filesystem errors other than a missing or non-directory root. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJHbG9iT3B0aW9ucyI6eyJocmVmIjoiI2dsb2JvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsYXp5IGZpbGVzeXN0ZW0gZ2xvYiBzY2FubmluZy4ifX0 fs.glob(pattern: string, options?: GlobOptions): AsyncIterable; ``` ## fs.exists Checks whether a path exists. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.exists(path: Path): Promise; ``` ## fs.empty Checks whether a file or directory is empty. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.empty(path: Path): Promise; ``` ## fs.arrayBuffer Reads a file into an array buffer. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.arrayBuffer(path: Path): Promise; ``` ## fs.bytes Reads a file into an unsigned byte array. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.bytes(path: Path): Promise; ``` ## fs.text Reads a UTF-8 text file. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.text(path: Path): Promise; ``` ## fs.json Reads and parses a JSON file. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.json(path: Path): Promise; ``` ## fs.stream Returns a readable stream for a path or streamable value. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9LCJTdHJlYW1hYmxlIjp7ImhyZWYiOiIjc3RyZWFtYWJsZSIsInRpdGxlIjoiQSB2YWx1ZSB0aGF0IGNhbiBwcm92aWRlIGEgd2ViIGBSZWFkYWJsZVN0cmVhbWAuIn19 fs.stream(target: Path | Streamable): ReadableStream; ``` ## fs.write Writes text, bytes, blobs, responses, or readable streams to a path. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9LCJXcml0YWJsZUlucHV0Ijp7ImhyZWYiOiIjd3JpdGFibGVpbnB1dCIsInRpdGxlIjoiQXJyYXlCdWZmZXIgfCBVaW50OEFycmF5IHwgQmxvYiB8IFJlYWRhYmxlU3RyZWFtIHwgUmVzcG9uc2UgfCBzdHJpbmcifX0 fs.write(path: Path, value: WritableInput): Promise; ``` ## fs.spool Copies a byte stream to a private disposable file while incrementally computing its SHA-256 digest. This operation uses backpressure and never buffers the complete input. It resolves only after source EOF, completed file writes, digest finalization, and optional `expectedDigest` verification. The returned snapshot reads the saved bytes rather than the original source. `spool()` takes ownership of `source` while it runs. Abort, source or file failure, digest-finalization failure, and digest mismatch close resources, delete the partial file, and reject without returning a snapshot. Without `expectedDigest`, the returned digest is computed but not externally verified. Supply a trusted expected value before using this operation to gate delivery of an artifact. The caller owns the result. Its one-shot stream removes the backing file after EOF or cancellation. Call `dispose()` if no consumer receives the stream, or to terminate an active read. Do not dispose immediately after constructing a streaming `Response`; allow its body to finish or be cancelled by the HTTP host. An abandoned, uncancelled body can retain its snapshot like any other open stream. Browser bundles remain safe to import, but calling this disk-backed operation in a browser throws a clear unavailable-filesystem error. **Parameters** - `source` — Byte stream to consume exactly once. - `options` — Digest verification and spooling cancellation options. **Throws:** On invalid options, abort, source or file I/O failure, digest mismatch, digest finalization failure, or unsupported runtime. ```ts api-types=eyJTcG9vbE9wdGlvbnMiOnsiaHJlZiI6IiNzcG9vbG9wdGlvbnMiLCJ0aXRsZSI6Ik9wdGlvbnMgZm9yIGNyZWF0aW5nIGEgZGlzcG9zYWJsZSBzdHJlYW1lZCBmaWxlIHNuYXBzaG90LiJ9LCJTcG9vbFNuYXBzaG90Ijp7ImhyZWYiOiIjc3Bvb2xzbmFwc2hvdCIsInRpdGxlIjoiQW4gb3duZWQsIGRpc3Bvc2FibGUgc25hcHNob3QgY3JlYXRlZCBieSBgZnMuc3Bvb2woKWAuIn19 fs.spool( source: ReadableStream, options?: SpoolOptions, ): Promise; ``` **Example** ```ts const snapshot = await fs.spool(response.body!, { expectedDigest: trustedDigest, }); const verified = new Response(snapshot.stream(), { headers: { "content-length": String(snapshot.size) }, }); ``` ## fs.writeJSON Writes a value as indented JSON. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.writeJSON(path: Path, value: JSONValue): Promise; ``` ## fs.size Returns a file's size in bytes. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.size(path: Path): Promise; ``` ## fs.webpath Converts a path to forward-slash separators. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.webpath(path: Path): string; ``` ## fs.join Joins path segments into a new reference. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.join(path: Path, ...paths: Exclude[]): FileRef; ``` ## fs.normalize Lexically normalizes a path without accessing the filesystem. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.normalize(path: Path): FileRef; ``` ## fs.isAbsolute Checks whether a path is absolute in native syntax. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.isAbsolute(path: Path): boolean; ``` ## fs.relativeTo Returns a portable lexical path from `base` to `path`. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.relativeTo(path: Path, base: Path): string; ``` ## fs.discover Walks upward until a directory containing a filename is found. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ fs.discover(path: Path, filename: string): Promise; ``` ## fs.type Returns the filesystem entry type, or `null` when it is missing. ```ts api-types=eyJGaWxlVHlwZSI6eyJocmVmIjoiI2ZpbGV0eXBlIiwidGl0bGUiOiJcImRpcmVjdG9yeVwiIHwgXCJmaWxlXCIgfCBcImxpbmtcIiB8IG51bGwifSwiUGF0aCI6eyJocmVmIjoiI3BhdGgiLCJ0aXRsZSI6IkZpbGVSZWYgfCBVUkwgfCBzdHJpbmcifX0 fs.type(path: Path): Promise; ``` ## Types ## DirectoryOptions Options for creating a directory. ```ts interface DirectoryOptions { // Create missing parent directories. // Default: `true` recursive?: boolean; } ``` ## FileInfo Information supplied to directory-entry filters. This closed data shape remains an object type alias so it is assignable to consumers accepting `Record`. ```ts type FileInfo = { // Native filesystem path for the entry. path: string; // Final path component including extensions. name: string; // Last extension including its leading dot. extension: string; // All extensions beginning at the first dot. fullExtension: string; // Kind of filesystem entry. type: "file" | "directory" | "link"; }; ``` ## FileRef A pathlib-inspired reference to a file or directory. Construct references through `fs.ref()` when possible. Methods perform filesystem work only when called; creating a reference does not access disk. ```ts declare class FileRef {} ``` ### Constructor #### new FileRef() Creates a reference without accessing the filesystem. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ constructor(path: Path) ``` ### Static methods #### FileRef.is() Checks whether a value carries the compatible `FileRef` brand. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ static is(x: unknown): x is FileRef ``` ### Instance properties #### file.path The native path spelling used to create this reference. ```ts get path(): string ``` #### file.name The final path component including its extension. ```ts get name(): string ``` #### file.base The final path component without its last extension. ```ts get base(): string ``` #### file.extension The last filename extension including its leading dot. ```ts get extension(): string ``` #### file.fullExtension All filename extensions beginning at the first dot. ```ts get fullExtension(): string ``` #### file.directory A reference to the parent directory. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ get directory(): FileRef ``` #### file.core The final path component without any extension. ```ts get core(): string ``` ### Instance methods #### file.join() Joins relative segments without lexical normalization. Absolute paths, drive-qualified operands and URLs are not join operands. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ join(...paths: Exclude[]): FileRef ``` #### file.normalize() Explicitly normalizes `.` and `..` into a new reference. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ normalize(): FileRef ``` #### file.isAbsolute() Checks whether this reference has an absolute native path. ```ts isAbsolute(): boolean ``` #### file.relativeTo() Returns a `/`-separated lexical path from `base` to this reference. Returns `"."` for the same location and rejects incompatible roots. This is not a containment or filesystem-identity check. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIjcGF0aCIsInRpdGxlIjoiRmlsZVJlZiB8IFVSTCB8IHN0cmluZyJ9fQ relativeTo(base: Path): string ``` #### file.webpath() Converts native separators to forward slashes. ```ts webpath(): string ``` #### file.toURL() Converts this filesystem path to a native `file:` URL. Relative paths are resolved from the current working directory according to the running host's `pathToFileURL` semantics. ```ts toURL(): URL ``` #### file.append() Appends text directly to the path. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ append(suffix: string): FileRef ``` #### file.bare() Removes the final extension and optionally appends text. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ bare(append?: string): FileRef ``` #### file.text() Reads the file as UTF-8 text. ```ts text(): Promise ``` #### file.json() Reads and parses the file as JSON. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9fQ json(): Promise ``` #### file.bytes() Reads the file as bytes. ```ts bytes(): Promise ``` #### file.arrayBuffer() Reads the file into an array buffer. ```ts arrayBuffer(): Promise ``` #### file.stream() Opens a readable byte stream for the file. Wrap the result in a `Response` and call `response.text()` to decode UTF-8 text. ```ts stream(): ReadableStream ``` #### file.size() Returns the file size in bytes. ```ts size(): Promise ``` #### file.write() Writes supported text, binary, blob, response, or stream input. ```ts api-types=eyJXcml0YWJsZUlucHV0Ijp7ImhyZWYiOiIjd3JpdGFibGVpbnB1dCIsInRpdGxlIjoiQXJyYXlCdWZmZXIgfCBVaW50OEFycmF5IHwgQmxvYiB8IFJlYWRhYmxlU3RyZWFtIHwgUmVzcG9uc2UgfCBzdHJpbmcifX0 write(input: WritableInput): Promise ``` #### file.chmod() Sets POSIX permission bits on an existing regular file. ```ts chmod(mode: number): Promise ``` #### file.writeJSON() Writes a value as indented JSON. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9fQ writeJSON(input: JSONValue): Promise ``` #### file.exists() Checks whether the referenced path exists. ```ts exists(): Promise ``` #### file.type() Returns the entry type, or `null` when the path is missing. ```ts api-types=eyJGaWxlVHlwZSI6eyJocmVmIjoiI2ZpbGV0eXBlIiwidGl0bGUiOiJcImRpcmVjdG9yeVwiIHwgXCJmaWxlXCIgfCBcImxpbmtcIiB8IG51bGwifX0 type(): Promise ``` #### file.modified() Returns the modification time as Unix milliseconds. ```ts modified(): Promise ``` #### file.empty() Checks whether a file has zero bytes or a directory has no entries. ```ts empty(): Promise ``` #### file.list() Lists immediate or recursive directory entries. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9fQ list(options?: ListOptions): Promise ``` #### file.files() Lists only file entries. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9fQ files(options?: ListOptions): Promise ``` #### file.dirs() Lists only directory entries. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJMaXN0T3B0aW9ucyI6eyJocmVmIjoiI2xpc3RvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBsaXN0aW5nIGRpcmVjdG9yeSBlbnRyaWVzLiJ9fQ dirs(options?: ListOptions): Promise ``` #### file.createDirectory() Creates this directory. **Default:** `options.recursive` is `true`. ```ts api-types=eyJEaXJlY3RvcnlPcHRpb25zIjp7ImhyZWYiOiIjZGlyZWN0b3J5b3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyBmb3IgY3JlYXRpbmcgYSBkaXJlY3RvcnkuIn19 createDirectory(options?: DirectoryOptions): Promise ``` #### file.createFile() Exclusively creates an empty file, without creating parents. ```ts createFile(): Promise ``` #### file.createLink() Creates a symbolic link at this reference, storing `target` unchanged. A relative target is interpreted from the link's directory when followed. Existing destinations and missing parents fail; dangling targets are valid. ```ts api-types=eyJMaW5rT3B0aW9ucyI6eyJocmVmIjoiI2xpbmtvcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBjcmVhdGluZyBhIHN5bWJvbGljIGxpbmsuIn0sIlBhdGgiOnsiaHJlZiI6IiNwYXRoIiwidGl0bGUiOiJGaWxlUmVmIHwgVVJMIHwgc3RyaW5nIn19 createLink( target: Exclude, options?: LinkOptions, ): Promise ``` #### file.remove() Removes this path. **Default:** Missing paths do not fail unless `options.fail` is `true`. ```ts api-types=eyJSZW1vdmVPcHRpb25zIjp7ImhyZWYiOiIjcmVtb3Zlb3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyBmb3IgcmVtb3ZpbmcgYSBmaWxlc3lzdGVtIGVudHJ5LiJ9fQ remove(options?: RemoveOptions): Promise ``` #### file.copy() Copies this file or directory to another reference. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9LCJGaWx0ZXIiOnsiaHJlZiI6IiNmaWx0ZXIiLCJ0aXRsZSI6IihpbmZvOiBGaWxlSW5mbykgPT4gTWF5YmVQcm9taXNlPGJvb2xlYW4-In19 copy(to: FileRef, filter?: Filter): Promise ``` #### file.hash() Hashes the file contents. **Parameters** - `algorithm` — A Web Crypto digest algorithm. **Default:** `"SHA-256"` ```ts hash(algorithm?: string): Promise ``` #### file.import() Dynamically imports the file, optionally returning one named export. ```ts import(name?: string): Promise ``` #### file.discover() Walks upward to find a directory containing a filename. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ discover(filename: string): Promise ``` #### file.sibling() Returns a named reference in the same directory. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ sibling(name: string): FileRef ``` #### file.or() Returns this reference when it exists, otherwise a fallback value. ```ts or(fallback: () => T): Promise ``` #### file.toString() Returns the normalized path. ```ts toString(): string ``` ### Protocol members #### file\[Symbol.replace\]() Replaces this reference's string value inside another string. ```ts api-types=eyJTdHJpbmdSZXBsYWNlciI6eyJocmVmIjoiL2FwaS90eXBlI3N0cmluZ3JlcGxhY2VyIiwidGl0bGUiOiIoKHN1YnN0cmluZzogc3RyaW5nLCAuLi5wYXJhbXM6IGFueVtdKSA9PiBzdHJpbmcpIn19 [Symbol.replace]( string: string, replacement: string | StringReplacer, ): string ``` #### file\[fs.streamable\]() Returns the file's stream through [`fs.streamable`](/api/fs#fs-streamable). ```ts [fs.streamable](): ReadableStream ``` #### file\[util.inspect.custom\]() Formats the reference for Node-compatible object inspection. ```ts [util.inspect.custom](): string ``` #### file.Name protocol property The stable class name used by shared protocols. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ get Name(): "FileRef" ``` ## FileType The recognized kind of a filesystem entry, or `null` when it is missing. ```ts type FileType = "directory" | "file" | "link" | null; ``` ## Filter Selects directory entries synchronously or asynchronously. **Parameters** - `info` — Information about the candidate entry. ```ts api-types=eyJNYXliZVByb21pc2UiOnsiaHJlZiI6Ii9hcGkvdHlwZSNtYXliZXByb21pc2UiLCJ0aXRsZSI6IlByb21pc2U8VD4gfCBUIn0sIkZpbGVJbmZvIjp7ImhyZWYiOiIjZmlsZWluZm8iLCJ0aXRsZSI6IkluZm9ybWF0aW9uIHN1cHBsaWVkIHRvIGRpcmVjdG9yeS1lbnRyeSBmaWx0ZXJzLiJ9fQ type Filter = (info: FileInfo) => MaybePromise; ``` ## ListOptions Options for listing directory entries. This remains an object type alias so options are assignable to broad `Record` consumers. Consumers can still extend the shape through an interface or intersection. ```ts api-types=eyJGaWx0ZXIiOnsiaHJlZiI6IiNmaWx0ZXIiLCJ0aXRsZSI6IihpbmZvOiBGaWxlSW5mbykgPT4gTWF5YmVQcm9taXNlPGJvb2xlYW4-In19 type ListOptions = { // Visit entries in nested directories. // Default: `false` recursive?: boolean; // Keep entries accepted by a regular expression or callback. filter?: RegExp | Filter; }; ``` ## GlobOptions Options for lazy filesystem glob scanning. This remains an object type alias so options are assignable to broad `Record` consumers. Consumers can still extend the shape through an interface or intersection. ```ts type GlobOptions = { // Directory against which the relative pattern is evaluated. cwd?: string; // Cancels traversal and causes the iterator to reject. signal?: AbortSignal; }; ``` ## LinkOptions Options for creating a symbolic link. ```ts type LinkOptions = { // Only symbolic links are supported. // Default: `"symbolic"` type?: "symbolic"; // Windows target-kind hint; ignored by POSIX filesystems. targetType?: "file" | "directory"; }; ``` ## NamedStreamable A streamable value with a filename or other display name. **Type parameters** - `T` — The chunks produced by the stream. ```ts api-types=eyJTdHJlYW1hYmxlIjp7ImhyZWYiOiIjc3RyZWFtYWJsZSIsInRpdGxlIjoiQSB2YWx1ZSB0aGF0IGNhbiBwcm92aWRlIGEgd2ViIGBSZWFkYWJsZVN0cmVhbWAuIn19 type NamedStreamable = Streamable & { name: string }; ``` ## Path A complete filesystem path accepted by `@rcompat/fs` operations. Native path strings and `file://` strings are accepted. Strings beginning with a non-file `://`, such as `https://example.com/file.txt`, are rejected before filesystem access. Drive-letter paths, including paths using doubled forward slashes such as `C://Temp/file.txt`, and ordinary filenames containing a colon remain native paths. URL objects must use the `file:` protocol. Filesystem helpers never fetch network resources. APIs for relative path segments, such as `FileRef.join()`, exclude URL objects from this complete-path contract. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIjZmlsZXJlZiIsInRpdGxlIjoiQSBwYXRobGliLWluc3BpcmVkIHJlZmVyZW5jZSB0byBhIGZpbGUgb3IgZGlyZWN0b3J5LiJ9fQ type Path = FileRef | URL | string; ``` ## RemoveOptions Options for removing a filesystem entry. ```ts api-types=eyJEaXJlY3RvcnlPcHRpb25zIjp7ImhyZWYiOiIjZGlyZWN0b3J5b3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyBmb3IgY3JlYXRpbmcgYSBkaXJlY3RvcnkuIn19 interface RemoveOptions extends DirectoryOptions { // Fail when the entry does not exist. // Default: `false` fail?: boolean; // Remove directory contents recursively. // Default: `true` recursive?: boolean; } ``` ## SpoolOptions Options for creating a disposable streamed file snapshot. This remains an object type alias so options are assignable to broad `Record` consumers. Consumers can still extend the shape through an interface or intersection. ```ts type SpoolOptions = { // Digest algorithm. Only `SHA-256` is currently supported. algorithm?: "SHA-256"; // Trusted 64-character hexadecimal SHA-256 digest to verify. expectedDigest?: string; // Aborts only the spooling phase. signal?: AbortSignal; }; ``` ## SpoolSnapshot An owned, disposable snapshot created by `fs.spool()`. ```ts type SpoolSnapshot = { // Lowercase hexadecimal SHA-256 digest of the saved bytes. readonly digest: string; // Number of bytes saved. readonly size: number; // Opens the snapshot for its single read. stream(): ReadableStream; // Closes an active read and removes the backing file. // Safe to call repeatedly, including after stream completion. dispose(): Promise; }; ``` ## Streamable A value that can provide a web `ReadableStream`. Objects can expose streams through [`fs.streamable`](/api/fs#fs-streamable). **Type parameters** - `T` — The chunks produced by the stream. ```ts type Streamable = | Blob | ReadableStream | { [fs.streamable](): ReadableStream } ; ``` ## WritableInput Content accepted by filesystem write operations. ```ts type WritableInput = | ArrayBuffer | Uint8Array | Blob | ReadableStream | Response | string ; ``` --- Source: https://rcompat.repopack.app/api/html # @rcompat/html API Browser-safe HTML text encoding utilities. These utilities have no runtime-native dependencies and work in current browsers, Node, Deno, and Bun. ```ts import HTML from "@rcompat/html"; ``` ## HTML.escape Escapes a string for HTML text or a quoted HTML attribute value. Replaces `&`, `<`, `>`, `"`, and `'` with HTML entities. HTML encoding is context-specific: this does not make input safe for JavaScript, CSS, unquoted attributes, or URL protocols. Validate URLs and other structured values before encoding them. **Parameters** - `input` — String to escape. **Returns:** The HTML-encoded string. ```ts HTML.escape(input: string): string; ``` **Example** ```ts HTML.escape(''); // "<span title="me & you">" ``` --- Source: https://rcompat.repopack.app/api/http # @rcompat/http API Cross-runtime HTTP servers using WHATWG request and response primitives. Serving is supported on Node, Deno, and Bun. Browser bundles can import the package and use its constants, MIME resolver, and multipart reader. `http.serve` throws because browsers cannot listen for incoming connections. ```ts import http from "@rcompat/http"; import type { Actions, Conf, Method, MultipartOptions, MultipartPart, Serve, Server, Timeout, ValidStatus, WebSocket, WebSocketData, WebSocketInput, } from "@rcompat/http"; ``` The default HTTP server utility aggregate. ## http.methods Supported lowercase HTTP method names. ```ts http.methods: readonly ["get", "post", "put", "delete", "head", "connect", "options", "trace", "patch"]; ``` ## http.MIME Common MIME types keyed by uppercase names. ```ts http.MIME: { readonly APPLICATION_GZIP: "application/gzip"; readonly APPLICATION_JSON: "application/json"; readonly APPLICATION_LD_JSON: "application/ld+json"; readonly APPLICATION_MANIFEST_JSON: "application/manifest+json"; readonly APPLICATION_OCTET_STREAM: "application/octet-stream"; readonly APPLICATION_PDF: "application/pdf"; readonly APPLICATION_RSS_XML: "application/rss+xml"; readonly APPLICATION_WASM: "application/wasm"; readonly APPLICATION_X_7Z_COMPRESSED: "application/x-7z-compressed"; readonly APPLICATION_X_BZIP2: "application/x-bzip2"; readonly APPLICATION_X_RAR_COMPRESSED: "application/x-rar-compressed"; readonly APPLICATION_X_TAR: "application/x-tar"; readonly APPLICATION_X_WWW_FORM_URLENCODED: "application/x-www-form-urlencoded"; readonly APPLICATION_XML: "application/xml"; readonly APPLICATION_YAML: "application/yaml"; readonly APPLICATION_ZIP: "application/zip"; readonly AUDIO_MPEG: "audio/mpeg"; readonly AUDIO_OGG: "audio/ogg"; readonly AUDIO_WAV: "audio/wav"; readonly AUDIO_WEBM: "audio/webm"; readonly FONT_OTF: "font/otf"; readonly FONT_TTF: "font/ttf"; readonly FONT_WOFF: "font/woff"; readonly FONT_WOFF2: "font/woff2"; readonly IMAGE_APNG: "image/apng"; readonly IMAGE_AVIF: "image/avif"; readonly IMAGE_BMP: "image/bmp"; readonly IMAGE_GIF: "image/gif"; readonly IMAGE_JPEG: "image/jpeg"; readonly IMAGE_PNG: "image/png"; readonly IMAGE_SVG_XML: "image/svg+xml"; readonly IMAGE_TIFF: "image/tiff"; readonly IMAGE_WEBP: "image/webp"; readonly IMAGE_X_ICON: "image/x-icon"; readonly MULTIPART_FORM_DATA: "multipart/form-data"; readonly TEXT_CSS: "text/css"; readonly TEXT_CSV: "text/csv"; readonly TEXT_EVENT_STREAM: "text/event-stream"; readonly TEXT_HTML: "text/html"; readonly TEXT_JAVASCRIPT: "text/javascript"; readonly TEXT_MARKDOWN: "text/markdown"; readonly TEXT_PLAIN: "text/plain"; readonly TEXT_RTF: "text/rtf"; readonly TEXT_TAB_SEPARATED_VALUES: "text/tab-separated-values"; readonly TEXT_VTT: "text/vtt"; readonly VIDEO_MP2T: "video/mp2t"; readonly VIDEO_MP4: "video/mp4"; readonly VIDEO_OGG: "video/ogg"; readonly VIDEO_QUICKTIME: "video/quicktime"; readonly VIDEO_WEBM: "video/webm"; }; ``` ## http.Status Standard HTTP status codes keyed by uppercase names. ```ts http.Status: { readonly ACCEPTED: 202; readonly ALREADY_REPORTED: 208; readonly BAD_GATEWAY: 502; readonly BAD_REQUEST: 400; readonly CONFLICT: 409; readonly CONTINUE: 100; readonly CREATED: 201; readonly EARLY_HINTS: 103; readonly EXPECTATION_FAILED: 417; readonly FAILED_DEPENDENCY: 424; readonly FORBIDDEN: 403; readonly FOUND: 302; readonly GATEWAY_TIMEOUT: 504; readonly GONE: 410; readonly HTTP_VERSION_NOT_SUPPORTED: 505; readonly IM_A_TEAPOT: 418; readonly IM_USED: 226; readonly INSUFFICIENT_STORAGE: 507; readonly INTERNAL_SERVER_ERROR: 500; readonly LENGTH_REQUIRED: 411; readonly LOCKED: 423; readonly LOOP_DETECTED: 508; readonly METHOD_NOT_ALLOWED: 405; readonly MISDIRECTED_REQUEST: 421; readonly MOVED_PERMANENTLY: 301; readonly MULTIPLE_CHOICES: 300; readonly NETWORK_AUTHENTICATION_REQUIRED: 511; readonly NO_CONTENT: 204; readonly NON_AUTHORITATIVE_INFORMATION: 203; readonly NOT_ACCEPTABLE: 406; readonly NOT_EXTENDED: 510; readonly NOT_FOUND: 404; readonly NOT_IMPLEMENTED: 501; readonly NOT_MODIFIED: 304; readonly OK: 200; readonly PARTIAL_CONTENT: 206; readonly PAYLOAD_TOO_LARGE: 413; readonly PAYMENT_REQUIRED: 402; readonly PERMANENT_REDIRECT: 308; readonly PRECONDITION_FAILED: 412; readonly PRECONDITION_REQUIRED: 428; readonly PROCESS: 102; readonly PROXY_AUTHENTICATION_REQUIRED: 407; readonly RANGE_NOT_SATISFIABLE: 416; readonly REQUEST_HEADER_FIELDS_TOO_LARGE: 431; readonly REQUEST_TIMEOUT: 408; readonly RESET_CONTENT: 205; readonly SEE_OTHER: 303; readonly SERVICE_UNAVAILABLE: 503; readonly SWITCH_PROXY: 306; readonly SWITCHING_PROTOCOLS: 101; readonly TEMPORARY_REDIRECT: 307; readonly TOO_EARLY: 425; readonly TOO_MANY_REQUESTS: 429; readonly UNAUTHORIZED: 401; readonly UNAVAILABLE_FOR_LEGAL_REASONS: 451; readonly UNPROCESSABLE_ENTITY: 422; readonly UNSUPPORTED_MEDIA_TYPE: 415; readonly UPGRADE_REQUIRED: 426; readonly URI_TOO_LONG: 414; readonly USE_PROXY: 305; readonly VARIANT_ALSO_NEGOTIATES: 506; }; ``` ## http.toMIME() Resolves a filename extension to a MIME type. **Parameters** - `filename` — Filename or path whose final extension is resolved. **Returns:** The matching MIME type, or `application/octet-stream` when the extension is absent or unknown. ```ts http.toMIME(filename: string): string; ``` ## http.serve() Starts a runtime-native HTTP server. **Parameters** - `handler` — Incoming request handler. - `conf` — Listening, TLS, and timeout configuration. **Returns:** A promise for the running server controls. **Throws:** In browsers, where listening for HTTP connections is unavailable. ```ts api-types=eyJDb25mIjp7ImhyZWYiOiIjY29uZiIsInRpdGxlIjoiSFRUUCBzZXJ2ZXIgY29uZmlndXJhdGlvbi4ifSwiU2VydmVyIjp7ImhyZWYiOiIjc2VydmVyIiwidGl0bGUiOiJBIHJ1bm5pbmcgSFRUUCBzZXJ2ZXIuIn0sIkhhbmRsZXIiOnsiaHJlZiI6IiNoYW5kbGVyIiwidGl0bGUiOiIocmVxdWVzdDogUHNldWRvUmVxdWVzdCB8IFJlcXVlc3QpID0-IE1heWJlUHJvbWlzZTxudWxsIHwgUmVzcG9uc2U-In19 http.serve: (handler: Handler, conf: Conf) => Promise; ``` **Example** ```ts const server = await http.serve( () => new Response("Hello"), { port: 8080 }, ); server.stop(); ``` ## http.multipart() Read a multipart form one part at a time from a Web byte stream. **Parameters** - `content_type` — The request's multipart/form-data Content-Type. - `source` — The unlocked input stream. - `options` — Parser limits and optional cancellation signal. **Returns:** An iterator yielding parts in wire order. ```ts api-types=eyJNdWx0aXBhcnRPcHRpb25zIjp7ImhyZWYiOiIjbXVsdGlwYXJ0b3B0aW9ucyIsInRpdGxlIjoiTGltaXRzIGFuZCBjYW5jZWxsYXRpb24gZm9yIGEgc3RyZWFtaW5nIG11bHRpcGFydCBmb3JtLiJ9LCJNdWx0aXBhcnRQYXJ0Ijp7ImhyZWYiOiIjbXVsdGlwYXJ0cGFydCIsInRpdGxlIjoiQSBwYXJ0IG9mIGEgbXVsdGlwYXJ0IGZvcm0gaW4gd2lyZSBvcmRlci4ifX0 http.multipart( content_type: string, source: ReadableStream, options?: MultipartOptions, ): AsyncIterableIterator; ``` ## http.MultipartError The input is not a well-formed multipart form. ```ts http.MultipartError: typeof MultipartError; ``` ## http.MultipartLimitError The multipart input exceeded a parser limit. ```ts http.MultipartLimitError: typeof MultipartLimitError; ``` ## Types ## Actions WebSocket lifecycle callbacks. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiV2ViU29ja2V0Ijp7ImhyZWYiOiIjd2Vic29ja2V0IiwidGl0bGUiOiJQb3J0YWJsZSBzZXJ2ZXItc2lkZSBXZWJTb2NrZXQuIn0sIldlYlNvY2tldERhdGEiOnsiaHJlZiI6IiN3ZWJzb2NrZXRkYXRhIiwidGl0bGUiOiJzdHJpbmcgfCBVaW50OEFycmF5In19 interface Actions extends Dict { // Called when a socket closes. close?: (socket: WebSocket, code: number, reason: string) => unknown; // Called with a text string or binary byte array. message?: (socket: WebSocket, message: WebSocketData) => unknown; // Called when a socket opens. open?: (socket: WebSocket) => unknown; } ``` ## Conf HTTP server configuration. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIvYXBpL2ZzI2ZpbGVyZWYiLCJ0aXRsZSI6IkEgcGF0aGxpYi1pbnNwaXJlZCByZWZlcmVuY2UgdG8gYSBmaWxlIG9yIGRpcmVjdG9yeS4ifSwiVGltZW91dCI6eyJocmVmIjoiI3RpbWVvdXQiLCJ0aXRsZSI6IlBvcnRhYmxlIHNlcnZlciB0aW1lb3V0IHBvbGljeSBpbiB3aG9sZSBtaWxsaXNlY29uZHMuIn19 type Conf = { // Hostname or address on which to listen. host: string; // TCP port on which to listen. port: number; // TLS certificate and private key files. ssl?: { // Certificate file. cert: FileRef; // Private-key file. key: FileRef; }; // Portable server timeout policy. timeout?: Timeout; }; ``` ## Method A lowercase method represented by `http.methods`. ```ts type Method = "get" | "post" | "put" | "delete" | "head" | "connect" | "options" | "trace" | "patch"; ``` ## MultipartOptions Limits and cancellation for a streaming multipart form. ```ts interface MultipartOptions { // Maximum number of parts, including skipped parts. Defaults to 128. readonly max_parts?: number; // Maximum bytes per part, including skipped bytes. Defaults to 16 MiB. readonly max_part_bytes?: number; readonly signal?: AbortSignal; } ``` ## MultipartPart A part of a multipart form in wire order. ```ts interface MultipartPart { readonly name: string; readonly filename?: string; readonly content_type?: string; readonly body: ReadableStream; } ``` ## Serve Starts a runtime-native HTTP server. **Parameters** - `handler` — Incoming request handler. - `conf` — Listening, TLS, and timeout configuration. **Returns:** A promise for the running server controls. **Throws:** In browsers, where listening for HTTP connections is unavailable. ```ts api-types=eyJDb25mIjp7ImhyZWYiOiIjY29uZiIsInRpdGxlIjoiSFRUUCBzZXJ2ZXIgY29uZmlndXJhdGlvbi4ifSwiU2VydmVyIjp7ImhyZWYiOiIjc2VydmVyIiwidGl0bGUiOiJBIHJ1bm5pbmcgSFRUUCBzZXJ2ZXIuIn0sIkhhbmRsZXIiOnsiaHJlZiI6IiNoYW5kbGVyIiwidGl0bGUiOiIocmVxdWVzdDogUHNldWRvUmVxdWVzdCB8IFJlcXVlc3QpID0-IE1heWJlUHJvbWlzZTxudWxsIHwgUmVzcG9uc2U-In19 type Serve = (handler: Handler, conf: Conf) => Promise; ``` **Example** ```ts const server = await http.serve( () => new Response("Hello"), { port: 8080 }, ); server.stop(); ``` ## Server A running HTTP server. ```ts api-types=eyJBY3Rpb25zIjp7ImhyZWYiOiIjYWN0aW9ucyIsInRpdGxlIjoiV2ViU29ja2V0IGxpZmVjeWNsZSBjYWxsYmFja3MuIn0sIldlYlNvY2tldCI6eyJocmVmIjoiI3dlYnNvY2tldCIsInRpdGxlIjoiUG9ydGFibGUgc2VydmVyLXNpZGUgV2ViU29ja2V0LiJ9fQ type Server = { // Stops accepting requests and closes the server. stop(): void; // Upgrades to WebSocket and returns the runtime response or `null`. upgrade(request: Request, actions: Actions): null | Response; }; ``` ## Timeout Portable server timeout policy in whole milliseconds. Omitting the object, using an empty object, or omitting an individual member preserves the corresponding runtime default. A value of `0` disables a supported clock. `inactivity` is supported by Node and Bun; Bun rounds it up to whole seconds. It accepts values through `255000`. `request` and `headers` are Node-only and accept values through `2147483647`. Deno rejects every configured member, and Bun rejects `request` and `headers`, even when the value is `0`. On Node, enabled `headers` cannot exceed the effective `request` timeout. Unknown members, non-integers, negative values, and out-of-range values are rejected before the server binds. ```ts type Timeout = { // Maximum consecutive in-flight network inactivity; traffic resets it. inactivity?: number; // Maximum total time to receive request headers and body. request?: number; // Maximum total time to receive complete request headers. headers?: number; }; ``` ## ValidStatus A numeric status represented by `http.Status`. ```ts type ValidStatus = typeof http.Status[keyof typeof http.Status]; ``` ## WebSocket Portable server-side WebSocket. Node limits each assembled incoming or outgoing message to 16 MiB, caps queued outgoing data at 32 MiB, does not negotiate extensions, and selects the first offered subprotocol. ```ts api-types=eyJXZWJTb2NrZXRJbnB1dCI6eyJocmVmIjoiI3dlYnNvY2tldGlucHV0IiwidGl0bGUiOiJzdHJpbmcgfCBBcnJheUJ1ZmZlciB8IFVpbnQ4QXJyYXkifX0 interface WebSocket { // Bytes currently waiting to be written, when reported by the runtime. readonly bufferedAmount?: number; // Negotiated subprotocol, when reported by the runtime. readonly protocol?: string; // Current WebSocket ready-state number. readonly readyState: number; // Closes the connection with an optional close code and reason. close(code?: number, reason?: string): void; // Sends text, an array buffer, or bytes. send(data: WebSocketInput): void; } ``` ## WebSocketData Portable incoming WebSocket message data. ```ts type WebSocketData = string | Uint8Array; ``` ## WebSocketInput Portable outgoing WebSocket message data. ```ts type WebSocketInput = string | ArrayBuffer | Uint8Array; ``` ## Supporting contract ### Handler Handles an incoming request and optionally produces a response. Node supplies its request-compatible adapter; Deno and Bun supply a native WHATWG `Request`. ```ts api-types=eyJNYXliZVByb21pc2UiOnsiaHJlZiI6Ii9hcGkvdHlwZSNtYXliZXByb21pc2UiLCJ0aXRsZSI6IlByb21pc2U8VD4gfCBUIn19 type Handler = (request: PseudoRequest | Request) => MaybePromise; ``` --- Source: https://rcompat.repopack.app/api/io # @rcompat/io API Standard streams, process execution, and async context across runtimes. Node, Deno, and Bun provide the complete API. Browser bundles can import the package, but every utility throws because standard streams and child processes are unavailable. ```ts import io from "@rcompat/io"; import type { ChildProcess, ExitStatus, ProcessSignal, RunOptions, RunResult, SpawnOptions, Stdio, StdioInput, StdioOptions, } from "@rcompat/io"; ``` The default input/output utility aggregate. ## io.async Asynchronous context utilities. ### Async members #### io.async.Context The runtime-compatible `AsyncLocalStorage` constructor. ```ts io.async.Context: typeof AsyncLocalStorage; ``` ## io.isatty() Tests whether standard output is attached to a terminal. ```ts io.isatty(): boolean; ``` ## io.run() Runs a shell command and captures its complete text output. Nonzero exit codes resolve normally with `success: false`. Startup and stream failures reject. A timeout covers both process exit and complete output capture. **Parameters** - `command` — Platform-shell command to execute. - `options` — Working directory, environment, timeout, and timeout signal. **Returns:** Captured output and exit status. ```ts api-types=eyJSdW5PcHRpb25zIjp7ImhyZWYiOiIjcnVub3B0aW9ucyIsInRpdGxlIjoiT21pdDxTcGF3bk9wdGlvbnMsIFwic3RkaW9cIj4ifSwiUnVuUmVzdWx0Ijp7ImhyZWYiOiIjcnVucmVzdWx0IiwidGl0bGUiOiJDYXB0dXJlZCB0ZXh0IG91dHB1dCBhbmQgZmluYWwgcHJvY2VzcyBzdGF0dXMgZnJvbSBgaW8ucnVuYC4ifX0 io.run( command: string, options?: RunOptions, ): Promise; ``` **Example** ```ts const result = await io.run("echo hello"); result.success; // true result.stdout.trim(); // "hello" ``` ## io.spawn() Spawns a platform-shell command or directly executes an argument vector. String commands use the platform shell. Supplying an argument array bypasses the shell and passes every argument verbatim. On POSIX systems the child is placed in an isolated process group so `kill` and timeouts terminate its descendants as well. ```ts api-types=eyJDaGlsZFByb2Nlc3MiOnsiaHJlZiI6IiNjaGlsZHByb2Nlc3MiLCJ0aXRsZSI6IkEgc3Bhd25lZCBwcm9jZXNzIGFuZCBpdHMgY29uZmlndXJlZCBXZWIgU3RyZWFtcy4ifSwiU3Bhd25PcHRpb25zIjp7ImhyZWYiOiIjc3Bhd25vcHRpb25zIiwidGl0bGUiOiJPcHRpb25zIGZvciBgaW8uc3Bhd25gLiJ9LCJTdGRpb0lucHV0Ijp7ImhyZWYiOiIjc3RkaW9pbnB1dCIsInRpdGxlIjoiU3RkaW8gfCBTdGRpb09wdGlvbnMifX0 io.spawn: { ( command: string, options?: SpawnOptions, ): ChildProcess; ( executable: string, args: readonly string[], options?: SpawnOptions, ): ChildProcess; }; ``` ## io.stderr Standard error as a Node-compatible writable stream. ```ts io.stderr: NodeJS.WriteStream & { readonly fd: 2 }; ``` ## io.stdin Standard input as a Node-compatible readable stream. ```ts io.stdin: NodeJS.ReadStream & { readonly fd: 0 }; ``` ## io.stdout Standard output as a Node-compatible writable stream. ```ts io.stdout: NodeJS.WriteStream & { readonly fd: 1 }; ``` ## io.which() Resolves an executable with the platform's `which` or `where` utility. **Parameters** - `command` — Executable name to locate. **Returns:** The first non-empty path reported by the locator. **Throws:** When the executable cannot be found or the locator fails. ```ts io.which(command: string): Promise; ``` ## Types ## RunOptions Spawn options accepted by `io.run`, excluding stream configuration. ```ts api-types=eyJTcGF3bk9wdGlvbnMiOnsiaHJlZiI6IiNzcGF3bm9wdGlvbnMiLCJ0aXRsZSI6Ik9wdGlvbnMgZm9yIGBpby5zcGF3bmAuIn19 type RunOptions = Omit; ``` ## RunResult Captured text output and final process status from `io.run`. ```ts api-types=eyJFeGl0U3RhdHVzIjp7ImhyZWYiOiIjZXhpdHN0YXR1cyIsInRpdGxlIjoiRmluYWwgY2hpbGQtcHJvY2VzcyBzdGF0dXMuIn19 type RunResult = ExitStatus & { // Captured standard error decoded as text. stderr: string; // Captured standard output decoded as text. stdout: string; }; ``` ## ChildProcess A spawned process and its configured Web Streams. ```ts api-types=eyJFeGl0U3RhdHVzIjp7ImhyZWYiOiIjZXhpdHN0YXR1cyIsInRpdGxlIjoiRmluYWwgY2hpbGQtcHJvY2VzcyBzdGF0dXMuIn0sIlByb2Nlc3NTaWduYWwiOnsiaHJlZiI6IiNwcm9jZXNzc2lnbmFsIiwidGl0bGUiOiJcIlNJR0FCUlRcIiB8IFwiU0lHQUxSTVwiIHwgXCJTSUdIVVBcIiB8IFwiU0lHSU5UXCIgfCBcIlNJR0tJTExcIiB8IFwiU0lHUElQRVwiIHwgXCJTSUdRVUlUXCIgfCBcIlNJR1RFUk1cIiB8IFwiU0lHVVNSMVwiIHwgXCJTSUdVU1IyXCIifSwiU3RkaW9JbnB1dCI6eyJocmVmIjoiI3N0ZGlvaW5wdXQiLCJ0aXRsZSI6IlN0ZGlvIHwgU3RkaW9PcHRpb25zIn0sIk1vZGUiOnsiaHJlZiI6IiNtb2RlIiwidGl0bGUiOiJTIGV4dGVuZHMgU3RkaW8gPyBTIDogSyBleHRlbmRzIGtleW9mIFMgPyBEZWZhdWx0UGlwZTxTW0tdPiA6IFwicGlwZVwiIn0sIlN0cmVhbSI6eyJocmVmIjoiI3N0cmVhbSIsInRpdGxlIjoiTSBleHRlbmRzIFwicGlwZVwiID8gVCA6IG51bGwifX0 type ChildProcess = { // Sends a signal, defaulting to `SIGTERM`. kill(signal?: ProcessSignal): void; // Runtime process identifier. pid: number; // Final status, including nonzero exits and timeout state. status: Promise; // Piped standard error, or `null` for `inherit` and `ignore`. stderr: Stream, ReadableStream>; // Piped standard input, or `null` for `inherit` and `ignore`. stdin: Stream, WritableStream>; // Piped standard output, or `null` for `inherit` and `ignore`. stdout: Stream, ReadableStream>; }; ``` ## ExitStatus Final child-process status. ```ts api-types=eyJQcm9jZXNzU2lnbmFsIjp7ImhyZWYiOiIjcHJvY2Vzc3NpZ25hbCIsInRpdGxlIjoiXCJTSUdBQlJUXCIgfCBcIlNJR0FMUk1cIiB8IFwiU0lHSFVQXCIgfCBcIlNJR0lOVFwiIHwgXCJTSUdLSUxMXCIgfCBcIlNJR1BJUEVcIiB8IFwiU0lHUVVJVFwiIHwgXCJTSUdURVJNXCIgfCBcIlNJR1VTUjFcIiB8IFwiU0lHVVNSMlwiIn19 type ExitStatus = { // Exit code, or `null` when terminated by a signal. code: number | null; // Terminating signal, or `null` after a normal exit. signal: ProcessSignal | null; // Whether the process exited with code zero without a signal or timeout. success: boolean; // Whether the configured timeout terminated the process. timedOut: boolean; }; ``` ## SpawnOptions Options for `io.spawn`. ```ts api-types=eyJQcm9jZXNzU2lnbmFsIjp7ImhyZWYiOiIjcHJvY2Vzc3NpZ25hbCIsInRpdGxlIjoiXCJTSUdBQlJUXCIgfCBcIlNJR0FMUk1cIiB8IFwiU0lHSFVQXCIgfCBcIlNJR0lOVFwiIHwgXCJTSUdLSUxMXCIgfCBcIlNJR1BJUEVcIiB8IFwiU0lHUVVJVFwiIHwgXCJTSUdURVJNXCIgfCBcIlNJR1VTUjFcIiB8IFwiU0lHVVNSMlwiIn0sIlN0ZGlvSW5wdXQiOnsiaHJlZiI6IiNzdGRpb2lucHV0IiwidGl0bGUiOiJTdGRpbyB8IFN0ZGlvT3B0aW9ucyJ9LCJFbnZpcm9ubWVudCI6eyJocmVmIjoiI2Vudmlyb25tZW50IiwidGl0bGUiOiJSZWNvcmQ8c3RyaW5nLCBzdHJpbmcgfCB1bmRlZmluZWQ-In19 type SpawnOptions = { // Child working directory. cwd?: string; // Child environment variables. env?: Environment; // Signal sent when `timeout` expires. // Default: `"SIGKILL"` killSignal?: ProcessSignal; // Standard-stream modes. // Default: `"pipe"` stdio?: S; // Milliseconds before terminating the process group. timeout?: number; }; ``` ## ProcessSignal Portable process signals accepted by process controls. ```ts type ProcessSignal = | "SIGABRT" | "SIGALRM" | "SIGHUP" | "SIGINT" | "SIGKILL" | "SIGPIPE" | "SIGQUIT" | "SIGTERM" | "SIGUSR1" | "SIGUSR2"; ``` ## Stdio Standard-stream handling mode. ```ts type Stdio = "ignore" | "inherit" | "pipe"; ``` ## StdioInput One mode for every stream or independent per-stream modes. ```ts api-types=eyJTdGRpbyI6eyJocmVmIjoiI3N0ZGlvIiwidGl0bGUiOiJcImlnbm9yZVwiIHwgXCJpbmhlcml0XCIgfCBcInBpcGVcIiJ9LCJTdGRpb09wdGlvbnMiOnsiaHJlZiI6IiNzdGRpb29wdGlvbnMiLCJ0aXRsZSI6IlBlci1zdHJlYW0gaGFuZGxpbmcgbW9kZXMuIn19 type StdioInput = Stdio | StdioOptions; ``` ## StdioOptions Per-stream handling modes. ```ts api-types=eyJTdGRpbyI6eyJocmVmIjoiI3N0ZGlvIiwidGl0bGUiOiJcImlnbm9yZVwiIHwgXCJpbmhlcml0XCIgfCBcInBpcGVcIiJ9fQ type StdioOptions = { // Standard-error mode. // Default: `"pipe"` stderr?: Stdio; // Standard-input mode. // Default: `"pipe"` stdin?: Stdio; // Standard-output mode. // Default: `"pipe"` stdout?: Stdio; }; ``` ## Supporting contracts These contracts support public signatures but are not named root exports. ### DefaultPipe Resolves an omitted stream mode to `"pipe"`. ```ts type DefaultPipe = [Exclude] extends [never] ? "pipe" : Exclude; ``` ### Environment Environment variables supplied to a child process. ```ts type Environment = Record; ``` ### Mode Resolves the effective mode for one configured standard stream. ```ts api-types=eyJTdGRpbyI6eyJocmVmIjoiI3N0ZGlvIiwidGl0bGUiOiJcImlnbm9yZVwiIHwgXCJpbmhlcml0XCIgfCBcInBpcGVcIiJ9LCJTdGRpb0lucHV0Ijp7ImhyZWYiOiIjc3RkaW9pbnB1dCIsInRpdGxlIjoiU3RkaW8gfCBTdGRpb09wdGlvbnMifSwiU3RkaW9PcHRpb25zIjp7ImhyZWYiOiIjc3RkaW9vcHRpb25zIiwidGl0bGUiOiJQZXItc3RyZWFtIGhhbmRsaW5nIG1vZGVzLiJ9LCJEZWZhdWx0UGlwZSI6eyJocmVmIjoiI2RlZmF1bHRwaXBlIiwidGl0bGUiOiJbRXhjbHVkZTxNLCB1bmRlZmluZWQ-XSBleHRlbmRzIFtuZXZlcl0gPyBcInBpcGVcIiA6IEV4Y2x1ZGU8TSwgdW5kZWZpbmVkPiJ9fQ type Mode = S extends Stdio ? S : K extends keyof S ? DefaultPipe : "pipe"; ``` ### Stream Selects a Web Stream for `"pipe"`, or `null` otherwise. ```ts api-types=eyJTdGRpbyI6eyJocmVmIjoiI3N0ZGlvIiwidGl0bGUiOiJcImlnbm9yZVwiIHwgXCJpbmhlcml0XCIgfCBcInBpcGVcIiJ9fQ type Stream = M extends "pipe" ? T : null; ``` --- Source: https://rcompat.repopack.app/api/is # @rcompat/is API Type guards and predicates for common JavaScript values. Checks use standard JavaScript and web-platform types available in current browsers, Node, Deno, and Bun. A `true` type-guard result narrows the input to the type shown in its signature. ```ts import is from "@rcompat/is"; ``` ## is.array Checks whether a value is an array. ```ts is.array(x: unknown): x is unknown[]; ``` ## is.arraybuffer Checks whether a value is an `ArrayBuffer`. ```ts is.arraybuffer(x: unknown): x is ArrayBuffer; ``` ## is.bigint Checks whether a value is a bigint. ```ts is.bigint(x: unknown): x is bigint; ``` ## is.blank Checks whether a value is an empty or whitespace-only string. ```ts is.blank(x: unknown): x is string; ``` ## is.blob Checks whether a value is a `Blob`. ```ts is.blob(x: unknown): x is Blob; ``` ## is.boolish Checks whether a value is the string `"true"` or `"false"`. ```ts api-types=eyJCb29saXNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjYm9vbGlzaCIsInRpdGxlIjoiXCJmYWxzZVwiIHwgXCJ0cnVlXCIifX0 is.boolish(x: unknown): x is Boolish; ``` ## is.boolean Checks whether a value is a boolean. ```ts is.boolean(x: unknown): x is boolean; ``` ## is.branded Checks whether an object owns a symbol brand. ```ts is.branded( x: unknown, brand: S, ): x is Record unknown>; ``` ## is.bytes Checks whether a value is a `Uint8Array`. ```ts is.bytes(x: unknown): x is Uint8Array; ``` ## is.date Checks whether a value is a `Date`. ```ts is.date(x: unknown): x is Date; ``` ## is.defined Checks whether a value is not `undefined`. ```ts is.defined(x: T): x is Exclude; ``` ## is.dict Checks whether a value is a plain object. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 is.dict(x: unknown): x is Dict; ``` ## is.empty Checks whether a string, collection, or object is empty. ```ts is.empty(x: unknown): boolean; ``` ## is.error Checks whether a value is an `Error`. ```ts is.error(x: unknown): x is Error; ``` ## is.f32 Checks whether a number is exactly representable as a float32. ```ts is.f32(x: unknown): x is number; ``` ## is.f32array Checks whether a value is a `Float32Array`. ```ts is.f32array(x: unknown): x is Float32Array; ``` ## is.f64array Checks whether a value is a `Float64Array`. ```ts is.f64array(x: unknown): x is Float64Array; ``` ## is.falsy Checks whether a value is falsy. ```ts is.falsy(x: unknown): boolean; ``` ## is.file Checks whether a value is a `File`. ```ts is.file(x: unknown): x is File; ``` ## is.finite Checks whether a value is a finite number or bigint. ```ts is.finite(x: unknown): x is bigint | number; ``` ## is.function Checks whether a value is callable. ```ts api-types=eyJVbmtub3duRnVuY3Rpb24iOnsiaHJlZiI6Ii9hcGkvdHlwZSN1bmtub3duZnVuY3Rpb24iLCJ0aXRsZSI6IiguLi5wYXJhbXM6IGFueVtdKSA9PiB1bmtub3duIn19 is.function(x: unknown): x is UnknownFunction; ``` ## is.int Checks whether a value is an integer number or bigint. ```ts is.int(x: unknown): x is bigint | number; ``` ## is.iterable Checks whether a value implements the iterable protocol. ```ts is.iterable(x: unknown): x is Iterable; ``` ## is.json Checks whether a value has a direct JSON representation. Sparse arrays are rejected because JSON serialization replaces holes with `null`. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9fQ is.json(x: unknown): x is JSONValue; ``` ## is.map Checks whether a value is a `Map`. ```ts is.map(x: unknown): x is Map; ``` ## is.nan Checks whether a value is `NaN`. ```ts is.nan(x: unknown): x is number; ``` ## is.nonempty Checks whether a nullable value is nonempty. ```ts api-types=eyJOdWxsaXNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjbnVsbGlzaCIsInRpdGxlIjoibnVsbCB8IHVuZGVmaW5lZCJ9fQ is.nonempty(x: T | Nullish): x is T; ``` ## is.newable Checks whether a value is constructible with `new`. ```ts api-types=eyJOZXdhYmxlIjp7ImhyZWYiOiIvYXBpL3R5cGUjbmV3YWJsZSIsInRpdGxlIjoibmV3ICguLi5hcmdzOiBBKSA9PiBJIn19 is.newable(x: unknown): x is Newable; ``` ## is.null Checks whether a value is `null`. ```ts is.null(x: unknown): x is null; ``` ## is.nullish Checks whether a value is `null` or `undefined`. ```ts api-types=eyJOdWxsaXNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjbnVsbGlzaCIsInRpdGxlIjoibnVsbCB8IHVuZGVmaW5lZCJ9fQ is.nullish(x: unknown): x is Nullish; ``` ## is.number Checks whether a value is a number, including `NaN`. ```ts is.number(x: unknown): x is number; ``` ## is.numeric Checks whether a value is a decimal numeric string. ```ts is.numeric(x: unknown): x is string; ``` ## is.object Checks whether a value is a non-null object. ```ts is.object(x: unknown): x is object; ``` ## is.primitive Checks whether a value is a JavaScript primitive. ```ts api-types=eyJQcmltaXRpdmUiOnsiaHJlZiI6Ii9hcGkvdHlwZSNwcmltaXRpdmUiLCJ0aXRsZSI6ImJpZ2ludCB8IGJvb2xlYW4gfCBudWxsIHwgbnVtYmVyIHwgc3RyaW5nIHwgc3ltYm9sIHwgdW5kZWZpbmVkIn19 is.primitive(x: unknown): x is Primitive; ``` ## is.promise Checks whether a value is a `Promise`. ```ts is.promise(x: unknown): x is Promise; ``` ## is.request Checks whether a value is a `Request`. ```ts is.request(x: unknown): x is Request; ``` ## is.response Checks whether a value is a `Response`. ```ts is.response(x: unknown): x is Response; ``` ## is.regexp Checks whether a value is a regular expression. ```ts is.regexp(x: unknown): x is RegExp; ``` ## is.safeint Checks whether a value is a safe integer number. ```ts is.safeint(x: unknown): x is number; ``` ## is.set Checks whether a value is a `Set`. ```ts is.set(x: unknown): x is Set; ``` ## is.stream Checks whether a value is a readable web stream. ```ts is.stream(x: unknown): x is ReadableStream; ``` ## is.string Checks whether a value is a string. ```ts is.string(x: unknown): x is string; ``` ## is.symbol Checks whether a value is a symbol. ```ts is.symbol(x: unknown): x is symbol; ``` ## is.text Checks whether a value is a nonempty, non-whitespace string. ```ts is.text(x: unknown): x is string; ``` ## is.truthy Checks whether a value is truthy and narrows out falsy literals. ```ts is.truthy(x: T): x is Exclude; ``` ## is.typedarray Checks whether a value is an `ArrayBuffer` view. ```ts is.typedarray(x: unknown): x is ArrayBufferView; ``` ## is.uint Checks whether a value is a non-negative integer or bigint. ```ts is.uint(x: unknown): x is bigint | number; ``` ## is.undefined Checks whether a value is `undefined`. ```ts is.undefined(x: unknown): x is undefined; ``` ## is.url Checks whether a value is a `URL`. ```ts is.url(x: unknown): x is URL; ``` ## is.versioned Checks whether an object owns the requested global version brand. **Throws:** If `brand` is not global or the object has another version of it. ```ts is.versioned(x: unknown, brand: symbol): boolean; ``` --- Source: https://rcompat.repopack.app/api/net # @rcompat/net API Cross-runtime TCP and Unix domain socket operations. Node, Deno, and Bun use runtime-selected native socket adapters exposed as Web Streams. Browser bundles can import this package, but `net.open()` rejects because browsers do not expose raw TCP or Unix sockets. ```ts import net from "@rcompat/net"; import type { NetOptions, Socket, TCPOptions, UnixOptions, } from "@rcompat/net"; ``` ## net.open Opens a TCP or Unix domain socket. Pass `{ host, port }` for TCP or `{ path }` for a Unix domain socket. Connection and address errors from the selected runtime are propagated. **Parameters** - `options` — TCP address or Unix socket path. **Returns:** A socket backed by native Web Streams. **Throws:** In browsers, always rejects because raw sockets are unavailable. ```ts api-types=eyJTb2NrZXQiOnsiaHJlZiI6IiNzb2NrZXQiLCJ0aXRsZSI6IkEgY29ubmVjdGVkIFRDUCBvciBVbml4IHNvY2tldCBiYWNrZWQgYnkgV2ViIFN0cmVhbXMuIn0sIk5ldE9wdGlvbnMiOnsiaHJlZiI6IiNuZXRvcHRpb25zIiwidGl0bGUiOiJUQ1BPcHRpb25zIHwgVW5peE9wdGlvbnMifX0 net.open(options: NetOptions): Promise; ``` **Example** ```ts const socket = await net.open({ host: "127.0.0.1", port: 9000 }); await socket.write("hello"); await socket.close(); ``` ## Types ## Socket A connected TCP or Unix socket backed by Web Streams. Instances are created by `net.open()`; the class is exported only as a type. ```ts declare class Socket {} ``` ### Instance properties #### socket.readable Stream of bytes received from the peer. Reading with `text()` or async iteration locks this stream while that operation is active. ```ts socket.readable: ReadableStream; ``` #### socket.writable Stream used to send bytes to the peer. The socket holds this stream's writer; use `write()`, `end()`, or `close()` rather than acquiring another writer. ```ts socket.writable: WritableStream; ``` ### Instance methods #### socket.write() Writes text or bytes to the peer. Strings are encoded as UTF-8; byte arrays are written unchanged. **Parameters** - `data` — Text or bytes to write. ```ts socket.write(data: string | Uint8Array): Promise ``` #### socket.end() Closes the writable side while leaving the readable side open. Use this half-close when the peer responds after receiving EOF. ```ts socket.end(): Promise ``` #### socket.close() Closes the writable side and cancels the readable side. ```ts socket.close(): Promise ``` #### socket.text() Drains received bytes and decodes them as streaming UTF-8 text. **Returns:** The decoded response after the readable stream ends. ```ts socket.text(): Promise ``` ### Protocol members #### socket\[Symbol.asyncIterator\]() Iterates byte chunks received from the peer. ```ts socket[Symbol.asyncIterator](): AsyncIterator ``` ## NetOptions TCP or Unix domain socket connection options. ```ts api-types=eyJUQ1BPcHRpb25zIjp7ImhyZWYiOiIjdGNwb3B0aW9ucyIsInRpdGxlIjoiVENQIGNvbm5lY3Rpb24gYWRkcmVzcy4ifSwiVW5peE9wdGlvbnMiOnsiaHJlZiI6IiN1bml4b3B0aW9ucyIsInRpdGxlIjoiVW5peCBkb21haW4gc29ja2V0IGFkZHJlc3MuIn19 type NetOptions = TCPOptions | UnixOptions; ``` ## TCPOptions TCP connection address. ```ts interface TCPOptions { // Hostname or IP address to connect to. host: string; // TCP port to connect to. port: number; } ``` ## UnixOptions Unix domain socket address. ```ts interface UnixOptions { // Filesystem path of the Unix domain socket. path: string; } ``` --- Source: https://rcompat.repopack.app/api/runtime # @rcompat/runtime API Runtime identity and process-level operations. Node, Bun, Deno, and browser implementations are selected through package export conditions. Browser imports are safe: identity, arguments, flags, platform fields, and memory queries have explicit browser values; process, filesystem, package, and module-resolution operations throw `unimplemented`. ```ts import runtime from "@rcompat/runtime"; import type { Flags, MemoryUsage, Resolve, Runtime, Unsubscribe, } from "@rcompat/runtime"; ``` ## runtime.name Current runtime name: `node`, `bun`, `deno`, or `browser`. ```ts runtime.name: string; ``` ## runtime.bin Runtime executable path, or an empty string in browsers. ```ts runtime.bin: string; ``` ## runtime.script Current script path or URL, or an empty string in browsers. ```ts runtime.script: string; ``` ## runtime.cwd Returns the current working directory as a file reference. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIvYXBpL2ZzI2ZpbGVyZWYiLCJ0aXRsZSI6IkEgcGF0aGxpYi1pbnNwaXJlZCByZWZlcmVuY2UgdG8gYSBmaWxlIG9yIGRpcmVjdG9yeS4ifX0 runtime.cwd: () => FileRef; ``` ## runtime.args Program arguments with the runtime and script entries removed. ```ts runtime.args: string[]; ``` ## runtime.exit Exits the process with an optional status code. **Throws:** In browsers, always throws `unimplemented`. ```ts runtime.exit: (code?: number) => never; ``` ## runtime.on Subscribe to current-process termination signals. Each registration, including duplicates, has its own idempotent unsubscribe function. **Throws:** In browsers, each method throws `unimplemented`. ```ts api-types=eyJVbnN1YnNjcmliZSI6eyJocmVmIjoiI3Vuc3Vic2NyaWJlIiwidGl0bGUiOiIoKSA9PiB2b2lkIn19 runtime.on: { // Subscribe to SIGINT. interrupt: (callback: () => void) => Unsubscribe; // Subscribe to SIGTERM. terminate: (callback: () => void) => Unsubscribe; // Subscribe to SIGHUP. hangup: (callback: () => void) => Unsubscribe; }; ``` ### runtime.on.interrupt Subscribe to SIGINT. ```ts api-types=eyJVbnN1YnNjcmliZSI6eyJocmVmIjoiI3Vuc3Vic2NyaWJlIiwidGl0bGUiOiIoKSA9PiB2b2lkIn19 runtime.on.interrupt: (callback: () => void) => Unsubscribe; ``` ### runtime.on.terminate Subscribe to SIGTERM. ```ts api-types=eyJVbnN1YnNjcmliZSI6eyJocmVmIjoiI3Vuc3Vic2NyaWJlIiwidGl0bGUiOiIoKSA9PiB2b2lkIn19 runtime.on.terminate: (callback: () => void) => Unsubscribe; ``` ### runtime.on.hangup Subscribe to SIGHUP. ```ts api-types=eyJVbnN1YnNjcmliZSI6eyJocmVmIjoiI3Vuc3Vic2NyaWJlIiwidGl0bGUiOiIoKSA9PiB2b2lkIn19 runtime.on.hangup: (callback: () => void) => Unsubscribe; ``` ## runtime.before Natural process lifecycle events. ```ts api-types=eyJOb3QiOnsiaHJlZiI6Ii9hcGkvdHlwZSNub3QiLCJ0aXRsZSI6IlQgZXh0ZW5kcyB0cnVlID8gZmFsc2UgOiB0cnVlIn0sIlVuc3Vic2NyaWJlIjp7ImhyZWYiOiIjdW5zdWJzY3JpYmUiLCJ0aXRsZSI6IigpID0-IHZvaWQifX0 runtime.before: { // Subscribe once to natural event-loop exhaustion. Removes the listener // before invoking the callback and keeps the process alive until its // returned promise settles. Consumers must bound cleanup and handle // errors. Not called for forced or explicit exits. exit: (callback: () => void | Promise) => Unsubscribe; }; ``` ### runtime.before.exit Subscribe once to natural event-loop exhaustion. Removes the listener before invoking the callback and keeps the process alive until its returned promise settles. Consumers must bound cleanup and handle errors. Not called for forced or explicit exits. **Throws:** In browsers, throws `unimplemented`. ```ts api-types=eyJVbnN1YnNjcmliZSI6eyJocmVmIjoiI3Vuc3Vic2NyaWJlIiwidGl0bGUiOiIoKSA9PiB2b2lkIn19 runtime.before.exit: (callback: () => void | Promise) => Unsubscribe; ``` ## runtime.interrupt Send SIGINT to this process without removing other listeners. Default termination requires all intercepting listeners to be removed first. **Throws:** In browsers, throws `unimplemented`. ```ts runtime.interrupt: () => void; ``` ## runtime.terminate Send SIGTERM; follows the same listener semantics as `interrupt`. ```ts runtime.terminate: () => void; ``` ## runtime.hangup Send SIGHUP; follows the same listener semantics as `interrupt`. ```ts runtime.hangup: () => void; ``` ## runtime.resolve Resolves a path or ESM package specifier from a directory. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJSZXNvbHZlIjp7ImhyZWYiOiIjcmVzb2x2ZSIsInRpdGxlIjoiKHNwZWNpZmllcjogc3RyaW5nLCBmcm9tOiBzdHJpbmcpID0-IHN0cmluZyJ9fQ runtime.resolve: Resolve; ``` ## runtime.toRequire Creates a CommonJS-compatible `require` function anchored at a path. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIvYXBpL2ZzI3BhdGgiLCJ0aXRsZSI6IkZpbGVSZWYgfCBVUkwgfCBzdHJpbmcifX0 runtime.toRequire: (path: Path) => NodeJS.Require; ``` ## runtime.packageJSON Reads the nearest project manifest. **Parameters** - `from` — Starting path; defaults to the current working directory. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJQYWNrYWdlSlNPTiI6eyJocmVmIjoiL2FwaS90eXBlI3BhY2thZ2Vqc29uIiwidGl0bGUiOiJBIHR5cGVkIG5wbS1jb21wYXRpYmxlIGBwYWNrYWdlLmpzb25gIG1hbmlmZXN0LiJ9LCJQYXRoIjp7ImhyZWYiOiIvYXBpL2ZzI3BhdGgiLCJ0aXRsZSI6IkZpbGVSZWYgfCBVUkwgfCBzdHJpbmcifX0 runtime.packageJSON: (from?: Path) => Promise; ``` ## runtime.projectRoot Finds the nearest ancestor containing `package.json`. **Parameters** - `from` — Starting path; defaults to the current working directory. **Returns:** A reference to the project directory. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJGaWxlUmVmIjp7ImhyZWYiOiIvYXBpL2ZzI2ZpbGVyZWYiLCJ0aXRsZSI6IkEgcGF0aGxpYi1pbnNwaXJlZCByZWZlcmVuY2UgdG8gYSBmaWxlIG9yIGRpcmVjdG9yeS4ifSwiUGF0aCI6eyJocmVmIjoiL2FwaS9mcyNwYXRoIiwidGl0bGUiOiJGaWxlUmVmIHwgVVJMIHwgc3RyaW5nIn19 runtime.projectRoot: (from?: Path) => Promise; ``` ## runtime.conditions Collects active CLI and TypeScript custom conditions without duplicates. Reads repeated `--conditions` flags and `compilerOptions.customConditions` from `tsconfig.json`, following string `extends` chains. Inherited TypeScript conditions precede local ones; circular chains throw. **Parameters** - `from` — Project directory; otherwise the project root is discovered. **Throws:** In browsers, always throws `unimplemented`. ```ts api-types=eyJQYXRoIjp7ImhyZWYiOiIvYXBpL2ZzI3BhdGgiLCJ0aXRsZSI6IkZpbGVSZWYgfCBVUkwgfCBzdHJpbmcifX0 runtime.conditions: (from?: Path) => Promise; ``` ## runtime.flags Parsed command-line flags; empty in browsers. ```ts api-types=eyJGbGFncyI6eyJocmVmIjoiI2ZsYWdzIiwidGl0bGUiOiJQYXJzZWQgY29tbWFuZC1saW5lIGZsYWdzLiJ9fQ runtime.flags: Flags; ``` ## runtime.os Operating system, or `undefined` when unavailable or unknown. ```ts api-types=eyJPUyI6eyJocmVmIjoiL2FwaS90eXBlI29zIiwidGl0bGUiOiJcImxpbnV4XCIgfCBcImRhcndpblwiIHwgXCJ3aW5kb3dzXCIifX0 runtime.os: OS | undefined; ``` ## runtime.arch CPU architecture, or `undefined` when unavailable or unknown. ```ts api-types=eyJBcmNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjYXJjaCIsInRpdGxlIjoiXCJ4NjRcIiB8IFwiYXJtNjRcIiJ9fQ runtime.arch: Arch | undefined; ``` ## runtime.memoryUsage Returns an instantaneous aggregate process-memory sample when available. Values are bytes. Node and Bun expose every field. Deno reports `arrayBuffers` as `undefined`. Browsers return `undefined` and do not use the non-standard Chromium-only `performance.memory` API. ```ts api-types=eyJNZW1vcnlVc2FnZSI6eyJocmVmIjoiI21lbW9yeXVzYWdlIiwidGl0bGUiOiJBZ2dyZWdhdGUgcHJvY2Vzcy1tZW1vcnkgdmFsdWVzIG1lYXN1cmVkIGluIGJ5dGVzLiJ9fQ runtime.memoryUsage: () => MemoryUsage | undefined; ``` ## Types ## Flags Parsed command-line flags. Extends [`Bag`](/api/type#bag) with `many()`, which returns every value supplied for a repeated key. Flags accept `--key=value`, `--key value`, and bare `--key` forms; a bare flag has an empty-string value. ```ts api-types=eyJCYWciOnsiaHJlZiI6Ii9hcGkvdHlwZSNiYWciLCJ0aXRsZSI6IkEgcmVhZGFibGUgc3RyaW5nLWtleWVkIHZhbHVlIGJhZy4ifX0 type Flags = Bag & { // Returns all values supplied for a key, in argument order. many(key: string): string[]; }; ``` ## MemoryUsage Aggregate process-memory values measured in bytes. ```ts interface MemoryUsage { // Resident set size, or `undefined` when unavailable. readonly rss: number | undefined; // Allocated JavaScript heap, or `undefined` when unavailable. readonly heapTotal: number | undefined; // Used JavaScript heap, or `undefined` when unavailable. readonly heapUsed: number | undefined; // Native memory attached to JavaScript objects, when available. readonly external: number | undefined; // Memory allocated for `ArrayBuffer` values, when available. readonly arrayBuffers: number | undefined; } ``` ## Resolve Resolves a path or ESM package specifier from a directory. Package resolution observes host import conditions and npm `exports`, `imports`, self references, and nested package ownership. **Parameters** - `specifier` — Relative path, absolute path, or package specifier. - `from` — Directory from which to resolve. **Returns:** The resolved filesystem path. ```ts type Resolve = (specifier: string, from: string) => string; ``` ## Runtime Runtime identity and process-level operations. Node, Bun, Deno, and browser implementations are selected through package export conditions. Browser imports are safe: identity, arguments, flags, platform fields, and memory queries have explicit browser values; process, filesystem, package, and module-resolution operations throw `unimplemented`. ```ts api-types=eyJBcmNoIjp7ImhyZWYiOiIvYXBpL3R5cGUjYXJjaCIsInRpdGxlIjoiXCJ4NjRcIiB8IFwiYXJtNjRcIiJ9LCJOb3QiOnsiaHJlZiI6Ii9hcGkvdHlwZSNub3QiLCJ0aXRsZSI6IlQgZXh0ZW5kcyB0cnVlID8gZmFsc2UgOiB0cnVlIn0sIk9TIjp7ImhyZWYiOiIvYXBpL3R5cGUjb3MiLCJ0aXRsZSI6IlwibGludXhcIiB8IFwiZGFyd2luXCIgfCBcIndpbmRvd3NcIiJ9LCJQYWNrYWdlSlNPTiI6eyJocmVmIjoiL2FwaS90eXBlI3BhY2thZ2Vqc29uIiwidGl0bGUiOiJBIHR5cGVkIG5wbS1jb21wYXRpYmxlIGBwYWNrYWdlLmpzb25gIG1hbmlmZXN0LiJ9LCJGaWxlUmVmIjp7ImhyZWYiOiIvYXBpL2ZzI2ZpbGVyZWYiLCJ0aXRsZSI6IkEgcGF0aGxpYi1pbnNwaXJlZCByZWZlcmVuY2UgdG8gYSBmaWxlIG9yIGRpcmVjdG9yeS4ifSwiUGF0aCI6eyJocmVmIjoiL2FwaS9mcyNwYXRoIiwidGl0bGUiOiJGaWxlUmVmIHwgVVJMIHwgc3RyaW5nIn0sIkZsYWdzIjp7ImhyZWYiOiIjZmxhZ3MiLCJ0aXRsZSI6IlBhcnNlZCBjb21tYW5kLWxpbmUgZmxhZ3MuIn0sIk1lbW9yeVVzYWdlIjp7ImhyZWYiOiIjbWVtb3J5dXNhZ2UiLCJ0aXRsZSI6IkFnZ3JlZ2F0ZSBwcm9jZXNzLW1lbW9yeSB2YWx1ZXMgbWVhc3VyZWQgaW4gYnl0ZXMuIn0sIlJlc29sdmUiOnsiaHJlZiI6IiNyZXNvbHZlIiwidGl0bGUiOiIoc3BlY2lmaWVyOiBzdHJpbmcsIGZyb206IHN0cmluZykgPT4gc3RyaW5nIn0sIlVuc3Vic2NyaWJlIjp7ImhyZWYiOiIjdW5zdWJzY3JpYmUiLCJ0aXRsZSI6IigpID0-IHZvaWQifX0 interface Runtime { // Current runtime name: `node`, `bun`, `deno`, or `browser`. name: string; // Runtime executable path, or an empty string in browsers. bin: string; // Current script path or URL, or an empty string in browsers. script: string; // Returns the current working directory as a file reference. cwd: () => FileRef; // Program arguments with the runtime and script entries removed. args: string[]; // Exits the process with an optional status code. exit: (code?: number) => never; // Subscribe to current-process termination signals. Each registration, // including duplicates, has its own idempotent unsubscribe function. on: { // Subscribe to SIGINT. interrupt: (callback: () => void) => Unsubscribe; // Subscribe to SIGTERM. terminate: (callback: () => void) => Unsubscribe; // Subscribe to SIGHUP. hangup: (callback: () => void) => Unsubscribe; }; // Natural process lifecycle events. before: { // Subscribe once to natural event-loop exhaustion. Removes the listener // before invoking the callback and keeps the process alive until its // returned promise settles. Consumers must bound cleanup and handle // errors. Not called for forced or explicit exits. exit: (callback: () => void | Promise) => Unsubscribe; }; // Send SIGINT to this process without removing other listeners. Default // termination requires all intercepting listeners to be removed first. interrupt: () => void; // Send SIGTERM; follows the same listener semantics as `interrupt`. terminate: () => void; // Send SIGHUP; follows the same listener semantics as `interrupt`. hangup: () => void; // Resolves a path or ESM package specifier from a directory. resolve: Resolve; // Creates a CommonJS-compatible `require` function anchored at a path. toRequire: (path: Path) => NodeJS.Require; // Reads the nearest project manifest. packageJSON: (from?: Path) => Promise; // Finds the nearest ancestor containing `package.json`. projectRoot: (from?: Path) => Promise; // Collects active CLI and TypeScript custom conditions without duplicates. conditions: (from?: Path) => Promise; // Parsed command-line flags; empty in browsers. flags: Flags; // Operating system, or `undefined` when unavailable or unknown. os: OS | undefined; // CPU architecture, or `undefined` when unavailable or unknown. arch: Arch | undefined; // Returns an instantaneous aggregate process-memory sample when available. memoryUsage: () => MemoryUsage | undefined; } ``` ## Unsubscribe Removes one lifecycle callback; safe to call more than once. ```ts type Unsubscribe = () => void; ``` --- Source: https://rcompat.repopack.app/api/source-map # @rcompat/source-map API Portable Source Map v3 consumption across browsers, Node, Deno, and Bun. Server runtimes use native source-map lookup after shared validation; browsers use the shared decoder directly. Every runtime returns the same normalized public result. ```ts import SourceMap from "@rcompat/source-map"; import type { OriginalPosition, SourceMapPayload, } from "@rcompat/source-map"; ``` ## SourceMap A validated Source Map v3 consumer. ```ts declare class SourceMap {} ``` ### Constructor #### new SourceMap() Creates a source-map consumer from an object or serialized JSON. **Parameters** - `input` — Source Map v3 payload or its JSON representation. **Throws:** `TypeError` when the payload or encoded mappings are invalid. ```ts api-types=eyJTb3VyY2VNYXBQYXlsb2FkIjp7ImhyZWYiOiIjc291cmNlbWFwcGF5bG9hZCIsInRpdGxlIjoiQSBTb3VyY2UgTWFwIHYzIHBheWxvYWQgYWNjZXB0ZWQgYnkgYFNvdXJjZU1hcGAuIn19 new SourceMap(input: SourceMapPayload | string) ``` ### Instance methods #### sourceMap.original() Finds the original position for a generated position. Inputs and returned coordinates are one-based. The closest preceding segment on the same generated line applies until the next segment. Invalid positions, missing lines, and unmapped segments return `undefined`. Relative sources are resolved against `sourceRoot`; absolute source URLs remain unchanged. `name` appears only when the selected segment explicitly carries one. **Parameters** - `line` — One-based generated line. - `column` — One-based generated column. **Returns:** The normalized original position, or `undefined` when unmapped. ```ts api-types=eyJPcmlnaW5hbFBvc2l0aW9uIjp7ImhyZWYiOiIjb3JpZ2luYWxwb3NpdGlvbiIsInRpdGxlIjoiQSBvbmUtYmFzZWQgb3JpZ2luYWwgc291cmNlIHBvc2l0aW9uLiJ9fQ sourceMap.original(line: number, column: number): OriginalPosition | undefined ``` **Example** ```ts const map = new SourceMap({ version: 3, sources: ["input.ts"], names: [], mappings: "AAAA", }); map.original(1, 1); // { source: "input.ts", line: 1, column: 1 } ``` ## Types ## OriginalPosition A one-based original source position. ```ts type OriginalPosition = { // One-based original column. column: number; // One-based original line. line: number; // Name attached explicitly to the selected mapping segment. name?: string; // Original source after applying `sourceRoot`, when present. source: string; }; ``` ## SourceMapPayload A Source Map v3 payload accepted by `SourceMap`. ```ts type SourceMapPayload = { // Generated filename associated with the map. file?: string; // Base64 VLQ-encoded mapping segments. mappings: string; // Optional names referenced by mapping segments. names?: string[]; // Optional root resolved against relative source entries. sourceRoot?: string; // Original source paths or URLs. sources: string[]; // Optional source contents aligned one-to-one with `sources`. sourcesContent?: (string | null)[]; // Source map format version; only version 3 is supported. version: 3; }; ``` --- Source: https://rcompat.repopack.app/api/sqlite # @rcompat/sqlite API Synchronous SQLite access across Node, Deno, and Bun. Node and Deno use `node:sqlite`; Bun uses `bun:sqlite`. Browser bundles can import the package, but constructing `Database` throws because no portable browser SQLite implementation is provided. ```ts import Database from "@rcompat/sqlite"; import type { Changes, Options, Param, PrimitiveParam, Statement, } from "@rcompat/sqlite"; ``` ## Database A synchronous SQLite database connection. ```ts declare class Database {} ``` ### Constructor #### new Database() Opens a file-backed or in-memory SQLite database. **Parameters** - `path` — Database path or `:memory:`. - `options` — Read-only and safe-integer options. ```ts api-types=eyJPcHRpb25zIjp7ImhyZWYiOiIjb3B0aW9ucyIsInRpdGxlIjoiT3B0aW9ucyB1c2VkIHdoZW4gb3BlbmluZyBhIGRhdGFiYXNlLiJ9fQ new Database(path: string, options?: Options) ``` ### Database methods #### database.close() Closes the database connection. Repeated calls are safe and have no additional effect. ```ts database.close(): void; ``` #### database.prepare() Compiles SQL into a reusable statement. **Parameters** - `sql` — SQL statement to prepare. ```ts api-types=eyJTdGF0ZW1lbnQiOnsiaHJlZiI6IiNzdGF0ZW1lbnQiLCJ0aXRsZSI6IkEgcmV1c2FibGUgcHJlcGFyZWQgU1FMaXRlIHN0YXRlbWVudC4ifX0 database.prepare(sql: string): Statement; ``` #### database.exec() Executes SQL once and returns its change metadata. Parameters may be supplied as positional primitive values or as one named parameter dictionary. Named keys retain their `$`, `@`, or `:` prefix. **Parameters** - `sql` — SQL statement to execute. - `first` — First positional value or the named parameter dictionary. - `rest` — Remaining positional values. ```ts api-types=eyJDaGFuZ2VzIjp7ImhyZWYiOiIjY2hhbmdlcyIsInRpdGxlIjoiTWV0YWRhdGEgcmV0dXJuZWQgYWZ0ZXIgZXhlY3V0aW5nIGEgc3RhdGVtZW50LiJ9LCJQYXJhbSI6eyJocmVmIjoiI3BhcmFtIiwidGl0bGUiOiJEaWN0PFByaW1pdGl2ZVBhcmFtPiB8IFByaW1pdGl2ZVBhcmFtIn0sIlByaW1pdGl2ZVBhcmFtIjp7ImhyZWYiOiIjcHJpbWl0aXZlcGFyYW0iLCJ0aXRsZSI6ImJpZ2ludCB8IG51bGwgfCBudW1iZXIgfCBzdHJpbmcgfCBVaW50OEFycmF5In19 database.exec( sql: string, first?: Param, ...rest: PrimitiveParam[] ): Changes ``` **Example** ```ts const database = new Database(":memory:"); database.exec("CREATE TABLE users (name TEXT)"); database.exec("INSERT INTO users VALUES (?)", "Ada"); const row = database.prepare("SELECT name FROM users").get(); // row is { name: "Ada" } ``` ## Types ## Changes Metadata returned after executing a statement. ```ts interface Changes { // Number of rows changed by the statement. changes: bigint | number; // Row ID of the most recent insertion. lastInsertRowid: bigint | number; } ``` ## Options Options used when opening a database. ```ts type Options = { // Opens the database without write access. // Default: `false` readonly?: boolean; // Returns SQLite integers as `bigint`. // Default: `false` safeIntegers?: boolean; }; ``` ## Param A positional value or dictionary of named parameter values. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIvYXBpL3R5cGUjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiUHJpbWl0aXZlUGFyYW0iOnsiaHJlZiI6IiNwcmltaXRpdmVwYXJhbSIsInRpdGxlIjoiYmlnaW50IHwgbnVsbCB8IG51bWJlciB8IHN0cmluZyB8IFVpbnQ4QXJyYXkifX0 type Param = Dict | PrimitiveParam; ``` ## PrimitiveParam A primitive value accepted by SQLite parameter bindings. ```ts type PrimitiveParam = | bigint | null | number | string | Uint8Array; ``` ## Statement A reusable prepared SQLite statement. ```ts declare abstract class Statement {} ``` ### Statement methods #### statement.close() Releases this prepared statement. Repeated calls are safe and have no additional effect. `get()`, `all()`, and `run()` throw after the statement is closed. ```ts statement.close(): void; ``` #### statement.get() Returns the first matching row or `null` when no row matches. **Type parameters** - `T` — Expected row shape. **Parameters** - `first` — First positional value or the named parameter dictionary. - `rest` — Remaining positional values. ```ts api-types=eyJQYXJhbSI6eyJocmVmIjoiI3BhcmFtIiwidGl0bGUiOiJEaWN0PFByaW1pdGl2ZVBhcmFtPiB8IFByaW1pdGl2ZVBhcmFtIn0sIlByaW1pdGl2ZVBhcmFtIjp7ImhyZWYiOiIjcHJpbWl0aXZlcGFyYW0iLCJ0aXRsZSI6ImJpZ2ludCB8IG51bGwgfCBudW1iZXIgfCBzdHJpbmcgfCBVaW50OEFycmF5In19 statement.get( first?: Param, ...rest: PrimitiveParam[] ): T | null; ``` #### statement.all() Returns all matching rows. **Type parameters** - `T` — Expected row shape. **Parameters** - `first` — First positional value or the named parameter dictionary. - `rest` — Remaining positional values. ```ts api-types=eyJQYXJhbSI6eyJocmVmIjoiI3BhcmFtIiwidGl0bGUiOiJEaWN0PFByaW1pdGl2ZVBhcmFtPiB8IFByaW1pdGl2ZVBhcmFtIn0sIlByaW1pdGl2ZVBhcmFtIjp7ImhyZWYiOiIjcHJpbWl0aXZlcGFyYW0iLCJ0aXRsZSI6ImJpZ2ludCB8IG51bGwgfCBudW1iZXIgfCBzdHJpbmcgfCBVaW50OEFycmF5In19 statement.all(first?: Param, ...rest: PrimitiveParam[]): T[]; ``` #### statement.run() Executes the statement and returns its change metadata. **Parameters** - `first` — First positional value or the named parameter dictionary. - `rest` — Remaining positional values. ```ts api-types=eyJDaGFuZ2VzIjp7ImhyZWYiOiIjY2hhbmdlcyIsInRpdGxlIjoiTWV0YWRhdGEgcmV0dXJuZWQgYWZ0ZXIgZXhlY3V0aW5nIGEgc3RhdGVtZW50LiJ9LCJQYXJhbSI6eyJocmVmIjoiI3BhcmFtIiwidGl0bGUiOiJEaWN0PFByaW1pdGl2ZVBhcmFtPiB8IFByaW1pdGl2ZVBhcmFtIn0sIlByaW1pdGl2ZVBhcmFtIjp7ImhyZWYiOiIjcHJpbWl0aXZlcGFyYW0iLCJ0aXRsZSI6ImJpZ2ludCB8IG51bGwgfCBudW1iZXIgfCBzdHJpbmcgfCBVaW50OEFycmF5In19 statement.run(first?: Param, ...rest: PrimitiveParam[]): Changes; ``` --- Source: https://rcompat.repopack.app/api/string # @rcompat/string API Browser-safe utilities for transforming, matching, and measuring strings. These utilities have no runtime-native dependencies and work in current browsers, Node, Deno, and Bun. ```ts import string from "@rcompat/string"; ``` ## string.Base64 UTF-8 Base64 encoding and decoding operations. ```ts api-types=eyJCYXNlNjRVdGlsaXRpZXMiOnsiaHJlZiI6IiNiYXNlNjR1dGlsaXRpZXMiLCJ0aXRsZSI6IlVURi04IEJhc2U2NCBlbmNvZGluZyBhbmQgZGVjb2Rpbmcgb3BlcmF0aW9ucy4ifX0 string.Base64: Base64Utilities; ``` ### Base64 methods #### string.Base64.encode() Encodes a string's UTF-8 bytes as Base64. **Parameters** - `decoded` — String to encode. ```ts string.Base64.encode(decoded: string): string; ``` #### string.Base64.decode() Decodes Base64 bytes as a UTF-8 string. **Parameters** - `encoded` — Base64 string to decode. ```ts string.Base64.decode(encoded: string): string; ``` ## string.dedent Removes common indentation and trims a string or tagged template. Interpolated values are string-coerced. Escaped newlines are removed and escaped backticks are restored before indentation is calculated. **Parameters** - `strings` — String value or template segments. - `values` — Tagged-template interpolation values. ```ts api-types=eyJUZW1wbGF0ZVN0cmluZ3MiOnsiaHJlZiI6IiN0ZW1wbGF0ZXN0cmluZ3MiLCJ0aXRsZSI6InN0cmluZyB8IFRlbXBsYXRlU3RyaW5nc0FycmF5In19 string.dedent(strings: TemplateStrings, ...values: unknown[]): string; ``` **Example** ```ts const name = "Ada"; string.dedent` Hello, ${name}. Welcome back. `; // "Hello, Ada.\nWelcome back." ``` ## string.glob Compiles a whole-string glob pattern to a Unicode regular expression. `*` excludes `/`, `**` includes `/`, and `**` followed by `/` matches zero or more path segments. `?` matches one character, and bracket classes and ranges are supported. Other regular-expression syntax is escaped. Input validation is consistent with [`assert.string()`](/api/assert#assert-string). **Parameters** - `pattern` — Glob pattern to compile. **Returns:** An anchored regular expression. ```ts string.glob(pattern: string): RegExp; ``` **Example** ```ts string.glob("src/**.ts").test("src/private/index.ts"); // true ``` ## string.semver Tests whether a concrete semantic version satisfies a version range. Malformed inputs return false. Build metadata is ignored when matching. ```ts string.semver(version: string, range: string): boolean; ``` ## string.toCamelCase Converts hyphen- or underscore-separated text to camel case. The complete input is lowercased first. Repeated and surrounding separators are ignored. **Parameters** - `string` — Text to convert. ```ts string.toCamelCase(string: string): string; ``` ## string.toSlug Converts text to a lowercase ASCII URL slug. Latin diacritics are removed, non-ASCII characters are discarded, and runs of remaining punctuation or whitespace become one `-`. **Parameters** - `string` — Text to convert. ```ts string.toSlug(string: string): string; ``` ## string.upperfirst Uppercases the first character and leaves the remainder unchanged. **Parameters** - `string` — Text to transform. ```ts string.upperfirst(string: string): string; ``` ## string.utf8 UTF-8 byte-size operations. ```ts api-types=eyJVdGY4VXRpbGl0aWVzIjp7ImhyZWYiOiIjdXRmOHV0aWxpdGllcyIsInRpdGxlIjoiVVRGLTggYnl0ZS1zaXplIG9wZXJhdGlvbnMuIn19 string.utf8: Utf8Utilities; ``` ### UTF-8 methods #### string.utf8.bytelength() Returns UTF-8 byte length by encoding the string with `TextEncoder`. **Parameters** - `string` — String to measure. ```ts string.utf8.bytelength(string: string): number; ``` #### string.utf8.size() Calculates UTF-8 byte size directly without allocating an encoded array. **Parameters** - `string` — String to measure. ```ts string.utf8.size(string: string): number; ``` ## Supporting contracts ### Base64Utilities UTF-8 Base64 encoding and decoding operations. ```ts interface Base64Utilities { // Encodes a string's UTF-8 bytes as Base64. encode(decoded: string): string; // Decodes Base64 bytes as a UTF-8 string. decode(encoded: string): string; } ``` ### Utf8Utilities UTF-8 byte-size operations. ```ts interface Utf8Utilities { // Returns UTF-8 byte length by encoding the string with `TextEncoder`. bytelength(string: string): number; // Calculates UTF-8 byte size directly without allocating an encoded array. size(string: string): number; } ``` ### TemplateStrings String or template segments accepted by `string.dedent`. ```ts type TemplateStrings = string | TemplateStringsArray; ``` --- Source: https://rcompat.repopack.app/api/test # @rcompat/test API Test registration, assertions, spies, fetch interception, and test-runner integration for Node, Deno, and Bun. Module mocking requires Node.js `module.registerHooks`. Browser bundles can import the package and use `test.config`; accessing any other root utility throws because test registration is unavailable. ```ts import test from "@rcompat/test"; import type { Asserter, Env, ExtendedTest, Repository, Result, Test, TestConfig, TestRun, } from "@rcompat/test"; ``` ## test.case Registers a named test case in the current suite. ```ts api-types=eyJCb2R5Ijp7ImhyZWYiOiIjYm9keSIsInRpdGxlIjoiKGFzc2VydGVyOiBBc3NlcnRlcikgPT4gTWF5YmVQcm9taXNlPHZvaWQ-In19 test.case(name: string, body: Body): void; ``` ## test.ended Registers cleanup to run after all cases in the current file. ```ts api-types=eyJFbmQiOnsiaHJlZiI6IiNlbmQiLCJ0aXRsZSI6IigpID0-IE1heWJlUHJvbWlzZTx2b2lkPiJ9fQ test.ended(end: End): void; ``` ## test.group Registers cases under a group that Proby can target by name. ```ts test.group(name: string, fn: () => void): void; ``` ## test.mock Registers tracked replacement exports for a module. Module mocking requires Node.js `module.registerHooks`. Calls are cleared between test cases when the mock belongs to the active repository suite. **Parameters** - `specifier` — Module specifier to intercept. - `factory` — Creates replacement exports. **Returns:** Tracked exports and restoration controls. **Throws:** When module hooks are unavailable in the active runtime. ```ts api-types=eyJNb2NrSGFuZGxlIjp7ImhyZWYiOiIjbW9ja2hhbmRsZSIsInRpdGxlIjoiVHJhY2tlZCBtb2R1bGUgZXhwb3J0cyBhbmQgcmVzdG9yYXRpb24gY29udHJvbHMuIn19 test.mock( specifier: string, factory: (original: unknown) => T, ): MockHandle; ``` ## test.spy Wraps a function and records every call. **Parameters** - `fn` — Original implementation and function type. - `mocker` — Optional replacement implementation. **Returns:** A callable tracker with `calls` and `called` properties. ```ts api-types=eyJBbnlGdW5jdGlvbiI6eyJocmVmIjoiI2FueWZ1bmN0aW9uIiwidGl0bGUiOiIoLi4uYXJnczogYW55W10pID0-IGFueSJ9LCJUcmFja2VkIjp7ImhyZWYiOiIjdHJhY2tlZCIsInRpdGxlIjoiQSBmdW5jdGlvbiBhdWdtZW50ZWQgd2l0aCBpdHMgcmVjb3JkZWQgY2FsbHMgYW5kIGNhbGxlZCBzdGF0ZS4ifX0 test.spy( fn: F, mocker?: F, ): Tracked; ``` ## test.import Dynamically imports a module after mocks have been registered. **Parameters** - `specifier` — Module specifier to import. ```ts test.import(specifier: string): Promise; ``` ## test.intercept Intercepts fetch requests to one origin and records matched requests. **Parameters** - `base_url` — Origin to intercept. - `setup` — Callback that registers path handlers by HTTP method. **Returns:** Recorded requests and restoration controls. **Throws:** When the intercepted origin receives an unregistered route. ```ts api-types=eyJJbnRlcmNlcHQiOnsiaHJlZiI6IiNpbnRlcmNlcHQiLCJ0aXRsZSI6IlJlY29yZGVkIHJlcXVlc3RzIGFuZCByZXN0b3JhdGlvbiBjb250cm9scyBmb3IgYW4gaW50ZXJjZXB0LiJ9LCJTZXR1cCI6eyJocmVmIjoiI3NldHVwIiwidGl0bGUiOiJSb3V0ZS1yZWdpc3RyYXRpb24gbWV0aG9kcyBwYXNzZWQgdG8gYW4gaW50ZXJjZXB0IHNldHVwIGNhbGxiYWNrLiJ9fQ test.intercept( base_url: string, setup: (setup: Setup) => void, ): Intercept; ``` ## test.any Casts a value to `never` for compile-time negative tests. **Parameters** - `value` — Value to cast without runtime validation. **Returns:** The same runtime value, typed as `never`. ```ts test.any(value: unknown): never; ``` ## test.config Returns a type-checked test-runner configuration unchanged. **Parameters** - `input` — Test discovery and preload options. **Returns:** The original configuration object. ```ts api-types=eyJUZXN0Q29uZmlnIjp7ImhyZWYiOiIjdGVzdGNvbmZpZyIsInRpdGxlIjoiVGVzdC1ydW5uZXIgY29uZmlndXJhdGlvbiBhY2NlcHRlZCBieSBgdGVzdC5jb25maWdgLiJ9LCJFeGFjdCI6eyJocmVmIjoiI2V4YWN0IiwidGl0bGUiOiJDb25maWcgJiBSZWNvcmQ8IEV4Y2x1ZGU8a2V5b2YgQ29uZmlnLCBrZXlvZiBUZXN0Q29uZmlnPiwgbmV2ZXIgPiJ9fQ test.config( input: Exact, ): Config; ``` ## test.E Casts a caught value to the error shape used in tests. This helper performs no runtime validation. ```ts api-types=eyJFbmNvZGVkRXJyb3IiOnsiaHJlZiI6IiNlbmNvZGVkZXJyb3IiLCJ0aXRsZSI6IkVycm9yIHNoYXBlIHVzZWQgYnkgdGVzdCBhc3NlcnRpb25zLiJ9fQ test.E(error: unknown): EncodedError; ``` ## test.equals Tests deep equality across supported primitive and structured values. ```ts test.equals(x: T, y: T): boolean; ``` ## test.extend Creates an aggregate whose asserter includes custom methods. ```ts api-types=eyJFeHRlbmRlZFRlc3QiOnsiaHJlZiI6IiNleHRlbmRlZHRlc3QiLCJ0aXRsZSI6IlRlc3QgYWdncmVnYXRlIHdpdGggY3VzdG9tIGFzc2VydGlvbiBtZXRob2RzIGFuZCB0aGUgYmFzZSB1dGlsaXRpZXMuIn0sIkZhY3RvcnkiOnsiaHJlZiI6IiNmYWN0b3J5IiwidGl0bGUiOiIoYXNzZXJ0OiBBc3NlcnRlciwgc3ViamVjdDogU3ViamVjdCkgPT4gRXh0ZW5zaW9ucyJ9fQ test.extend( factory: Factory, ): ExtendedTest; ``` ## test.includes Tests deep inclusion across strings and supported structured values. ```ts test.includes(x: T, y: T): boolean; ``` ## test.repository Suite repository used by test runners to register and execute files. ```ts api-types=eyJSZXBvc2l0b3J5Ijp7ImhyZWYiOiIjcmVwb3NpdG9yeSIsInRpdGxlIjoiU3VpdGUgcmVwb3NpdG9yeSB1c2VkIGJ5IHRlc3QgcnVubmVycyB0byByZWdpc3RlciBhbmQgZXhlY3V0ZSBmaWxlcy4ifX0 test.repository: Repository; ``` ## test.undef Pre-cast `undefined` typed as `never` for negative tests. ```ts test.undef: never; ``` ## Types ## Asserter Creates a fluent assertion for an optional actual value. ```ts api-types=eyJBc3NlcnQiOnsiaHJlZiI6IiNhc3NlcnQiLCJ0aXRsZSI6IkZsdWVudCBydW50aW1lIGFuZCBjb21waWxlLXRpbWUgYXNzZXJ0aW9ucyBmb3IgYW4gYWN0dWFsIHZhbHVlLiJ9fQ type Asserter = (actual?: T) => Assert; ``` ## Env Per-file environment hooks consumed by Proby from sibling `.env.ts` files. ```ts type Env = { // Returns globals to install while the suite runs. globals(context: C): object; // Creates optional context before the suite runs. setup?(): MaybePromise; // Cleans up the context after the suite ends. teardown?(context: C): MaybePromise; }; ``` ## ExtendedTest Test aggregate with custom assertion methods and the base utilities. ```ts api-types=eyJFeHRlbmRlZEJvZHkiOnsiaHJlZiI6IiNleHRlbmRlZGJvZHkiLCJ0aXRsZSI6Iihhc3NlcnRlcjogRXh0ZW5kZWRBc3NlcnRlcjxFeHRlbnNpb25zPikgPT4gTWF5YmVQcm9taXNlPHZvaWQ-In0sIkZhY3RvcnkiOnsiaHJlZiI6IiNmYWN0b3J5IiwidGl0bGUiOiIoYXNzZXJ0OiBBc3NlcnRlciwgc3ViamVjdDogU3ViamVjdCkgPT4gRXh0ZW5zaW9ucyJ9LCJGb3J3YXJkZWQiOnsiaHJlZiI6IiNmb3J3YXJkZWQiLCJ0aXRsZSI6Ik9taXQ8QmFzZSwgXCJjYXNlXCI-In19 type ExtendedTest = Forwarded & { // Registers a case receiving the extended asserter. case(name: string, body: ExtendedBody): void; // Composes another set of assertion methods. extend( factory: Factory, ): ExtendedTest; }; ``` ## Repository Suite repository used by test runners to register and execute files. ```ts api-types=eyJCb2R5Ijp7ImhyZWYiOiIjYm9keSIsInRpdGxlIjoiKGFzc2VydGVyOiBBc3NlcnRlcikgPT4gTWF5YmVQcm9taXNlPHZvaWQ-In0sIkVuZCI6eyJocmVmIjoiI2VuZCIsInRpdGxlIjoiKCkgPT4gTWF5YmVQcm9taXNlPHZvaWQ-In0sIlJlcG9zaXRvcnlTdWl0ZSI6eyJocmVmIjoiI3JlcG9zaXRvcnlzdWl0ZSIsInRpdGxlIjoiQSByZWdpc3RlcmVkIGZpbGUgc3VpdGUgZXhwb3NlZCB0byB0ZXN0LXJ1bm5lciBpbnRlZ3JhdGlvbnMuIn19 interface Repository { // Registered replacement modules. readonly mocks: Map; // Registers work to run between test cases. between(fn: () => void): void; // Registers cleanup for the current suite. ended(end: End): void; // Runs registrations under a named group. group(name: string, fn: () => void): void; // Iterates registered suites. next(): Generator; // Adds a named case to the current suite. put(name: string, body: Body): void; // Clears suites and registered mocks. reset(): void; // Starts registration for a spec file. suite(file: FileRef): void; } ``` ## Result One recorded assertion result. **Type parameters** - `T` — Type shared by the actual and expected values. `class Result` is exported as a type. ### Result members #### Result instance: actual Actual value observed by the assertion. ```ts get actual(): T; ``` #### Result instance: expected Expected value recorded by the assertion. ```ts get expected(): T; ``` #### Result instance: passed Whether the assertion passed. ```ts get passed(): boolean; ``` ## Test A registered test case and its assertion results. `class Test` is exported as a type. ### Test members #### Test instance: name Test case name. ```ts get name(): string; ``` #### Test instance: group Optional registration group. ```ts get group(): string | undefined; ``` #### Test instance: results Assertion results recorded while the case ran. ```ts api-types=eyJSZXN1bHQiOnsiaHJlZiI6IiNyZXN1bHQiLCJ0aXRsZSI6Ik9uZSByZWNvcmRlZCBhc3NlcnRpb24gcmVzdWx0LiJ9fQ get results(): Result[]; ``` #### Test instance: report Records one assertion result. ```ts report(actual: T, expected: T, passed: boolean): void; ``` #### Test instance: run Executes the test body and returns this completed test. ```ts run(): Promise; ``` ## TestConfig Test-runner configuration accepted by `test.config`. ```ts interface TestConfig { // Directories searched for spec files. // Default: `["src", "test"]` include?: readonly string[]; // Modules preloaded before test files run. // Default: `[]` loaders?: readonly string[]; // Whether package directories are scanned as a monorepo. // Default: `false` monorepo?: boolean; // Package directory resolved from the project root. // Default: `"packages"` packages?: string; } ``` ## TestRun One completed test and its execution duration. ```ts api-types=eyJUZXN0Ijp7ImhyZWYiOiIjdGVzdCIsInRpdGxlIjoiQSByZWdpc3RlcmVkIHRlc3QgY2FzZSBhbmQgaXRzIGFzc2VydGlvbiByZXN1bHRzLiJ9fQ type TestRun = { // Execution time in milliseconds. duration: number; // Completed test and assertion results. test: Test; }; ``` ## Supporting contracts ### Assert Fluent runtime and compile-time assertions for an actual value. **Type parameters** - `Actual` — Inferred actual value or compile-time type. `Assert` instances are created by an `Asserter`. #### Assert members #### Assert.not Negates the next runtime assertion. ```ts get not(): this; ``` **Example** ```ts assert(false).not.true(); // passes ``` #### Assert.equals Records whether the actual and expected values are deeply equal. ```ts equals(expected: unknown): this; ``` **Example** ```ts assert({ ready: true }).equals({ ready: true }); // passes ``` #### Assert.nequals Records whether the actual and expected values are not deeply equal. ```ts nequals(expected: unknown): this; ``` **Example** ```ts assert(1).nequals(2); // passes ``` #### Assert.includes Records string substring or array member inclusion. ```ts includes(expected: unknown): this; ``` **Example** ```ts assert("standard").includes("and"); // passes ``` #### Assert.type Records a pass when the actual and expected compile-time types match. ```ts api-types=eyJFcXVhbHMiOnsiaHJlZiI6IiNlcXVhbHMiLCJ0aXRsZSI6Iig8VD4oKSA9PiBUIGV4dGVuZHMgWCA_IHRydWUgOiBmYWxzZSkgZXh0ZW5kcyA8VD4oKSA9PiBUIGV4dGVuZHMgWSA_IHRydWUgOiBmYWxzZSA_IHRydWUgOiBmYWxzZSJ9fQ type extends true ? unknown : Print>(_expected?: Expected): this; ``` **Example** ```ts assert("ready").type(); // passes ``` #### Assert.nottype Constrains the actual and expected compile-time types to differ. ```ts api-types=eyJFcXVhbHMiOnsiaHJlZiI6IiNlcXVhbHMiLCJ0aXRsZSI6Iig8VD4oKSA9PiBUIGV4dGVuZHMgWCA_IHRydWUgOiBmYWxzZSkgZXh0ZW5kcyA8VD4oKSA9PiBUIGV4dGVuZHMgWSA_IHRydWUgOiBmYWxzZSA_IHRydWUgOiBmYWxzZSJ9fQ nottype> extends true ? unknown : "actual and expected types are same">(_expected?: Expected): this; ``` **Example** ```ts assert<"ready">().nottype<"waiting">(); // type-checks ``` #### Assert.true Records whether the actual value is exactly `true`. ```ts true(): this; ``` **Example** ```ts assert(true).true(); // passes ``` #### Assert.false Records whether the actual value is exactly `false`. ```ts false(): this; ``` **Example** ```ts assert(false).false(); // passes ``` #### Assert.null Records whether the actual value is `null`. ```ts null(): this; ``` **Example** ```ts assert(null).null(); // passes ``` #### Assert.undefined Records whether the actual value is `undefined`. ```ts undefined(): this; ``` **Example** ```ts assert(undefined).undefined(); // passes ``` #### Assert.defined Records whether the actual value is not `undefined`. ```ts defined(): this; ``` **Example** ```ts assert(null).defined(); // passes ``` #### Assert.instance Records whether the actual value is an instance of a constructor. ```ts instance(expected: UnknownFunction): this; ``` **Example** ```ts assert(new Date()).instance(Date); // passes ``` #### Assert.throws Records whether the asserted callback throws or rejects as expected. Async callbacks return a promise and must be awaited. ```ts api-types=eyJBc3NlcnRpb25SZXN1bHQiOnsiaHJlZiI6IiNhc3NlcnRpb25yZXN1bHQiLCJ0aXRsZSI6IkFzeW5jIGFzc2VydGlvbiByZXN1bHQgc2VsZWN0ZWQgZnJvbSB0aGUgYXNzZXJ0ZWQgY2FsbGJhY2sncyByZXR1cm4gdHlwZS4ifSwiRXhwZWN0ZWRFcnJvciI6eyJocmVmIjoiI2V4cGVjdGVkZXJyb3IiLCJ0aXRsZSI6InN0cmluZyB8IChuZXcgKC4uLmFyZ3M6IGFueVtdKSA9PiBFcnJvcikgfCB1bmRlZmluZWQifX0 throws(expected?: ExpectedError): AssertionResult; ``` **Example** ```ts assert(() => { throw new TypeError("invalid"); }).throws(TypeError); // passes ``` #### Assert.tries Records whether the asserted callback returns or resolves successfully. Async callbacks return a promise and must be awaited. ```ts api-types=eyJBc3NlcnRpb25SZXN1bHQiOnsiaHJlZiI6IiNhc3NlcnRpb25yZXN1bHQiLCJ0aXRsZSI6IkFzeW5jIGFzc2VydGlvbiByZXN1bHQgc2VsZWN0ZWQgZnJvbSB0aGUgYXNzZXJ0ZWQgY2FsbGJhY2sncyByZXR1cm4gdHlwZS4ifX0 tries(): AssertionResult; ``` **Example** ```ts assert(() => 42).tries(); // passes ``` #### Assert.pass Records an unconditional passing assertion. ```ts pass(): void; ``` **Example** ```ts assert().pass(); // passes ``` #### Assert.fail Marks an intentional compile-time failure or records a runtime failure. ```ts api-types=eyJFcXVhbHMiOnsiaHJlZiI6IiNlcXVhbHMiLCJ0aXRsZSI6Iig8VD4oKSA9PiBUIGV4dGVuZHMgWCA_IHRydWUgOiBmYWxzZSkgZXh0ZW5kcyA8VD4oKSA9PiBUIGV4dGVuZHMgWSA_IHRydWUgOiBmYWxzZSA_IHRydWUgOiBmYWxzZSJ9fQ fail> extends true ? unknown : "was supposed to fail but didn't">(): void; fail(reason: string): void; ``` **Example** ```ts assert("actual").fail("expected another value"); // fails ``` ### AssertionResult Async assertion result selected from the asserted callback's return type. ```ts type AssertionResult = Actual extends (...args: any[]) => infer Return ? Return extends PromiseLike ? Promise : Assertion : Assertion; ``` ### Base Root methods forwarded to an extended test aggregate. ```ts api-types=eyJCb2R5Ijp7ImhyZWYiOiIjYm9keSIsInRpdGxlIjoiKGFzc2VydGVyOiBBc3NlcnRlcikgPT4gTWF5YmVQcm9taXNlPHZvaWQ-In19 type Base = { case(name: string, body: Body): void; ended(end: () => MaybePromise): void; group(name: string, fn: () => void): void; mock: typeof mock; spy: typeof spy; import: typeof import_; intercept: typeof intercept; }; ``` ### Body Test-case callback receiving its suite asserter. ```ts api-types=eyJBc3NlcnRlciI6eyJocmVmIjoiI2Fzc2VydGVyIiwidGl0bGUiOiI8Y29uc3QgVD4oYWN0dWFsPzogVCkgPT4gQXNzZXJ0PFQ-In19 type Body = (asserter: Asserter) => MaybePromise; ``` ### EncodedError Error shape used by test assertions. ```ts type EncodedError = { // Error message. message: string; // Optional application error code. code?: string; }; ``` ### End Cleanup callback run after a suite's test cases. ```ts type End = () => MaybePromise; ``` ### Equals Exact compile-time type equality. ```ts type Equals = (() => T extends X ? true : false) extends () => T extends Y ? true : false ? true : false; ``` ### Exact Rejects keys outside the test-runner configuration contract. ```ts api-types=eyJUZXN0Q29uZmlnIjp7ImhyZWYiOiIjdGVzdGNvbmZpZyIsInRpdGxlIjoiVGVzdC1ydW5uZXIgY29uZmlndXJhdGlvbiBhY2NlcHRlZCBieSBgdGVzdC5jb25maWdgLiJ9fQ type Exact = Config & Record< Exclude, never >; ``` ### ExpectedError Optional error message, code, or constructor matched by `throws`. ```ts type ExpectedError = string | (new (...args: any[]) => Error) | undefined; ``` ### ExtendedAssert Assertion enriched with custom methods. ```ts api-types=eyJBc3NlcnQiOnsiaHJlZiI6IiNhc3NlcnQiLCJ0aXRsZSI6IkZsdWVudCBydW50aW1lIGFuZCBjb21waWxlLXRpbWUgYXNzZXJ0aW9ucyBmb3IgYW4gYWN0dWFsIHZhbHVlLiJ9fQ type ExtendedAssert = Assert & Extensions; ``` ### ExtendedAsserter Creates an assertion enriched with custom methods. ```ts api-types=eyJFeHRlbmRlZEFzc2VydCI6eyJocmVmIjoiI2V4dGVuZGVkYXNzZXJ0IiwidGl0bGUiOiJBc3NlcnQ8VD4gJiBFeHRlbnNpb25zIn19 type ExtendedAsserter = (actual?: T) => ExtendedAssert; ``` ### ExtendedBody Test-case callback receiving an extended asserter. ```ts api-types=eyJFeHRlbmRlZEFzc2VydGVyIjp7ImhyZWYiOiIjZXh0ZW5kZWRhc3NlcnRlciIsInRpdGxlIjoiPGNvbnN0IFQ-KGFjdHVhbD86IFQpID0-IEV4dGVuZGVkQXNzZXJ0PFQsIEV4dGVuc2lvbnM-In19 type ExtendedBody = (asserter: ExtendedAsserter) => MaybePromise; ``` ### Factory Creates custom assertion methods for the current subject. ```ts api-types=eyJBc3NlcnRlciI6eyJocmVmIjoiI2Fzc2VydGVyIiwidGl0bGUiOiI8Y29uc3QgVD4oYWN0dWFsPzogVCkgPT4gQXNzZXJ0PFQ-In19 type Factory = (assert: Asserter, subject: Subject) => Extensions; ``` ### Forwarded Base methods other than the replaced `case` registration method. ```ts api-types=eyJCYXNlIjp7ImhyZWYiOiIjYmFzZSIsInRpdGxlIjoiUm9vdCBtZXRob2RzIGZvcndhcmRlZCB0byBhbiBleHRlbmRlZCB0ZXN0IGFnZ3JlZ2F0ZS4ifX0 type Forwarded = Omit; ``` ### Handler Handler for an intercepted request. ```ts type Handler = (request: Request) => unknown; ``` ### Intercept Recorded requests and restoration controls for an intercept. ```ts type Intercept = { // Returns the number of intercepted requests for a path. calls(path: string): number; // Returns intercepted requests for a path in call order. requests(path: string): Request[]; // Restores the fetch implementation active before interception. restore(): void; // Restores fetch when used with an explicit resource-management scope. [Symbol.dispose](): void; }; ``` ### MockFunction Any callable module export that can be tracked. ```ts type MockFunction = (...args: any[]) => any; ``` ### MockHandle Tracked module exports and restoration controls. ```ts api-types=eyJNb2NrRnVuY3Rpb24iOnsiaHJlZiI6IiNtb2NrZnVuY3Rpb24iLCJ0aXRsZSI6IiguLi5hcmdzOiBhbnlbXSkgPT4gYW55In0sIk1vY2tUcmFja2VkIjp7ImhyZWYiOiIjbW9ja3RyYWNrZWQiLCJ0aXRsZSI6IkEgbW9ja2VkIGZ1bmN0aW9uIGF1Z21lbnRlZCB3aXRoIGNhbGwgdHJhY2tpbmcuIn19 type MockHandle = { [K in keyof T]: T[K] extends MockFunction ? MockTracked : T[K]; } & { // Removes the registered module mock. restore(): void; // Removes the mock when used with an explicit resource-management scope. [Symbol.dispose](): void; }; ``` ### MockTracked A mocked function augmented with call tracking. ```ts api-types=eyJNb2NrRnVuY3Rpb24iOnsiaHJlZiI6IiNtb2NrZnVuY3Rpb24iLCJ0aXRsZSI6IiguLi5hcmdzOiBhbnlbXSkgPT4gYW55In19 type MockTracked = F & { // Argument tuples recorded in call order. calls: Parameters[]; // Whether the function has been called at least once. readonly called: boolean; }; ``` ### RepositorySuite A registered file suite exposed to test-runner integrations. ```ts api-types=eyJUZXN0UnVuIjp7ImhyZWYiOiIjdGVzdHJ1biIsInRpdGxlIjoiT25lIGNvbXBsZXRlZCB0ZXN0IGFuZCBpdHMgZXhlY3V0aW9uIGR1cmF0aW9uLiJ9fQ interface RepositorySuite { // Spec file represented by this suite. readonly file: FileRef; // Runs registered suite cleanup callbacks. end(): Promise; // Executes tests in registration order. run(): AsyncGenerator; } ``` ### Setup Route-registration methods passed to an intercept setup callback. ```ts api-types=eyJIYW5kbGVyIjp7ImhyZWYiOiIjaGFuZGxlciIsInRpdGxlIjoiKHJlcXVlc3Q6IFJlcXVlc3QpID0-IHVua25vd24ifX0 type Setup = { // Registers a GET response handler. get(path: string, handler: Handler): void; // Registers a POST response handler. post(path: string, handler: Handler): void; // Registers a PUT response handler. put(path: string, handler: Handler): void; // Registers a PATCH response handler. patch(path: string, handler: Handler): void; // Registers a DELETE response handler. delete(path: string, handler: Handler): void; }; ``` ### AnyFunction Any callable value accepted by `test.spy`. ```ts type AnyFunction = (...args: any[]) => any; ``` ### Tracked A function augmented with its recorded calls and called state. ```ts api-types=eyJBbnlGdW5jdGlvbiI6eyJocmVmIjoiI2FueWZ1bmN0aW9uIiwidGl0bGUiOiIoLi4uYXJnczogYW55W10pID0-IGFueSJ9fQ type Tracked = F & { // Argument tuples recorded in call order. calls: Parameters[]; // Whether the function has been called at least once. called: boolean; }; ``` --- Source: https://rcompat.repopack.app/api/type # @rcompat/type API TypeScript utility types for portable JavaScript libraries. This package contains only types. Its imports are erased at build time and are safe to use in projects targeting browsers, Node, Deno, and Bun. ```ts import type { Dict, MaybePromise } from "@rcompat/type"; ``` ## AbstractNewable An abstract constructor with configurable instance and argument types. **Type parameters** - `I` — Constructed instance type. - `A` — Constructor argument tuple. ```ts type AbstractNewable = abstract new (...args: A) => I; ``` ## Arch CPU architectures recognized by runtime APIs. ```ts type Arch = "x64" | "arm64"; ``` ## Bag A readable string-keyed value bag. **Type parameters** - `V` — Stored value type. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 interface Bag { // Returns a value or throws when its key is missing. get(key: string): V; // Returns a value or `undefined` when its key is missing. try(key: string): V | undefined; // Checks whether a key exists. has(key: string): boolean; // Iterates over key/value entries. [Symbol.iterator](): IterableIterator; // Returns all entries as a dictionary. all(): Dict; // Returns a JSON-compatible dictionary representation. toJSON(): Dict; // Returns the bag's string representation. toString(): string; } ``` ## Boolish Boolean values represented as lowercase strings. ```ts type Boolish = "false" | "true"; ``` ## DeepMutable Recursively removes `readonly` modifiers from arrays and objects. **Type parameters** - `T` — Value type to make mutable. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 type DeepMutable = T extends readonly [...infer E extends readonly unknown[]] ? { -readonly [K in keyof E]: DeepMutable } : T extends Dict ? { -readonly [K in keyof T]: DeepMutable } : T; ``` ## Dict A string-keyed record. **Type parameters** - `V` — Stored value type. ```ts type Dict = Record; ``` ## EmptyDict The inferred type of an empty object literal. ```ts type EmptyDict = typeof _; ``` ## ImpliedOptional Adds `undefined` when every property of an object accepts it. **Type parameters** - `T` — Value type to inspect. ```ts type ImpliedOptional = AllOptional extends true ? T | undefined : T; ``` ## Import A module namespace containing a default export. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 type Import = { default: unknown } & Dict; ``` ## IndexedKeys Tests whether a dictionary exposes concrete string or numeric keys. **Type parameters** - `T` — Dictionary type to inspect. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 type IndexedKeys = Extract extends never ? false : true; ``` ## IsAny Tests whether a type is `any`. **Type parameters** - `T` — Type to inspect. ```ts type IsAny = false extends T & true ? true : false; ``` ## IsArray Tests whether a type is a non-tuple array. **Type parameters** - `T` — Type to inspect. ```ts api-types=eyJJc0FueSI6eyJocmVmIjoiI2lzYW55IiwidGl0bGUiOiJmYWxzZSBleHRlbmRzIFQgJiB0cnVlID8gdHJ1ZSA6IGZhbHNlIn0sIklzTmV2ZXIiOnsiaHJlZiI6IiNpc25ldmVyIiwidGl0bGUiOiJJczxULCBuZXZlcj4ifSwiSXNUdXBsZSI6eyJocmVmIjoiI2lzdHVwbGUiLCJ0aXRsZSI6IltUXSBleHRlbmRzIFtyZWFkb25seSBbLi4uaW5mZXIgRWxlbWVudHNdXSA_IG51bWJlciBleHRlbmRzIEVsZW1lbnRzW1wibGVuZ3RoXCJdID8gZmFsc2UgOiB0cnVlIDogZmFsc2UifSwiU29tZSI6eyJocmVmIjoiI3NvbWUiLCJ0aXRsZSI6IlQgZXh0ZW5kcyByZWFkb25seSBbaW5mZXIgRmlyc3QsIC4uLmluZmVyIFJlc3QgZXh0ZW5kcyBib29sZWFuW11dID8gRmlyc3QgZXh0ZW5kcyB0cnVlID8gdHJ1ZSA6IFNvbWU8UmVzdD4gOiBmYWxzZSJ9fQ type IsArray = Some<[IsNever, IsAny]> extends true ? false : [T] extends [readonly unknown[]] ? IsTuple extends true ? false : true : false; ``` ## IsClass Tests whether a type is a non-static object instance. **Type parameters** - `T` — Type to inspect. ```ts api-types=eyJJc0FueSI6eyJocmVmIjoiI2lzYW55IiwidGl0bGUiOiJmYWxzZSBleHRlbmRzIFQgJiB0cnVlID8gdHJ1ZSA6IGZhbHNlIn0sIklzTmV2ZXIiOnsiaHJlZiI6IiNpc25ldmVyIiwidGl0bGUiOiJJczxULCBuZXZlcj4ifSwiU29tZSI6eyJocmVmIjoiI3NvbWUiLCJ0aXRsZSI6IlQgZXh0ZW5kcyByZWFkb25seSBbaW5mZXIgRmlyc3QsIC4uLmluZmVyIFJlc3QgZXh0ZW5kcyBib29sZWFuW11dID8gRmlyc3QgZXh0ZW5kcyB0cnVlID8gdHJ1ZSA6IFNvbWU8UmVzdD4gOiBmYWxzZSJ9fQ type IsClass = Some<[ IsNever, IsAny, Is, Is, Is, ]> extends true ? false : T extends { constructor: unknown } & object ? true : false; ``` ## IsNever Tests whether a type is `never`. **Type parameters** - `T` — Type to inspect. ```ts type IsNever = Is; ``` ## IsTuple Tests whether a type is a fixed-length tuple. **Type parameters** - `T` — Type to inspect. ```ts type IsTuple = [T] extends [readonly [...infer Elements]] ? number extends Elements["length"] ? false : true : false; ``` ## IsUnion Tests whether a type is a union. **Type parameters** - `T` — Type to inspect. ```ts type IsUnion = ( T extends unknown ? (x: T) => void : never ) extends (x: infer U) => void ? [T] extends [U] ? false : true : never; ``` ## IsUnknown Tests whether a type is exactly `unknown`. **Type parameters** - `T` — Type to inspect. ```ts api-types=eyJJc0FueSI6eyJocmVmIjoiI2lzYW55IiwidGl0bGUiOiJmYWxzZSBleHRlbmRzIFQgJiB0cnVlID8gdHJ1ZSA6IGZhbHNlIn0sIk5vdCI6eyJocmVmIjoiI25vdCIsInRpdGxlIjoiVCBleHRlbmRzIHRydWUgPyBmYWxzZSA6IHRydWUifX0 type IsUnknown = [unknown] extends [T] ? Not> : false; ``` ## IsVoid Tests whether a type is exactly `void`. **Type parameters** - `T` — Type to inspect. ```ts type IsVoid = Is; ``` ## Join Joins a tuple of string types with a separator. **Type parameters** - `T` — Strings to join. - `Separator` — Separator placed between strings. ```ts type Join = T extends [] ? "" : T extends [infer First extends string] ? First : T extends [infer First extends string, ...infer Rest extends string[]] ? `${First}${Separator}${Join}` : string; ``` ## JSONPointer An empty or slash-prefixed JSON Pointer path. ```ts type JSONPointer = "" | `/${string}`; ``` ## JSONValue A value representable in JSON. ```ts type JSONValue = | { readonly [key: string]: JSONValue } | JSONPrimitive | readonly JSONValue[]; ``` ## LooseOptional Makes properties accepting `undefined` optional while retaining explicit `undefined` in their value types. **Type parameters** - `T` — Object type to transform. ```ts api-types=eyJVbnBhY2siOnsiaHJlZiI6IiN1bnBhY2siLCJ0aXRsZSI6IkV4cGFuZHMgYW4gb2JqZWN0IHR5cGUgZm9yIGNsZWFyZXIgZWRpdG9yIGRpc3BsYXkuIn19 type LooseOptional = Unpack< { [K in keyof T as Undef extends T[K] ? K : never]?: Exclude | undefined; } & { [K in keyof T as Undef extends T[K] ? never : K]: T[K]; } >; ``` ## Maybe A value that may be `undefined`. **Type parameters** - `T` — Defined value type. ```ts type Maybe = T | undefined; ``` ## MaybePromise A synchronous value or a promise for that value. **Type parameters** - `T` — Resolved value type. ```ts type MaybePromise = Promise | T; ``` ## Mutable Removes top-level `readonly` modifiers. **Type parameters** - `T` — Value type to make mutable. ```ts type Mutable = { -readonly [K in keyof T]: T[K] }; ``` ## Newable A concrete constructor with configurable instance and argument types. **Type parameters** - `I` — Constructed instance type. - `A` — Constructor argument tuple. ```ts type Newable = new (...args: A) => I; ``` ## Not Negates a boolean literal type. **Type parameters** - `T` — Boolean to negate. ```ts type Not = T extends true ? false : true; ``` ## Nullish A `null` or `undefined` value. ```ts type Nullish = null | undefined; ``` ## OS Operating-system names recognized by runtime APIs. ```ts type OS = "linux" | "darwin" | "windows"; ``` ## PackageJSON A typed npm-compatible `package.json` manifest. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiSlNPTlZhbHVlIjp7ImhyZWYiOiIjanNvbnZhbHVlIiwidGl0bGUiOiJBIHZhbHVlIHJlcHJlc2VudGFibGUgaW4gSlNPTi4ifX0 type PackageJSON = { name: string; version: string; description?: string; keywords?: string[]; homepage?: string; bugs?: string | { url?: string; email?: string; }; license?: string; author?: Person; contributors?: Person[]; funding?: Funding | Funding[]; files?: string[]; exports?: string | string[] | JSONValue; imports?: JSONValue; main?: string; type?: "module" | "commonjs"; browser?: string; bin?: string | JSONValue; man?: string | string[]; directories?: JSONValue; repository?: string | TypeURL & { directory?: string }; scripts?: JSONValue; gypfile?: boolean; config?: JSONValue; dependencies?: JSONValue; devDependencies?: JSONValue; peerDependencies?: JSONValue; peerDependenciesMeta?: Dict<{ optional: boolean }>; bundleDependencies?: string[] | boolean; bundledDependencies?: string[] | boolean; optionalDependencies?: JSONValue; overrides?: JSONValue; engines?: JSONValue; os?: string[]; cpu?: string[]; libc?: string[]; devEngines?: JSONValue; private?: boolean; publishConfig?: JSONValue; workspaces?: string[]; }; ``` ## PartialDict A string-keyed record whose values may be absent. **Type parameters** - `T` — Defined value type. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifX0 type PartialDict = Dict; ``` ## Primitive Any JavaScript primitive value. ```ts type Primitive = bigint | boolean | null | number | string | symbol | undefined; ``` ## Print Converts a TypeScript type into a readable string literal type. **Type parameters** - `T` — Type to print. ```ts api-types=eyJEaWN0Ijp7ImhyZWYiOiIjZGljdCIsInRpdGxlIjoiUmVjb3JkPHN0cmluZywgVj4ifSwiSXNBbnkiOnsiaHJlZiI6IiNpc2FueSIsInRpdGxlIjoiZmFsc2UgZXh0ZW5kcyBUICYgdHJ1ZSA_IHRydWUgOiBmYWxzZSJ9LCJJc0FycmF5Ijp7ImhyZWYiOiIjaXNhcnJheSIsInRpdGxlIjoiVGVzdHMgd2hldGhlciBhIHR5cGUgaXMgYSBub24tdHVwbGUgYXJyYXkuIn0sIklzQ2xhc3MiOnsiaHJlZiI6IiNpc2NsYXNzIiwidGl0bGUiOiJUZXN0cyB3aGV0aGVyIGEgdHlwZSBpcyBhIG5vbi1zdGF0aWMgb2JqZWN0IGluc3RhbmNlLiJ9LCJJc05ldmVyIjp7ImhyZWYiOiIjaXNuZXZlciIsInRpdGxlIjoiSXM8VCwgbmV2ZXI-In0sIklzVHVwbGUiOnsiaHJlZiI6IiNpc3R1cGxlIiwidGl0bGUiOiJbVF0gZXh0ZW5kcyBbcmVhZG9ubHkgWy4uLmluZmVyIEVsZW1lbnRzXV0gPyBudW1iZXIgZXh0ZW5kcyBFbGVtZW50c1tcImxlbmd0aFwiXSA_IGZhbHNlIDogdHJ1ZSA6IGZhbHNlIn0sIklzVW5pb24iOnsiaHJlZiI6IiNpc3VuaW9uIiwidGl0bGUiOiIoIFQgZXh0ZW5kcyB1bmtub3duID8gKHg6IFQpID0-IHZvaWQgOiBuZXZlciApIGV4dGVuZHMgKHg6IGluZmVyIFUpID0-IHZvaWQgPyBbVF0gZXh0ZW5kcyBbVV0gPyBmYWxzZSA6IHRydWUgOiBuZXZlciJ9LCJJc1Vua25vd24iOnsiaHJlZiI6IiNpc3Vua25vd24iLCJ0aXRsZSI6Ilt1bmtub3duXSBleHRlbmRzIFtUXSA_IE5vdDxJc0FueTxUPj4gOiBmYWxzZSJ9LCJJc1ZvaWQiOnsiaHJlZiI6IiNpc3ZvaWQiLCJ0aXRsZSI6IklzPFQsIHZvaWQ-In0sIk11dGFibGUiOnsiaHJlZiI6IiNtdXRhYmxlIiwidGl0bGUiOiJSZW1vdmVzIHRvcC1sZXZlbCBgcmVhZG9ubHlgIG1vZGlmaWVycy4ifX0 type Print = IsVoid extends true ? "void" : IsUnknown extends true ? "unknown" : IsNever extends true ? "never" : IsAny extends true ? "any" : [T] extends [boolean] ? [boolean] extends [T] ? "boolean" : `${T}` : IsUnion extends true ? PrintUnion : T extends string ? string extends T ? "string" : `'${T}'` : T extends number ? number extends T ? "number" : `${T}` : T extends bigint ? bigint extends T ? "bigint" : `${T}n` : T extends symbol ? "symbol" : T extends null ? "null" : T extends undefined ? "undefined" : IsTuple extends true ? PrintTuple : IsArray extends true ? T extends (infer E)[] ? `${PrintArray}[]` : T extends ReadonlyArray ? `readonly ${Print}[]` : "array" : T extends Dict ? // If T is a fully readonly, concrete object (like Readonly<{ ok: boolean }>), // print it wrapped as Readonly<...>. Otherwise print the dictionary normally. IsEqual> extends true ? HasSpecificKeys extends true ? `Readonly<${PrintDict>}>` : PrintDict : PrintDict : IsClass extends true ? PrintClass : never ; ``` ## Printable A value carrying a readable type name. ```ts interface Printable { // The readable type name. readonly Name: string; } ``` ## PrintableGeneric A printable value carrying its represented type. **Type parameters** - `Type` — Represented type. ```ts api-types=eyJQcmludGFibGUiOnsiaHJlZiI6IiNwcmludGFibGUiLCJ0aXRsZSI6IkEgdmFsdWUgY2FycnlpbmcgYSByZWFkYWJsZSB0eXBlIG5hbWUuIn19 interface PrintableGeneric extends Printable { // The represented type marker. readonly Type: Type; } ``` ## Schema A parser that converts unknown input into a typed value. **Type parameters** - `T` — Parsed output type. ```ts interface Schema { // Parses and validates an unknown input. parse(input: unknown): T; } ``` ## Serializable A value with a custom JSON-compatible representation. `JSON.stringify` invokes `toJSON` when serializing implementations. ```ts api-types=eyJKU09OVmFsdWUiOnsiaHJlZiI6IiNqc29udmFsdWUiLCJ0aXRsZSI6IkEgdmFsdWUgcmVwcmVzZW50YWJsZSBpbiBKU09OLiJ9fQ interface Serializable { // Converts the value into a JSON-compatible representation. toJSON(): JSONValue; } ``` ## Some Tests whether any member of a boolean tuple is `true`. **Type parameters** - `T` — Boolean tuple to inspect. ```ts type Some = T extends readonly [infer First, ...infer Rest extends boolean[]] ? First extends true ? true : Some : false ; ``` ## StringClass A string-like object supporting replacement and conversion. ```ts api-types=eyJTdHJpbmdSZXBsYWNlciI6eyJocmVmIjoiI3N0cmluZ3JlcGxhY2VyIiwidGl0bGUiOiIoKHN1YnN0cmluZzogc3RyaW5nLCAuLi5wYXJhbXM6IGFueVtdKSA9PiBzdHJpbmcpIn19 type StringClass = { [Symbol.replace](string: string, replacement: string): string; [Symbol.replace](string: string, replacement: StringReplacer): string; toString(): string; }; ``` ## StringLike A primitive string or string-like object. ```ts api-types=eyJTdHJpbmdDbGFzcyI6eyJocmVmIjoiI3N0cmluZ2NsYXNzIiwidGl0bGUiOiJBIHN0cmluZy1saWtlIG9iamVjdCBzdXBwb3J0aW5nIHJlcGxhY2VtZW50IGFuZCBjb252ZXJzaW9uLiJ9fQ type StringLike = string | StringClass; ``` ## StringReplacer A replacement callback accepted by `String.prototype.replace`. ```ts type StringReplacer = ((substring: string, ...params: any[]) => string); ``` ## TupleToUnion Converts a tuple into a union of its element types. **Type parameters** - `T` — Tuple to convert. ```ts type TupleToUnion = T[number]; ``` ## TypedArray Any JavaScript typed array. **Type parameters** - `Buffer` — Allowed backing buffer type. ```ts type TypedArray = | BigInt64Array | BigUint64Array | Float16Array | Float32Array | Float64Array | Int16Array | Int32Array | Int8Array | Uint16Array | Uint32Array | Uint8Array | Uint8ClampedArray ; ``` ## UndefinedToOptional Makes properties accepting `undefined` optional and removes explicit `undefined` from their value types. **Type parameters** - `T` — Object type to transform. ```ts api-types=eyJVbnBhY2siOnsiaHJlZiI6IiN1bnBhY2siLCJ0aXRsZSI6IkV4cGFuZHMgYW4gb2JqZWN0IHR5cGUgZm9yIGNsZWFyZXIgZWRpdG9yIGRpc3BsYXkuIn19 type UndefinedToOptional = Unpack< { [K in keyof T as Undef extends T[K] ? K : never]?: Exclude; } & { [K in keyof T as Undef extends T[K] ? never : K]: T[K]; } >; ``` ## UnionToTuple Converts a union into a tuple containing each union member. **Type parameters** - `U` — Union to convert. - `T` — Accumulated tuple used during conversion. ```ts type UnionToTuple = [U] extends [never] ? T : UnionToTuple>, [LastOf, ...T]> ; ``` ## UnknownFunction A callable function with arbitrary parameters and an unknown result. ```ts type UnknownFunction = (...params: any[]) => unknown; ``` ## UnknownMap A map with property keys and unknown values. ```ts type UnknownMap = Map; ``` ## UnknownSet A set containing unknown values. ```ts type UnknownSet = Set; ``` ## Unpack Expands an object type for clearer editor display. **Type parameters** - `T` — Object type to expand. ```ts type Unpack = { [K in keyof T]: T[K] } & {}; ``` --- Source: https://rcompat.repopack.app/api/webview # @rcompat/webview API Native desktop webviews for Bun and Deno. Bun and Deno provide the native implementation on supported macOS, Linux, and Windows targets. Node and browser bundles can import the package, but constructing a webview throws a descriptive unsupported-runtime error. ```ts import Webview from "@rcompat/webview"; import platform from "@rcompat/webview/default"; import type { Init, Size, SizeHint, Webview as WebviewContract, } from "@rcompat/webview"; ``` ## Webview constructor Runtime-selected native webview constructor. ```ts api-types=eyJJbml0Ijp7ImhyZWYiOiIjaW5pdCIsInRpdGxlIjoiT3B0aW9ucyB1c2VkIHRvIGNvbnN0cnVjdCBhIHdlYnZpZXcuIn0sIldlYnZpZXdDb250cmFjdCI6eyJocmVmIjoiI3dlYnZpZXciLCJ0aXRsZSI6IkEgbmF0aXZlIHdlYnZpZXcgaW5zdGFuY2UuIn19 new Webview(init: Init): WebviewContract; ``` **Example** ```ts const webview = new Webview({ platform }); webview.html = "

Hello

"; webview.run(); ``` ## Types ## Init Options used to construct a webview. ```ts type Init = { // Enables native developer tools. // Default: `false` debug?: boolean; // Runtime-specific native sidecar artifact. platform: Platform; }; ``` ## Size Partial native window size assignment. ```ts api-types=eyJTaXplSGludCI6eyJocmVmIjoiI3NpemVoaW50IiwidGl0bGUiOiIwIHwgMSB8IDIgfCAzIn19 type Size = { // Window height in pixels. // Default: `720` height?: number; // Native size constraint. // Default: `0` hint?: SizeHint; // Window width in pixels. // Default: `1280` width?: number; }; ``` ## SizeHint Native window size constraint: `0` none, `1` minimum, `2` maximum, or `3` fixed. ```ts type SizeHint = 0 | 1 | 2 | 3; ``` ## Webview A native webview instance. ### Webview members #### Webview.html Latest HTML assigned to the webview, if any. Replaces the webview document with an HTML string. ```ts get html(): string | undefined; set html(value: string); ``` #### Webview.size Effective size as an isolated snapshot. Resizes the window, applying defaults to omitted fields. Mutating the returned object does not resize the native window. Assign a new partial size object to resize the native window. ```ts api-types=eyJTaXplIjp7ImhyZWYiOiIjc2l6ZSIsInRpdGxlIjoiUGFydGlhbCBuYXRpdmUgd2luZG93IHNpemUgYXNzaWdubWVudC4ifX0 get size(): Required; set size(value: Size); ``` #### Webview.destroy Idempotently terminates and releases the native handle. Posts `"destroyed"` when `globalThis.postMessage` is available. ```ts destroy(): void; ``` #### Webview.navigate Navigates the webview to a URL. ```ts navigate(url: string): void; ``` #### Webview.run Runs the blocking native event loop, then destroys the handle. ```ts run(): void; ``` ## Platform exports The `default` subpath detects the current target; named subpaths select the indicated target explicitly. Bun loads the embedded sidecar artifact, while Deno returns its filesystem path. Node and browser imports resolve to `undefined` because native webviews are unsupported there. ### @rcompat/webview/default ```ts import platform from "@rcompat/webview/default"; ``` ### @rcompat/webview/darwin-arm64 ```ts import platform from "@rcompat/webview/darwin-arm64"; ``` ### @rcompat/webview/darwin-x64 ```ts import platform from "@rcompat/webview/darwin-x64"; ``` ### @rcompat/webview/linux-arm64 ```ts import platform from "@rcompat/webview/linux-arm64"; ``` ### @rcompat/webview/linux-x64 ```ts import platform from "@rcompat/webview/linux-x64"; ``` ### @rcompat/webview/windows-x64 ```ts import platform from "@rcompat/webview/windows-x64"; ``` --- Source: https://rcompat.repopack.app/api/worker # @rcompat/worker API Portable module workers with the Web Worker messaging contract. Browsers and Deno use the native worker. Bun adds a compatibility preload, while Node adapts `worker_threads` and bootstraps Web Worker globals. Worker scripts should use `self`, events, and `postMessage` rather than runtime-specific messaging APIs. ```ts import Worker from "@rcompat/worker"; import type { Worker as WorkerContract, WorkerConstructor, WorkerOptions, } from "@rcompat/worker"; ``` ## Worker constructor Runtime-selected portable worker constructor. ```ts api-types=eyJXb3JrZXJDb250cmFjdCI6eyJocmVmIjoiI3dvcmtlciIsInRpdGxlIjoiUG9ydGFibGUgd29ya2VyIGluc3RhbmNlIGFuZCBtZXNzYWdpbmcgY29udHJhY3QuIn0sIldvcmtlck9wdGlvbnMiOnsiaHJlZiI6IiN3b3JrZXJvcHRpb25zIiwidGl0bGUiOiJTaGFyZWQgb3B0aW9ucyBmb3IgY29uc3RydWN0aW5nIGEgcG9ydGFibGUgbW9kdWxlIHdvcmtlci4ifX0 new Worker( input: string | URL, options?: WorkerOptions, ): WorkerContract; ``` **Example** ```ts const worker = new Worker(new URL("./worker.js", import.meta.url), { name: "example", }); worker.postMessage("hello"); ``` ## Types ## Worker Portable worker instance and messaging contract. `Worker` extends `EventTarget`, including its standard listener and dispatch methods. ### Worker members #### Worker.onerror Callback invoked for worker execution errors. ```ts api-types=eyJFcnJvckhhbmRsZXIiOnsiaHJlZiI6IiNlcnJvcmhhbmRsZXIiLCJ0aXRsZSI6IigoZXZlbnQ6IEVycm9yRXZlbnQpID0-IHVua25vd24pIHwgbnVsbCJ9fQ onerror: ErrorHandler; ``` #### Worker.onmessage Callback invoked for messages from the worker. ```ts api-types=eyJNZXNzYWdlSGFuZGxlciI6eyJocmVmIjoiI21lc3NhZ2VoYW5kbGVyIiwidGl0bGUiOiIoKGV2ZW50OiBNZXNzYWdlRXZlbnQpID0-IHVua25vd24pIHwgbnVsbCJ9fQ onmessage: MessageHandler; ``` #### Worker.onmessageerror Callback invoked when an incoming message cannot be deserialized. ```ts api-types=eyJNZXNzYWdlSGFuZGxlciI6eyJocmVmIjoiI21lc3NhZ2VoYW5kbGVyIiwidGl0bGUiOiIoKGV2ZW50OiBNZXNzYWdlRXZlbnQpID0-IHVua25vd24pIHwgbnVsbCJ9fQ onmessageerror: MessageHandler; ``` #### Worker.postMessage Sends a structured-cloneable value and optional transferables. ```ts postMessage(message: unknown, transfer?: Transferable[]): void; ``` #### Worker.terminate Stops worker execution. ```ts terminate(): void; ``` ## WorkerConstructor Runtime-selected portable worker constructor. ```ts api-types=eyJXb3JrZXIiOnsiaHJlZiI6IiN3b3JrZXIiLCJ0aXRsZSI6IlBvcnRhYmxlIHdvcmtlciBpbnN0YW5jZSBhbmQgbWVzc2FnaW5nIGNvbnRyYWN0LiJ9LCJXb3JrZXJPcHRpb25zIjp7ImhyZWYiOiIjd29ya2Vyb3B0aW9ucyIsInRpdGxlIjoiU2hhcmVkIG9wdGlvbnMgZm9yIGNvbnN0cnVjdGluZyBhIHBvcnRhYmxlIG1vZHVsZSB3b3JrZXIuIn19 type WorkerConstructor = new ( input: string | URL, options?: WorkerOptions, ) => Worker; ``` **Example** ```ts const worker = new Worker(new URL("./worker.js", import.meta.url), { name: "example", }); worker.postMessage("hello"); ``` ## WorkerOptions Shared options for constructing a portable module worker. ```ts api-types=eyJXb3JrZXIiOnsiaHJlZiI6IiN3b3JrZXIiLCJ0aXRsZSI6IlBvcnRhYmxlIHdvcmtlciBpbnN0YW5jZSBhbmQgbWVzc2FnaW5nIGNvbnRyYWN0LiJ9fQ type WorkerOptions = { // Runtime-visible worker name. name?: string; // Worker execution mode. // Default: `"module"` type?: "module"; }; ``` ## Supporting contracts These handler aliases support the public worker properties. ### ErrorHandler Error-event callback assigned to a worker. ```ts type ErrorHandler = ((event: ErrorEvent) => unknown) | null; ``` ### MessageHandler Message-event callback assigned to a worker. ```ts type MessageHandler = ((event: MessageEvent) => unknown) | null; ``` --- Source: https://rcompat.repopack.app/api/proby # proby API Configuration types and the legacy configuration helper for the Proby test runner. The `proby` command discovers and runs `*.spec.ts` and `*.spec.js` files on Node, Deno, and Bun. New configuration files should use [`test.config()`](/api/test#test-config) from `@rcompat/test`; the default export remains available for existing `proby.config.*` files. ```ts import config from "proby"; import type { Config, TestConfig } from "proby"; ``` ## config() legacy helper Returns a type-checked test configuration unchanged. This helper is retained for existing `proby.config.*` files. New `spec.config.*` files should use [`test.config()`](/api/test#test-config) from `@rcompat/test`. **Parameters** - `input` — Test discovery and preload options. **Returns:** The original configuration object. ```ts api-types=eyJUZXN0Q29uZmlnIjp7ImhyZWYiOiIjdGVzdGNvbmZpZyIsInRpdGxlIjoiVGVzdC1ydW5uZXIgY29uZmlndXJhdGlvbiBhY2NlcHRlZCBieSBgdGVzdC5jb25maWdgLiJ9LCJFeGFjdCI6eyJocmVmIjoiI2V4YWN0IiwidGl0bGUiOiJUICYgUmVjb3JkPCBFeGNsdWRlPGtleW9mIFQsIGtleW9mIFRlc3RDb25maWc-LCBuZXZlciA-In19 config(input: Exact): T; ``` **Example** ```ts import config from "proby"; export default config({ include: ["src"], monorepo: true, }); ``` ## Types ## Config Fully normalized configuration used by the Proby runner. ```ts type Config = { // Whether package directories are scanned as a monorepo. monorepo: boolean; // Package directory resolved from the project root. packages: string; // Directories searched for spec files. include: string[]; // Modules preloaded before test files run. loaders: string[]; }; ``` ## TestConfig Test-runner configuration accepted by `test.config`. ```ts interface TestConfig { // Directories searched for spec files. // Default: `["src", "test"]` include?: readonly string[]; // Modules preloaded before test files run. // Default: `[]` loaders?: readonly string[]; // Whether package directories are scanned as a monorepo. // Default: `false` monorepo?: boolean; // Package directory resolved from the project root. // Default: `"packages"` packages?: string; } ``` ## Supporting contracts ### Exact Rejects configuration keys outside the public input contract. ```ts api-types=eyJUZXN0Q29uZmlnIjp7ImhyZWYiOiIjdGVzdGNvbmZpZyIsInRpdGxlIjoiVGVzdC1ydW5uZXIgY29uZmlndXJhdGlvbiBhY2NlcHRlZCBieSBgdGVzdC5jb25maWdgLiJ9fQ type Exact = T & Record< Exclude, never >; ```