Gargamelle
Gargamelle generates typed JSON decoders and JSON Schema 2020-12 documents from the same Gleam definition.
Gargamelle also provides gargamelle/boundary APIs that bind a contract to a handler.
A contract combines a definition with optional semantic checks of decoded values.
Incoming JSON must satisfy that contract before the handler runs. Handlers receive
decoded Gleam values and original JSON, or verified JSON.
Definitions, decoding and schema generation can be used independently of boundary APIs.
| Operation | API | Module |
|---|---|---|
| Definition construction | string, safe_integer, array, record, … |
gargamelle |
| Direct admitted JSON construction | json_* constructors |
gargamelle |
| JSON decoding into a Gleam value | decode |
gargamelle |
| Decoding or validation with semantic requirements | decode_contract / validate_contract |
gargamelle |
| JSON Schema generation | schema_json / schema_string |
gargamelle |
| JSON retention with the accepting contract | verify → VerifiedJson |
gargamelle |
| Pipe-friendly record definitions | record.start or record.start1–record.start32, then a field pipeline |
gargamelle/record |
| Shared record definitions and encoders | codec_record.start(record.start2(Constructor)), then a field pipeline |
gargamelle/codec_record |
| Validated handler invocation with decoded data | new → Boundary + forward |
gargamelle/boundary |
| Validated handler invocation with original JSON | json → JsonBoundary + forward_json |
gargamelle/boundary |
| Typed output through a receiving boundary | output + send |
gargamelle/boundary |
| Loading and saving through one contract | paired → PairedBoundary + load / save |
gargamelle/boundary |
| Typed JSON encoding | encode_json |
gargamelle/encoding |
| Encoding checked against a Contract | encode |
gargamelle/encoding |
| Contract error summaries and JSON reports | summary / to_json |
gargamelle/diagnostics |
Getting started
Requires Gleam 1.18.1 or later.
Package installation:
gleam add gargamelle@1.3.0
JavaScript
Target configuration in gleam.toml:
target = "javascript"
Erlang
Target configuration in gleam.toml:
target = "erlang"
The native regex helper requires make and a C compiler. Helper compilation:
gleam deps download
make -C build/packages/gargamelle/priv/regex-src
Native Erlang setup documents tested runtimes and deployment requirements.
Basic example
One definition generates the schema and validates JSON during decoding:
import gargamelle
import gleam/io
import gleam/string
pub fn main() {
let definition: gargamelle.Definition(List(String)) = gargamelle.array(gargamelle.string())
let schema: String = gargamelle.schema_string(definition, gargamelle.Pretty)
let assert Ok(json): Result(gargamelle.Json, _) = gargamelle.parse("[\"Brainy\", \"Jokey\"]")
let assert Ok(data): Result(List(String), _) = gargamelle.decode(definition, json)
io.println(schema)
io.println(string.join(data, ", "))
}
Output:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"items": {
"type": "string"
},
"type": "array"
}
Brainy, Jokey
Definition(List(String)) describes both accepted JSON and decoded output.
parse returns opaque Json; decode produces List(String). The Result
annotations describe the whole Ok(...) pattern; _ leaves the error type inferred.
schema_string returns the schema as a String. Pretty uses two-space
indentation; Compact produces canonical JSON. to_string(json, layout) serializes
any Gargamelle Json, not just schemas.
Parsing and decoding errors are separate results. The example uses assertions
for brevity; application code handles those errors explicitly. validate checks
acceptance without constructing the decoded output.
Receiving boundaries
A boundary binds a handler to its input contract. Submission checks JSON against the stored contract and invokes the handler only on success, combining validation and handler invocation in one operation.
This complete example uses the same array-of-strings definition for two receivers:
import gargamelle/boundary as gargamelle_boundary
import gargamelle
import gleam/io
import gleam/string
pub fn main() {
let names: gargamelle.Definition(List(String)) = gargamelle.array(gargamelle.string())
let assert Ok(json): Result(gargamelle.Json, _) = gargamelle.parse("[\"Brainy\", \"Jokey\"]")
let receiver = gargamelle_boundary.new(
gargamelle.contract(names),
fn(decoded_names, _original_json) { string.join(decoded_names, ", ") },
)
let assert Ok(response): Result(String, _) = gargamelle_boundary.forward(receiver, json)
io.println(response)
let json_receiver = gargamelle_boundary.json(
gargamelle.contract(names),
fn(verified) {
gargamelle.to_string(gargamelle.verified_json(verified), gargamelle.Compact)
},
)
let assert Ok(response): Result(String, _) = gargamelle_boundary.forward_json(json_receiver, json)
io.println(response)
}
Output:
Brainy, Jokey
["Brainy","Jokey"]
Both boundaries check their stored contract before invoking the handler.
Boundary also decodes and passes the typed data and original JSON;
JsonBoundary delivers a VerifiedJson certificate. Contracts without semantic
checks validate without decoding; semantic checks require one decoding pass.
Structural or semantic rejection invokes neither handler.
VerifiedJson(a) retains the original admitted JSON and the exact contract that
accepted it. It does not contain a decoded a. The type parameter identifies the
definition's output type, not its particular constraints: two definitions producing
String can accept different inputs. Receiving boundaries always check their own
stored contract; a certificate from another contract cannot bypass that check.
definition, json_definition, output_definition and paired_definition
expose each boundary's structural definition for inspection and schema generation.
Verified JSON boundaries
documents certificate retention and application responses.
Guarantees and scope
- Validation, decoding acceptance and the generated schema describe the same structural rules within the documented JSON domain and validator settings.
- Receiving boundaries validate before invoking a handler; structurally invalid input runs neither decoding conversions nor the handler. Semantic rejection also skips the handler.
- Semantic requirements are added with
require(contract, description, check). They inspect decoded values and can only reject. Their descriptions appear indocumentation.render_contract; generated schemas describe the structural definition only. - Application rules, such as whether a score agrees with its answers, are not inferred automatically. They require explicit semantic checks.
- Conversion callbacks and semantic requirements must be pure and total. Callback or handler exceptions and resource failures remain operational failures, rather than validation errors.
- The opaque Gleam APIs enforce access through public operations. They are not a sandbox against hostile code in the same runtime.
The technical contract specifies the JSON domain, external validator settings, decoded-value semantics and limits.
Typed records
The core builders consume a curried constructor. During decoding, each field supplies an argument to a one-argument function. gargamelle/record accepts an ordinary constructor and chains the construction Results into one pipeline.
These two definitions accept the same JSON, produce the same User values and
generate identical schemas:
import gargamelle
import gargamelle/record
pub type User { User(name: String, age: Int, active: Bool) }
// Without gargamelle/record: explicit currying and separate Result handling.
pub fn curried_user_definition() -> gargamelle.Definition(User) {
let constructor = fn(name) {
fn(age) { fn(active) { User(name, age, active) } }
}
let assert Ok(fields) =
gargamelle.record(constructor)
|> gargamelle.required("name", gargamelle.string())
let assert Ok(fields) = gargamelle.required(fields, "age", gargamelle.safe_integer())
let assert Ok(fields) = gargamelle.required(fields, "active", gargamelle.boolean())
gargamelle.finish(fields, gargamelle.Strict)
}
// With gargamelle/record: the ordinary constructor and one Result pipeline.
pub fn user_definition() -> gargamelle.Definition(User) {
let assert Ok(definition) =
record.start3(User)
|> record.required("name", gargamelle.string())
|> record.required("age", gargamelle.safe_integer())
|> record.required("active", gargamelle.boolean())
|> record.finish(gargamelle.Strict)
definition
}
pub fn read_user(source: String) {
let assert Ok(json) = gargamelle.parse(source)
gargamelle.decode(user_definition(), json)
}
For input {"name":"Brainy","age":42,"active":true}, read_user returns
Ok(User("Brainy", 42, True)). gargamelle.Strict rejects undeclared fields.
gargamelle.schema_string(user_definition(), gargamelle.Pretty) generates the record’s schema.
start1 through start32 accept ordinary constructors without explicit currying.
required, optional, defaulted, and finish preserve the existing semantics
and propagate the first construction error. The generated range is not a limit
on record size: larger records can use record.start with an explicitly curried
constructor. Field definitions remain static in both APIs.
For records that also require encoding, gargamelle/codec_record shares field
names and child codecs between the definition and encoder. It returns the existing
encoding codec and rejects child semantic requirements. The
encoding guide
shows the paired declarations and optional/defaulted field policies.
More definitions
| Feature | Constructors |
|---|---|
| Arbitrary admitted JSON | anything |
| Recursive structures | recursive, recursive_pair |
| Tuples and array membership | tuple, element, contains |
| Object key and presence constraints | property_names, dependent_required |
| Conditional constraints and exclusion | if_then, if_then_else, exclude |
| Numeric constraints | bounds, number_bounds, integer_multiple_of |
| Schema metadata | title, description, examples, default_annotation, format_annotation |
| Explicit UUID validation | assert_format(_, Uuid) |
Metadata does not change acceptance. A schema default annotation does not insert
a value; a defaulted record field is a separate decoding feature. format_annotation adds an
annotation, while assert_format adds validation constraints.
Advanced definitions documents these features and the HTML documentation recipe.
Limitations
JavaScript is tested on Node 24.10.0, Chrome 155, Firefox 157 and Safari 27. Native Erlang requires a C regex helper and is tested on macOS arm64 with OTP 29 and Ubuntu 24.04 x86_64 with OTP 28.5.0.7 and 29.1.1. Browser compatibility and Native Erlang setup document the compatibility matrix, regex Unicode differences and deployment requirements. Other runtimes and platforms are unverified; Windows native support is unavailable.
- Gargamelle supports the JSON Schema features exposed by its constructors. It does not validate arbitrary imported schemas or implement the full 2020-12 dialect. The technical contract, section 16 lists keyword coverage and restrictions.
- JSON numbers are finite parsed binary64 values;
safe_integeruses JavaScript's safe-integer range. Strings and object keys must contain Unicode scalar values. - General typed intersections, fractional divisibility and fractional constants
are unsupported.
integer_multiple_ofsupports exact safe-integer divisibility; UUID is the only supported explicit format assertion. - Runtime resource use is not bounded. Parsing may round number literals and collapse duplicate object keys.
- Encoders require explicit getters and projections; no automatic derivation, decode/encode inverse or migration API is provided. Defaults, projection and maps can lose information during decoding. Encoding creates temporary JSON text for admission. Encoding failures identify the output field or array element with a JSON Pointer and a typed reason.
Compatibility commitments are specified in the technical contract, section 18.
Related libraries
Gargamelle was originally inspired by glon, but is not a fork.
Sextant also combines typed decoding with
JSON Schema 2020-12 generation. Its use-based field API supports definitions whose
later fields depend on earlier decoded values. Gargamelle uses static definitions,
with ordinary or explicitly curried record constructors. Its schema describes
structural acceptance, while application rules are checked separately. Receiving
boundaries bind structural definitions and semantic requirements
to handlers.
Further documentation
- Technical contract: complete intended acceptance, output, emission and error semantics.
- Advanced definitions: numeric constraints, recursion, tuples, key constraints, membership, conditionals, exclusion and HTML documentation.
- Constructing JSON values: public constructors for opaque admitted JSON.
- Typed JSON encoding: explicit encoders, checked output and typed receiving paths.
- Verified JSON boundaries: decoded and JSON-only receiving handlers, with paired loading and saving.
- Diagnostic presentation: bounded summaries and complete structured error reports.
Verification
The library is checked with typed-output and rejection fixtures, generated compositions, independent JSON Schema validators, selected official suite cases and deliberate implementation mutations. These provide evidence for the contract, not a formal proof or full-dialect conformance. The package source is available in the repository and the Hex archive.
License
Gargamelle is distributed under the MIT License. Licenses contains the library, native regex engine and retained JSON Schema test-suite notices.
Authorship
This package was authored by Codex Astra, with occasional direction and review from the human repository maintainer.