Skip to content

Static helpers

Validation modes: Validation modes reference

Every operation that takes a registered schema also has a static counterpart on JsonTology. The static form builds a one-shot ephemeral registry containing only the supplied schema, runs the operation, and discards the registry.

Use static when you do not need to reuse a registry across calls.

The bookstore schemas defined in the Bookstore Domain are used in the example.

Catalogue

StaticPurposeInstance equivalent
JsonTology.is(schema, data)Boolean type guardjt.is(id, data)
JsonTology.validate(schema, data)Returns ValidationErrorsjt.validate(id, data)
JsonTology.instantiate(schema, data, options?)Validates and returns the typed valuejt.instantiate(id, data)
JsonTology.materialize(schema, partial?, options?)Fills defaults; throws on validation failurejt.materialize(schema, ...)
JsonTology.subschemaAt(schema, pointer)Resolves a sub-schema by JSON Pointerjt.subschemaAt(id, pointer)
JsonTology.dump(schema, value, options?)Serializes to wire formjt.dump(id, value)
JsonTology.dumpJson(schema, value, options?)Serializes to JSON stringjt.dumpJson(id, value)
JsonTology.toQuads(schema, data)Projects instance to ABox quadsjt.toQuads(schema, data)
JsonTology.fromQuads(schema, quads)Lifts quads back to typed objectsjt.fromQuads(id, quads)
JsonTology.toSchema(schema)Reconstructs JSON Schema from the canonical graphjt.toSchema(id)
JsonTology.toTbox(schemas)Returns OWL TBox builder for the given schemasjt.toTbox()
JsonTology.toShacl(schemas)Returns SHACL shapes builder for the given schemasjt.toShacl()
JsonTology.ontology(schemas)Returns combined TBox + SHACL builderjt.ontology()

The single-schema statics accept a schema object (not a string $id) because they need the full document to register internally. The multi-schema statics (toTbox, toShacl, ontology) accept a ReadonlyArray of schema objects.

When to pick which

  • Static. Self-contained schema, one or two operations, no shared state with other schemas.
  • Instance. Multiple schemas that $ref each other, repeated operations on the same schema, registered computed fields or invariants, format plugins, vocabulary plugins, or anything that reuses validation state.

A static call rebuilds the canonical graph for every invocation. An instance reuses the registry's compiled validators, materializer, and graph cache.

Comparison: instance vs static for validate

/**
 * Static helpers: instance vs static for validate
 *
 * The instance form reuses the registry's compiled validators across calls.
 * The static form builds an ephemeral registry, registers the schema, runs
 * the operation, and discards the registry — useful for one-off scripts
 * and self-contained schemas.
 *
 * Both return the same `ValidationErrors` collection for the same data.
 *
 * Pick the static form for one-off scripts or examples; pick the instance
 * form when multiple schemas reference each other or when you need
 * registered invariants and computed fields.
 */

import { JsonTology } from '../../../src/index.js';
import {
  aboxFixtures, bookstoreEntities, CustomerSchema, IsbnSchema
} from '../bookstore/index.js';

// Instance form — CustomerSchema was registered once at JsonTology.create()
// time; every call reuses the compiled validator. CustomerSchema references
// AddressSchema, EmailSchema, etc. — all resolved via the shared registry.
const errs = bookstoreEntities.validate(CustomerSchema.$id, aboxFixtures.customer);

console.assert(errs.length === 0);

// Static form — builds an ephemeral one-shot registry for a single schema,
// runs validate, discards the registry. Each call repeats the compilation.
// Use the static form for self-contained schemas with no cross-schema $ref.
// IsbnSchema is a plain string primitive: no external $ref needed.
const errs2 = JsonTology.validate(IsbnSchema, aboxFixtures.rareBook.isbn);

console.assert(errs2.length === 0);

// Both return empty ValidationErrors for valid data.
console.assert(errs.length === 0);
console.assert(errs2.length === 0);

console.log('instance validate error count (CustomerSchema):', errs.length);
console.log('static validate error count (IsbnSchema):', errs2.length);
console.log('customer name:', aboxFixtures.customer.name);
console.log('isbn validated:', aboxFixtures.rareBook.isbn);
Output
Press Execute to run this example against the real library.

The two forms return the same ValidationErrors collection. Pick the static form for one-off scripts, examples, and self-contained schemas; pick the instance form for everything else.

JsonTology.create options

Options marked Compile-time affect type inference only; options marked Runtime affect the validation or materialization path. See Validation modes for the badge reference.

OptionTypeDefaultPurpose
baseIristring(required)Base URI for the canonical graph and ontology output.
schemasreadonly Schema[][]Schemas to register at construction. Order matters when using $ref: register referenced schemas before referencing schemas.
prefetchedSnapshotInterface(none)Pre-resolved schema bundle produced by JsonTology.prefetch. Schemas passed via schemas register first; entries from the snapshot then fill any IRIs not already in the registry. schemas wins on $id collision. See Schema federation.
prefixesRecord<string, string>STANDARD_PREFIXESVocabulary prefix → IRI mappings, merged with built-in defaults (rdf, rdfs, owl, sh, xsd, schema, foaf, dc, dcterms, dcat, skos, prov, time, geo, vann, dash, jt).
formatsRecord<string, FormatValidatorFn>{}Custom format validators. Keys are format names ('isbn'), values are (value: unknown) => boolean.
enableTypeCastbooleanfalseEnable string→number/boolean coercion at validation time.
enableStrictTypesbooleanfalseReject implicit coercions globally. Per-field jt:strict overrides. Different from enableStrictGraph.
enableDefaultsbooleantrueFill schema default values during instantiate. Set false to validate without mutating missing fields.
enableDebugbooleanfalseSurface internal debug logging via logger.debug (graph construction, validator compilation, materialization steps). Useful when investigating unexpected validation outcomes.
enableInlineWarningsbooleantrueSurface inline-object, inline-primitive, and inline-array-items warnings via logger.warn at registration. Forced true when enableStrictGraph is on; pass false explicitly to opt out. See graph-native authoring.
enableDuplicateDetectionbooleantrueRun findDuplicates() at registration and warn on structural duplicates. Forced true when enableStrictGraph is on; pass false explicitly to opt out.
enableStrictGraphbooleantruePromote inline warnings and duplicate detection to SchemaError throws. Requires all sub-schemas to be standalone $id schemas or $defs entries. Pass false to opt out. See strict graph mode.
keywordsKeywordDefinitionInterface[][]Custom keyword handlers for unrecognized JSON Schema vocabulary.
vocabulariesVocabularyPluginInterface[][]Vocabulary plugins for custom RDF output (DCAT, FOAF, etc.).
materializerMaterializerOptionsInterface(built-in)Override the default materializer (rare).
maxSchemaDepthnumber(no limit)Maximum schema-graph traversal depth. Protects against pathological schemas.
loggerLoggerInterfaceSILENT_LOGGERLogger for warnings (enableInlineWarnings, enableDuplicateDetection). Must be set for warnings to surface.
invariantsRecord<string, InvariantInterface[]>{}Cross-field invariant functions, keyed by schema $id.
computedsRecord<string, Record<string, ComputedFnType>>{}Computed-field functions, keyed by schema $id then property name.

Type inference options

These options are configured via module augmentation in a .d.ts file, not through JsonTology.create. They affect InferType output only and have zero runtime cost.

FlagDefaultPurpose
tightStringLengthsfalseCompile-time Narrow strings with minLength/maxLength bounds within 8 to fixed-length template literals. Opt in with declare module 'json-tology/types' { interface JsonTologyTypeConfigInterface { 'tightStringLengths': true } }.

See Constraint brands - tightStringLengths for the full reference.

Graph emission options

These options control how toQuads mints subject IRIs and how fromQuads reverses them. See Skolemization for the full reference.

OptionTypeDefaultPurpose
iriForSkolemizeFnType | string(content-hash)Default IRI minting strategy for toQuads. A regular string becomes a root-only override; the string 'blank-node' is a runtime-recognised constant that emits anonymous subjects (not a discriminated type member); a function matching SkolemizeFnType is the full custom minting shape. Per-call options override this.
defaultGraphIristring(none)Default graph field for every quad emitted by toQuads. Per-call graphIri overrides.
defaultDeskolemizebooleanfalseTreat */.well-known/genid/* IRIs as blank nodes during fromQuads. Reverses Skolemize.wellKnownGenid.

See also

Released under the MIT License.