Multi-format data ingestion, WebAssembly sandboxing, and GitOps drift healing for TypeScript.
Rez parses incoming JSON, CSV, TSV, XML, YAML, key-value/logfmt, and raw text payloads, validates them against Zod contracts, executes approvedtransform(raw)patches inside a QuickJS WebAssembly isolate, and—when unseen drift occurs—synthesizes a repair patch with AI (optionally guided by vendor docs/changelogs) and opens a Git review branch / Pull Request.
Git is the source of truth. Approved patches are stored as versioned JavaScript files in patches/ (or registered in memory for edge/serverless runtimes) and reviewed via standard GitHub Pull Requests.
flowchart TD
A["Incoming Payload (JSON / CSV / TSV / XML / YAML / KV / Text)"] --> B["Parse & Detect Format (src/parsers.ts)"]
B --> C{"Approved Patch in Catalog?"}
C -- "Yes" --> D["Execute transform(raw) in QuickJS WASM"]
D -- "Validates against Zod" --> E["Return Normalized Data (SUCCESS)"]
C -- "No" --> F{"Matches Zod Contract?"}
F -- "Yes" --> E
F -- "No (Drift)" --> G["Deduplicate In-Flight / Check Open PRs"]
G --> H["Fetch Optional Vendor Docs (docsUrl / resolveDocs)"]
H --> I["AI Synthesizes ES2020 transform(raw) Patch"]
I --> J["Verify Patch in QuickJS WASM + Zod"]
J -- "Fails" --> K["Quarantine (HEALING_FAILED)"]
J -- "Passes" --> L["Commit Branch & Open PR (GitHub REST / Local Git)"]
L --> M["Quarantine (PENDING_GIT_REVIEW)"]
- Multi-Format Parsing (
src/parsers.ts): Normalizesstringor object/array inputs acrossjson,csv,tsv(papaparse),xml(fast-xml-parser),yaml(yaml),kv(logfmt/.env), and rawtext, withautoformat detection. - Contract Validation (
src/contracts.ts): Validates parsed data against user-defined Zod schemas or dynamic field specification dictionaries ({ field: "str" | "int" | "float" | "bool" | "list" | "dict" }). - Fast-Path Patch Execution (
src/sandbox.ts,src/catalog.ts): If an active patch exists for asource, it runstransform(raw)inside an in-process QuickJS WebAssembly (quickjs-emscripten) isolate with an 8 MB memory limit and configurable execution deadline (default2000ms), then validates the output against the target contract. - Drift Deduplication (
src/core.ts): Coalesces concurrent healing attempts for the samesource::schema, caches pending review branches, and checks GitHub for an already-open review PR before invoking an LLM. - Vendor Docs Context (
src/docs-fetcher.ts): When drift occurs, optionally fetches one or moredocsUrlendpoints (converting HTML to Markdown vianode-html-markdown) or calls a customresolveDocshook, truncating to12,000characters by default and failing gracefully on network errors. - AI Synthesis & Verification (
src/ai-engine.ts): Uses the VercelaiSDK (generateObject) across supported providers to generatefunction transform(raw) { ... }, a Conventional Commit message, and a Markdown PR summary, then verifies the generated function in the QuickJS WASM sandbox before accepting it. - GitOps Review (
src/git-ops.ts,src/git-review.ts): Commits the verified patch to a review branch (rez-patch/...) via the GitHub REST API (@octokit/rest) or local Git (simple-git) and opens a Pull Request when credentials are configured.
npm install rezjs zodRequirements:
- Node.js
>= 20.0.0 - Either a local Git repository (
git init) or remote GitHub credentials (GITHUB_TOKEN+GITHUB_REPOSITORY).
import { defineConfig } from "rezjs";
import { z } from "zod";
export default defineConfig({
model: {
provider: "google", // "google" | "openai" | "anthropic" | "openrouter" | "deepseek" | "groq" | "ollama"
},
git: {
baseBranch: "main",
patchDir: "patches",
autoPush: false,
createPullRequest: true,
},
contracts: {
LogisticsShipment: z.object({
container_id: z.string(),
carrier_name: z.string(),
status: z.enum(["IN_TRANSIT", "DELIVERED", "DELAYED", "EXCEPTION"]),
weight_kg: z.number().positive(),
}),
},
});import { Rez } from "rezjs";
import { z } from "zod";
const ShipmentSchema = z.object({
container_id: z.string(),
weight_kg: z.number().positive(),
});
const rez = new Rez({
contract: ShipmentSchema,
docsUrl: "https://vendor.example.com/api-changelog",
});
const result = await rez.ingest({
source: "vendor_csv_feed",
format: "csv", // "auto" | "json" | "csv" | "tsv" | "xml" | "yaml" | "kv" | "text"
payload: `cntr_no,gross_lbs\nMSKU100,2204.62`,
// Optional custom hook (e.g. search API or internal wiki lookup):
resolveDocs: async ({ source, validationError }) =>
`Docs for ${source}: ${validationError}`,
});
if (result.isSuccess()) {
console.log("Normalized:", result.data);
} else if (result.isQuarantined()) {
console.warn("Quarantined:", result.status, result.reviewBranch, result.prUrl);
}rezjs/edge exports the core engine without node:fs, node:path, or node:child_process, using MemoryPatchCatalog and GitHub REST GitOps:
import { Rez } from "rezjs/edge";
import { z } from "zod";
const ShipmentContract = z.object({
container_id: z.string(),
weight_kg: z.number(),
});
const rez = new Rez({
contract: ShipmentContract,
gitToken: env.GITHUB_TOKEN,
gitRepository: env.GITHUB_REPOSITORY, // "owner/repo"
model: {
provider: "google",
apiKey: env.GEMINI_API_KEY,
},
});
// Pre-register an approved patch in memory if needed
rez.registerPatch("vendor_feed", `
function transform(raw) {
return { container_id: String(raw.cntr), weight_kg: Number(raw.kg) };
}
`);| Format | format value |
Underlying Parser | Notes |
|---|---|---|---|
| JSON | "json" |
JSON.parse |
Objects, arrays, or JSON strings |
| CSV / TSV | "csv" / "tsv" |
papaparse |
Header-keyed array of row objects |
| XML | "xml" |
fast-xml-parser |
Attributes under @attributes, text under #text, repeated tags as arrays |
| YAML | "yaml" |
yaml |
Full YAML document parsing |
| Key-Value | "kv" |
Built-in logfmt parser | key=value / key="quoted value" with scalar coercion |
| Raw Text | "text" |
Passthrough | Passes raw string directly to transform(raw) |
| Auto-Detect | "auto" (default) |
Heuristic detector | Infers format from string payloads; falls back to "text" |
Patches execute inside a quickjs-emscripten context rather than eval() or Node vm:
- No Node/OS globals:
require(),import,process, filesystem, and network APIs are unavailable inside the isolate. - Memory limit:
8 MB(1024 * 1024 * 8bytes). - Execution timeout: Interrupt handler terminates infinite loops after the configured deadline (default
2000ms). - Contract check: Serialized return values are validated against the target Zod schema or field specs before leaving
executePatch().
Resolved via environment variables or explicit model config (provider, name, apiKey, baseURL):
- Google (
google—GEMINI_API_KEY/GOOGLE_GENERATIVE_AI_API_KEY/GOOGLE_API_KEY) - OpenAI (
openai—OPENAI_API_KEY) - Anthropic (
anthropic—ANTHROPIC_API_KEY) - OpenRouter (
openrouter—OPENROUTER_API_KEY) - DeepSeek (
deepseek—DEEPSEEK_API_KEY) - Groq (
groq—GROQ_API_KEY) - Ollama (
ollama—OLLAMA_BASE_URL, defaults tohttp://localhost:11434/v1)
Optional GitOps environment variables:
GITHUB_TOKENGITHUB_REPOSITORY("owner/repo")
FilePatchCatalog(Node default): Stores versioned patch files inpatches/and supportslistPatchVersions()androllbackPatch().MemoryPatchCatalog(Edge default): Stores versioned patches in memory withregisterPatch(),listPatchVersions(), androllbackPatch().
Build TypeScript definitions and compiled output:
npm run buildRun the unit test suite (Vitest):
npm testTest coverage across the 8 Vitest suites (tests/*.test.ts):
parsers.test.ts: CSV/TSV, XML, YAML, KV, format auto-detection, and multi-formatRez.ingest()fast-path transformsdocs-fetcher.test.ts: HTML-to-Markdown conversion, Markdown passthrough,resolveDocs, error fallback, and truncation (mockedfetch)sandbox.test.ts: QuickJS execution, error isolation, deadline interruption, and Zod validationcontracts.test.ts: Dynamic schema creation, validation errors, inference, and Zod field extractioncatalog.test.ts: In-memory and file-backed patch versioning and rollbackgit-review.test.ts: Localsimple-gitbranching/commits and GitHub REST API branch/PR operationsai-engine.test.ts: Provider/model resolution,PatchResultSchema, missing-key handling, and explicit edgeapiKeyconfigsdk.test.ts: End-to-endRezSDK lifecycle,defineConfig, fast-path catalog execution, drift quarantine, rollback, andrezjs/edgeimports
Apache 2.0 © Rez Contributors.