WebAssembly (browser)
jlens-wasm compiles jlens to WebAssembly as an ES module for browsers. It covers what the
Rust crates do:
- evaluation;
- audit trees and explanations;
- schema inference;
- the language service (completion, diagnostics, hover, signature help) for editors.
It also runs in Node.js 20+ and Deno, provided init is given the .wasm bytes. A
classic script with the .wasm embedded serves a page opened from
disk, and anything that cannot resolve the .wasm file.
import init, { Expression } from "jlens-wasm";
await init();
const expr = new Expression("$sum(items[type = $kind].(price * qty))");
expr.evaluate({ items: [{ type: "a", price: 2.5, qty: 4 }] }, { kind: "a" }); // 10
Building the package
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version <the wasm-bindgen version in Cargo.lock> --locked
cargo xtask wasm # release build into crates/jlens-wasm/pkg
cargo xtask wasm --dev # unoptimized, with Rust panics reported on the console
cargo xtask wasm does five things:
- It compiles the crate with the
wasm-releaseprofile, which optimizes for size and speed (opt-level = "s"), with link-time optimization. It builds thecdylibalone (cargo rustc --crate-type cdylib), since Cargo leaves the profile’sltoout of acargo buildof a crate that is anrlibtoo. - It generates the JavaScript glue and the TypeScript declarations with
wasm-bindgen --target web. - It runs
wasm-opt -Osfrom binaryen: the installed one, or the npm package throughnpx. Without either, the module is about 45% larger. - It writes
jlens.global.js, the same package as one classic script. - It writes
package.json.
The wasm-bindgen CLI must be the exact version in Cargo.lock, and the task checks this.
| File | Contents |
|---|---|
jlens.js | The ES module |
jlens.d.ts | TypeScript declarations |
jlens_bg.wasm | The WebAssembly module: about 1.7 MiB, 673 KiB gzipped |
jlens.global.js | The package as one classic script, the module embedded: about 2.4 MiB, 968 KiB gzipped |
jlens.global.d.ts | TypeScript declarations of its global, jlens |
package.json | npm metadata: "type": "module", exports, types |
A size budget for the gzipped module is enforced in xtask/src/wasm.rs.
Loading the module
Call init() once, and await it, before using anything else. By default it fetches
jlens_bg.wasm from next to jlens.js:
<script type="module">
import init, { Expression } from "./pkg/jlens.js";
await init();
</script>
Bundlers that understand new URL(..., import.meta.url) handle this as is. Vite, webpack 5,
Rollup and esbuild all do (esbuild with a loader for .wasm). Otherwise, pass the module’s URL
or its bytes:
// Vite: get the URL of the asset.
import wasmUrl from "jlens-wasm/jlens_bg.wasm?url";
await init({ module_or_path: wasmUrl });
// Node.js or Deno: pass the bytes.
import { readFile } from "node:fs/promises";
await init({ module_or_path: await readFile(new URL("./pkg/jlens_bg.wasm", import.meta.url)) });
initSync({ module }) instantiates synchronously from bytes or a WebAssembly.Module. This is
useful in workers.
One file: jlens.global.js
A page opened from disk, at a file:// address, can neither import a module nor fetch, so it
cannot load jlens.js. jlens.global.js is the same package as one classic script, with
jlens_bg.wasm embedded in base64. It sets one global, jlens, which holds the exports of
jlens.js, with init for its default export. With no argument, init() and initSync()
instantiate the embedded module:
<script src="jlens.global.js"></script>
<script>
jlens.init().then(() => {
const expr = new jlens.Expression("$sum(items.(price * qty))");
console.log(expr.evaluate({ items: [{ price: 2.5, qty: 4 }] })); // 10
});
</script>
It also serves what cannot resolve the .wasm file: a classic worker loads it with
importScripts("jlens.global.js"), and a module, a module worker or a bundler with
import "jlens-wasm/global", which runs the script and sets the global. In TypeScript, that
import declares it too; a classic script references it with
/// <reference types="jlens-wasm/global" />.
Its cost is size: the .wasm in base64 is a third larger, about 2.4 MiB, and 968 KiB gzipped
against 673 KiB for jlens_bg.wasm, as base64 compresses less well
(serving the module compares them). A page that loads it pays for the
whole module even if it never calls init, and the npm package unpacks to 4.4 MB, of which the
script takes 2.5 MB. Starting is no slower: in Node.js 22, reading
the script and init() take about 19 ms, and the module with its bytes about 26 ms. jlens.js
does not change, nor what importing it loads. Each loads a module of its own, so a page that
loads both has two instances, with classes that do not mix.
cargo xtask wasm writes it from the module that wasm-bindgen generates, putting each of its
JavaScript snippets in a function of its own. It changes only what it recognises in the output
of the wasm-bindgen version in Cargo.lock, and the build fails on anything else. The Node.js
and browser tests run the whole suite against it, and open a page from file:// that loads it
with one <script>.
Serving the module
Content-Security-Policy
A Content-Security-Policy decides whether a page may compile WebAssembly, as it decides for
eval. A page whose policy has a script-src directive, or only a default-src, needs
'wasm-unsafe-eval' in its script-src:
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'
'wasm-unsafe-eval' allows compiling WebAssembly and nothing else: eval and new Function
stay forbidden, and jlens uses neither. 'unsafe-eval' would allow the module too, but those as
well. Without either, init() rejects with a WebAssembly.CompileError, from jlens.js and
jlens.global.js alike. In Edge, as in the other Chromium browsers, it reads:
CompileError: WebAssembly.instantiateStreaming(): Compiling or instantiating WebAssembly module violates the following Content Security policy directive because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'".
and in Firefox call to WebAssembly.instantiateStreaming() blocked by CSP, with
WebAssembly.instantiate() in both when it comes from jlens.global.js. The message names
'unsafe-eval', but 'wasm-unsafe-eval' is the narrower fix.
jlens.js also fetches jlens_bg.wasm, so the policy’s connect-src, or its default-src,
must allow the module’s origin. Otherwise init() rejects with a TypeError before compiling
anything: Failed to fetch in Edge, NetworkError when attempting to fetch resource. in Firefox. jlens.global.js fetches nothing.
These were tried with the policies above sent as headers, in Edge 158 and Firefox 160.
Size
| What the page loads | Size | gzip | brotli |
|---|---|---|---|
jlens.js and jlens_bg.wasm | 42 KiB + 1.7 MiB | 9 + 673 KiB | 8 + 496 KiB |
jlens.global.js | 2.4 MiB | 968 KiB | 686 KiB |
The sizes of 0.37, brotli at its highest quality, 11. To serve the module small:
- Compress
jlens_bg.wasmwith brotli, sent withContent-Encoding: br: a quarter smaller than with gzip. A server that compresses as it sends often uses a lower quality (at 5, the module is 571 KiB); compressing the file once when deploying, at quality 11, and serving that copy keeps the smaller size. - Send it with
Content-Type: application/wasm.init()then compiles the module withWebAssembly.instantiateStreaming, while it downloads. With any other type, it warns on the console and compiles only once the whole module has arrived. - Load
jlens.jswith the.wasmbeside it, notjlens.global.js, wherever the page can load a module. The module in base64 compresses worse, a third more with brotli, and it is decoded and compiled only once the whole script has arrived.jlens.global.jsis for what cannot fetch the.wasm: a page opened from disk, a classic worker.
Evaluating expressions
const expr = new Expression(source); // compile once (throws JlensError on syntax errors)
expr.evaluate(input, bindings, options); // evaluate many times
expr.evaluateJson(jsonText, bindings); // JSON text in, JSON text out
expr.free(); // release it (or let the garbage collector do so)
inputcan be any JSON-compatible value.undefined, or no argument, means there is no input document, so$is undefined. Values are read asJSON.stringifyreads them. As a result,Dateobjects become strings, and functions andundefinedfields are dropped. See how the input is read.bindingsis an object of variables and functions:{limit: 10}makes$limitavailable, and a function becomes a host function.optionssets the limits (timeout,maxDepth,maxSteps,maxStringLength,maxArrayLength,maxResultSize), and the clock and seed that make an evaluation reproducible:nowfixes$now()and$millis()(milliseconds since the epoch, aDateor an ISO 8601 timestamp), andseedfixes$random()and$shuffle(). The options are read from the object, unlike the input: each once, as a property, so a getter or an inherited option works, andtoJSONis not called.undefinedandnullmean the default; a number must be finite, soNaNorInfinitythrows aTypeError, as an invalidDatedoes.- The result is a plain value, or
undefinedwhen the expression evaluates to undefined. Numbers are the same as in jsonata-js. An object of the result is a JavaScript object, so its integer-like keys come first, as in jsonata-js. Inside the expression, an object it builds keeps its keys in insertion order, which$keys,$string,$eachand$spreadshow, and so does the textevaluateJsonreturns (compatibility).
evaluateJson takes the input as JSON text and returns the result as JSON text. For large
documents that you already have as text, such as a fetch response body, it avoids converting
the document to JavaScript objects and back. While it parses, it skips the fields the expression
does not read, checking them as JSON syntax only.
How the input is read
evaluate reads its input during the evaluation, one object or array at a time, when the
expression first reaches it (ADR 0010). A path such as
customer.name reads two small objects, however large the rest of the document is. An object or
array of more than 16 values is read whole, with everything it holds, through JSON.stringify,
which is faster than reading its values one by one. An index into an array, such as
items[0] or items[$i], reads the items it picks alone, however long the array is.
Two consequences follow:
- Errors appear when their part is read. A cycle, a
BigInt, or atoJSONmethod that throws makesJSON.stringifythrow.evaluatethrows the same exception, but only when the expression reads the object or array that holds it: an expression that never reaches it succeeds. - The input must not change during the evaluation. A host function that modifies the input object can change what the rest of the evaluation reads. Copy the input first if a function must modify it.
evaluateJson converts the fields the expression reads first; evaluateWithAudit and
Document convert their whole input first.
Reusing a document
evaluate reads the parts of the input that the expression reaches, on every call. For an
expression that reads most of a document of a few dozen kilobytes, that costs hundreds of
microseconds, often more than the evaluation itself. To evaluate several expressions against
one document (a set of rules, say), convert it once:
import { Document } from "jlens-wasm";
const doc = new Document(input); // or Document.fromJson(text)
const results = rules.map((rule) => rule.evaluateDocument(doc, bindings));
doc.free();
Evaluations never modify a document. Performance has measurements.
With explicit resource management, using expr = new Expression(...) frees the expression at
the end of the block.
Host functions
JavaScript functions, in the bindings or registered on an expression, are called from the expression like built-in functions:
const expr = new Expression("$shipping($sum(items.weight), region)");
expr.evaluate(order, { shipping: (weight, region) => weight * rates[region] });
// As in jsonata-js: available to every evaluation, with an optional signature.
expr.registerFunction("shipping", (weight, region) => weight * rates[region], "<ns:n>");
- Arguments and the result pass through JSON, like the input.
undefinedstands for undefined, and a function argument arrives as a JavaScript function that calls it (below). - A signature (
registerFunction’s third argument) checks the arguments before each call, with the errors of the built-in functions (T0410,T0412). A parameter with-receives the context value when the argument is missing:<n-:n>makesprice.$double()work. thisisundefined. Use a signature with-to receive the context value.- The function’s
lengthtells higher-order functions how many arguments to pass:$mappasses the index only to functions with two parameters or more. - An exception thrown by the function is rethrown by
evaluateas is. Itspositionandtokenare set to the call when it has none.evaluateWithAuditreports it with itscode, or itsname, and itsmessage. - Asynchronous functions are not supported. A function that returns a promise fails with
U1002. Fetch what the expression needs before evaluating it. - Precedence: a function in the bindings replaces a registered function of the same name, and both replace a built-in function.
The Rust crate guide describes the same model.
Functions as arguments
A host function can call a JSONata function it receives, such as a fallback or a step to retry: a lambda, a built-in function, a partial application, a chain or another host function.
const retry = (step, times) => {
for (let i = 1; ; i++) {
try {
return step(i);
} catch (e) {
if (i >= times) throw e;
}
}
};
new Expression("$retry(function($i) { $lookup(sku, $i) }, 3)").evaluate(order, { retry, lookup });
- The call is part of the evaluation, as when
$mapcalls its function. The context value isnull, and a lambda keeps the variables of its definition. The call counts as a level of depth, so a recursion through a host function ends withD1011; it checks the timeout; its result is limited bymaxResultSize. - It is synchronous: it returns the result, where jsonata-js returns a promise. Code written
for jsonata-js with
await step(i)keeps working. - Arguments and the result pass through JSON. A sequence comes back as an array or a single
value; a JavaScript function among the arguments becomes
undefined, and a function result comes back asundefined. - Its
lengthis 0 and itsarityproperty is the number of parameters, as in jsonata-js. - Errors are thrown as a
JlensErrorwith their codes, or as the exception a host function threw. The host function can catch them, or let them through, which ends the evaluation with that error. - It is valid until the host function returns. Called later, from a promise or a timer, it
throws
U1005.
Errors
Errors are Error objects named JlensError. They carry the JSONata error fields; every offset is
in UTF-16 code units, like JavaScript string indexes:
try {
new Expression("Account.Order[0;]");
} catch (err) {
if (err.name !== "JlensError") throw err;
err.code; // "S0202"
err.message; // 'Expected "]", got ";"'
err.position; // 16: where it was detected, as in jsonata-js
err.start; // 15: the offending source range
err.end; // 16
err.token; // ";"
}
Evaluation errors carry value too, when there is one (for T2001, the value that is not a
number). Invalid arguments, such as bindings that are not an object or malformed JSON for
evaluateJson, throw a TypeError instead. The error reference lists
every code.
The fields an expression reads
reads() tells which fields of its input and of each binding an expression may read, without
evaluating it (ADR 0016): an application can fetch only those from
a database, or know which rules depend on a field. unionReads combines the answers of several
expressions.
const expr = new Expression("$sum(items[type = $kind].(price * quantity)) * $rate(country)");
expr.reads({ rate: (country) => rates[country] });
// {input: {country: true, items: {price: true, quantity: true, type: true}},
// bindings: {kind: true, rate: true}}
unionReads([expr.reads({ rate }), new Expression("customer.name").reads()]);
// {input: {country: true, customer: {name: true}, items: {...}}, bindings: {...}}
- The answer is an upper bound.
truereads the value whole; an object reads only the fields it lists, of an object, or of each item of an array; an empty object needs the value but none of its fields, as$countdoes. On its input and bindings cut down that way, an expression gives the same result, or fails with the same error code. Where the analysis cannot follow a value, under*or**, in a constructed object or in the result, it reads the value whole. - Pass the bindings the expression will be evaluated with. A JavaScript function cannot
read the context of its call (
thisisundefined), so a call to one in the bindings, or registered on the expression, reads only its arguments, and the context a-parameter may take. A call to a function the analysis does not know may read its context: the whole input, at the top of an expression. everyBinding: truesays the expression may read any binding whole, as$evalcan: keep them all.- A binding named after a built-in function shadows it during the evaluation, but the analysis takes the name as the built-in’s: such an application cannot cut its input by it.
Document.fromJson(text, read) parses JSON text cut by a Read, the input of reads() or
of unionReads(). It skips the fields the Read leaves out, which on a wide document is several
times faster (Performance), and the document serves each
expression that went into the union as the whole one would:
const rules = sources.map((source) => new Expression(source));
const { input } = unionReads(rules.map((rule) => rule.reads(bindings)));
const doc = Document.fromJson(text, input);
const results = rules.map((rule) => rule.evaluateDocument(doc, bindings));
The fields skipped are checked as JSON syntax only: a number too large for a float, which a full parse rejects, passes there.
Explaining results
evaluateWithAudit evaluates and records how the result was reached; see the
audit guide. Evaluation errors are reported in the result, not thrown:
const expr = new Expression('/** @label "Big order" */ $sum(items.(price * qty)) > $limit');
const { result, error, audit, explanation, explanationText } = expr.evaluateWithAudit(
{ items: [{ price: 2.5, qty: 4 }, { price: 1, qty: 3 }] },
{ limit: 20 },
{ level: "decisions", limits: { maxNodes: 1000 } },
);
result; // false
explanationText; // 'result: false\n✘ Big order — $sum(items.(price * qty)) > $limit → false (13 > 20)'
audit.root; // { kind: "binary", op: ">", label: "Big order", operands: [13, 20], outcome: "false", ... }
The options are those of evaluate, plus two more:
levelis"off","decisions"(the default) or"full".limitssets the capture limits:maxItems,maxString,maxDepth,maxRejected,maxNodesandmaxSource.
explanation.lines holds structured lines (depth, passed, text, message, node) for
rendering in a user interface. Audit node spans are UTF-16 offsets, so a viewer can highlight
a node’s source in the editor. The web editor example does this.
Tooling
parseRecover(source) never throws. It returns the partial syntax tree and every diagnostic:
parseRecover("Account.Order[0;].");
// { ast: {...}, diagnostics: [{ severity: "error", code: "S0202", message: ..., span: {start: 15, end: 16} }] }
expr.ast() returns the processed tree of a compiled expression, and functions() returns the
catalog of built-in functions. Spans are UTF-16 offsets throughout.
Schemas
inferSchema(samples, overrides?) infers a JSON Schema 2020-12 from sample documents. The
schema guide describes what it records and the overrides format:
const schema = inferSchema([doc1, doc2], {
"items[].type": { description: "Product category", enum: ["apparel", "electronic", "toy"] },
"items[].internalCode": { hidden: true },
});
The result is an ordinary JSON Schema object. Store it, edit it by hand, or pass it to
LanguageService.
An override path the samples lack declares a new field, which is what a misspelt path does too.
missingOverridePaths(samples, overrides) lists those paths, each with the existing path it most
likely meant, so that an editor can warn about them:
missingOverridePaths([order], { "items.type": { enum: ["apparel"] }, "customer.vip": {} });
// [{ path: "customer.vip" }, { path: "items.type", suggestion: "items[].type" }]
The language service
const service = new LanguageService({ schema, variables: { limit: { type: "number" } } });
const text = "items[type = 'a'].p";
service.complete(text, text.length);
// { range: {start: 18, end: 19},
// items: [{ label: "price", kind: "field", detail: "integer", documentation: "Examples: `1`", insertText: "price" }] }
service.diagnostics("customer.Login");
// [{ severity: "warning", code: "W0201", span: {start: 9, end: 14},
// message: 'Field "Login" is not in the schema; did you mean `login`?' }]
service.hover("customer.login", 10);
// { range: {start: 9, end: 14}, contents: '`login`: string\n\nExamples: `"1"`' }
service.signatureHelp("$substring(name, ", 17);
// { name: "$substring", signature: "<s-nn?:s>", params: ["$str", "$start", "$length"], activeParam: 1, ... }
The constructor takes one object of options, each optional:
| Option | What it gives |
|---|---|
schema | The JSON Schema of the input documents. Without one, functions and variables are still completed |
variables | The variables the expressions are evaluated with: its keys are their names, with or without $, and its values are schemas, or null when the shape is unknown |
functions | The host functions, as {name, signature, params, summary} objects. They are completed first, and hover and signature help show them |
sources | The documents that the $refs of the schemas lead to, below |
resultType, contextPath | What the expressions are, below |
new LanguageService({
schema,
functions: [
{ name: "shipping", signature: "<ns:n>", params: ["weight", "region"], summary: "Shipping cost" },
],
});
Create a new service when an option changes. Construction is cheap.
An option the constructor does not have throws a TypeError, a misspelt one included. So does
a call in the form before 0.35, whose arguments were positional, the schema first: a schema is
not taken for the options, and neither is a second argument.
Completion items are ranked best first, and insertText replaces range. Field names that are
not plain identifiers come quoted with backquotes. kind is field, variable, function,
keyword, operator or value: a value of the enumeration of the left-hand side of =, != or
in, inserted as a JSONata literal. Inside a string literal, range covers the whole literal,
quotes included, and only values are suggested; open the list after = and on a quote to
offer them while typing. documentation and hover contents are Markdown.
A field with an open domain (x-jlens-domain, or domain in the
overrides) takes values only the application can fetch. Where its values are completed,
complete also returns a valueRequest; fetch the values, then write each with valueLiteral:
const schema = inferSchema([order], { "customer.login": { domain: "customers" } });
const service = new LanguageService({ schema });
const text = "customer.login = 'al";
const { range, items, valueRequest } = service.complete(text, text.length);
// valueRequest: { domain: "customers", path: "customer.login", prefix: "al",
// range: {start: 17, end: 20}, quote: "'", conditions: [], inArray: false,
// listed: [] }
const logins = await fetchCustomers(valueRequest.prefix); // the application's own source
const options = logins.map((login) => valueLiteral(login, valueRequest.quote)); // "'alice'"
range is the same as the completions’ range, in UTF-16 units. valueLiteral(value, quote?)
writes a string in quote (" by default) when it can, and other values as JSON.
conditions lists the fields fixed to literals beside the value, for a domain whose values
depend on another one; inArray says whether the value is an element of in [...], where
several may be inserted, and listed holds the literals already in that array, not to offer
again (schema guide):
// A schema whose items[].categories[].subgroup has a domain
const text = "items[categories[group = 'Electronics' and subgroup in ['TVs', '";
const { valueRequest } = service.complete(text, text.length);
// valueRequest.conditions: [{ path: "items[].categories[].group", values: ["Electronics"] }]
// valueRequest.inArray: true
// valueRequest.listed: ["TVs"]
CodeMirror 6
CodeMirror positions are UTF-16 offsets, like jlens offsets, so no conversion is needed.
examples/web-editor/jlens-codemirror.js in the repository
is a self-contained module to copy. It provides highlighting, completion, linting, hover and
signature help, and takes an asynchronous source for the values of open domains
(jlensExtensions(getService, signatureElement, { values })). The core of it is:
autocompletion({
override: [(context) => {
const { range, items } = service.complete(context.state.doc.toString(), context.pos);
return {
from: range.start, to: range.end, filter: false,
options: items.map((i) => ({ label: i.label, detail: i.detail, apply: i.insertText })),
};
}],
}),
linter((view) =>
service.diagnostics(view.state.doc.toString()).map((d) => ({
from: d.span.start, to: d.span.end, severity: d.severity, message: d.message,
})),
),
Monaco
Monaco works with line and column positions; convert with the model:
monaco.languages.registerCompletionItemProvider("jsonata", {
triggerCharacters: [".", "[", "$", "=", '"', "'"],
provideCompletionItems(model, position) {
const { range, items } = service.complete(model.getValue(), model.getOffsetAt(position));
const start = model.getPositionAt(range.start);
const end = model.getPositionAt(range.end);
return {
suggestions: items.map((i) => ({
label: i.label,
insertText: i.insertText,
detail: i.detail,
documentation: i.documentation && { value: i.documentation },
kind: monaco.languages.CompletionItemKind.Field, // map i.kind as needed
range: new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column),
})),
};
},
});
// Diagnostics: monaco.editor.setModelMarkers(model, "jlens", ...) with the same conversion.
A schema in several documents
A $ref may lead to another document. jlens never fetches one: the application gives each
document with its URI, as the sources of LanguageService (the
schema guide):
const sources = {
uri: "https://example.com/schemas/order.json", // of the schema, when it has no $id
documents: { "https://example.com/schemas/common.json": common },
};
const service = new LanguageService({ schema: order, sources });
const report = schemaReport(order, sources);
// { unresolved: [{ place: "https://example.com/schemas/order.json#/properties/carrier",
// reference: "carrier.json",
// uri: "https://example.com/schemas/carrier.json",
// document: "https://example.com/schemas/carrier.json" }] }
// {} when every $ref was followed; `unread` lists the keywords not read, as
// [{ place: "#/properties/code", keyword: "type" }] for a type that names no JSON type,
// and `openTuples` the tuples that any item may follow, as [{ place: "#/properties/point" }]
A $ref that is not followed does not fail the service: its place is unknown, and nothing is
completed or warned about under it. schemaReport lists those $refs, each with the
document to add to documents; an application that can fetch them does, and makes the
service again. A keyword the load does not read leaves its place unknown too, and unread
lists it (the schema guide lists the keywords). A tuple
that says nothing of the items after it is read, and openTuples lists it: its items are
checked only at a literal index inside it, which may be less than the schema’s author meant.
The documents serve the schemas of the variables too; uri is that of the
input’s schema alone. Both throw a TypeError for sources that are not in this form.
The type of the result, and the context
Two options of LanguageService say what the expressions are, besides what their schemas
say: resultType, the type their result must have, and contextPath, the path whose items
they are evaluated against, as the body of items.( … ) (the
schema guide). They are those of jlens.json in an editor:
const conditions = new LanguageService({ schema, resultType: "boolean" });
conditions.diagnostics('$contains(customer.name, "VIP")');
// [{ severity: "warning", code: "W0214", span: {start: 10, end: 18},
// message: "The result may be undefined, not a boolean, because of customer" }]
const lines = new LanguageService({ schema, resultType: ["number"], contextPath: "items[]" });
lines.diagnostics("%.customer.login & ': ' & code"); // W0212: a string, never a number
conditions.resultType('$contains(customer.name, "VIP")');
// { types: ["boolean"], undefined: {start: 10, end: 18}, sequence: null, check: "maybe" }
resultType is a type’s name or an array of them, and number accepts an integer. The method
resultType gives what the typing knows of the result: the types it may have (null where they are not
known, as without a schema or with a syntax error), and the spans, in UTF-16 units, of the
operands that may make it undefined or several values. check compares it with the option:
always, never, maybe or unknown, absent when the service expects no type. Options not
in this form throw a TypeError.
What an expression uses of its schema
An application that stores expressions written against a schema that changes keeps, beside each one, what it uses of the schema, and compares it when a new version arrives (the schema guide describes both answers):
const expression = new Expression('$sum(items[type = "book"].price)');
const uses = new LanguageService({ schema }).uses(expression.reads());
// { input: { "$": { types: ["object"] },
// "items": { types: ["array"], required: true },
// "items[]": { types: ["object"] },
// "items[].price": { whole: true, types: ["number"], required: false },
// "items[].type": { whole: true, types: ["string"], enum: ["book", "toy"],
// closed: true, required: true } },
// bindings: {} }
const kept = JSON.stringify(uses);
// Later, with the new version of the schema:
const changes = usesChanges(JSON.parse(kept), new LanguageService({ schema: newSchema }).uses(expression.reads()));
// { input: { changed: { "items[].price": { types: { old: ["number"], new: ["integer", "string"] } } } } }
// {} when nothing the expression uses changed
uses takes the fields the expression reads, so that the
application chooses them: expression.reads(bindings) knows that the JavaScript functions of
the bindings do not read their context, where reads() alone takes the input as read whole by
a function it does not know. usesChanges needs no service and no schema. Both throw a
TypeError for an argument that is not in the form reads() or uses() returns.
The fields of a schema
An editor that offers its own list of attributes, or an application that matches the fields of
two versions of a schema, takes them from fields() rather than walking the schema (the
schema guide says what each holds):
const service = new LanguageService({ schema: {
type: "object",
required: ["status"],
properties: {
status: { type: "string", title: "Status", enum: ["open", "closed"], "x-attribute-id": "A17" },
lines: { type: "array", items: { type: "object", properties: {
sku: { type: "string", "x-jlens-domain": "products" } } } },
internal: { type: "string", "x-jlens-hidden": true },
},
} });
service.fields();
// [ { path: "$", typeSummary: "object", types: ["object"] },
// { path: "lines", typeSummary: "array<object>", types: ["array"], required: false },
// { path: "lines[]", typeSummary: "object", types: ["object"] },
// { path: "lines[].sku", typeSummary: "string", types: ["string"], required: false,
// domain: "products" },
// { path: "status", typeSummary: "string", types: ["string"], required: true, label: "Status",
// enum: ["open", "closed"], closed: true, extensions: { "x-attribute-id": "A17" } } ]
Each path is written as uses writes it, and they come in its order; a hidden field is left
out, with what is under it. extensions holds the field’s own x- keywords as written, which
jlens does not read, such as a key the application gives each field.
Fields renamed by a new version
When a new version of a schema renames fields, rename() rewrites an expression written against
the old one, given a table of paths, each old path to its new one (the schema
guide says what it renames and why it may not be
sure). A table built from the two versions’ fields(), matched by a key of the application’s in
extensions, fits:
const key = (field) => field.extensions?.["x-attribute-id"];
const newPaths = new Map(after.fields().filter(key).map((field) => [key(field), field.path]));
const renames = Object.fromEntries(before.fields()
.filter((field) => newPaths.has(key(field)))
.map((field) => [field.path, newPaths.get(key(field))]));
before.rename("status = 'open' and $sum(lines.(qty * price)) > 100", renames);
// { text: "status = 'open' and $sum(items.(quantity * price)) > 100",
// edits: [ { span: { start: 25, end: 30 }, text: "items" },
// { span: { start: 32, end: 35 }, text: "quantity" } ],
// unsure: [] }
Spans are in UTF-16 code units. unsure lists the places it leaves as written, each with its
span, path and reason (whole, string, mixed or lost). A text that does not compile
throws its error, and a table that is not one of renames a TypeError.
Limits and memory
| Limit | Default | Error |
|---|---|---|
Evaluation depth (maxDepth) | 500 | D1011 |
Evaluation time (timeout, milliseconds) | none | D1012 |
Evaluation steps (maxSteps) | none | U1006 |
Length of a string built (maxStringLength, bytes of UTF-8) | 256 MiB | U1001 |
Items of an array built (maxArrayLength) | 16,777,216 | U1001 |
Size of the result as JSON text (maxResultSize, bytes) | 256 MiB | U1001 |
| Expression nesting | 1,000 levels | U1001 |
| Nesting of arrays and objects in a value that is returned, compared or serialized | 1,000 levels | U1001 |
The size of the result counts a value each time it appears, as the JSON text does, and also
limits the arguments passed to a host function. Wasm evaluations are synchronous, so there is
no cancellation: use timeout or maxSteps.
A timeout reads the clock, so the same evaluation can pass natively and fail in WebAssembly,
which is slower, or pass on one machine and fail on another. maxSteps does not depend on the
machine: each node evaluated is a step, and so is each function a built-in or a host function
calls back, and each 1,024 steps of a regular expression’s backtracking. The same expression,
input and options take the same steps in every browser, in Node.js and natively, and fail with
U1006 once the budget is spent; the error’s value is the limit. The header of an audit
reports the steps an evaluation took (audit.header.steps), to set a budget from. For the same
outcome on every platform, set maxDepth too, since its default differs natively. See
ADR 0018. In a browser, an evaluation can also run in a Web Worker, and
terminating the worker stops it; the web editor does this.
The depth limit is lower than on native targets (50,000). WebAssembly runs on the JavaScript
engine’s stack, which is about 1 MiB in V8, and deep recursion beyond it raises a JavaScript
RangeError. Such an error, like any trap, leaves the module instance unusable. The defaults
keep evaluations inside the engine’s stack, with headroom. Raise maxDepth only if you have
measured what your target engines allow. The jlens errors themselves (JlensError,
TypeError) never affect the instance.
How deep an evaluation fits depends on the shape of the recursion and on V8’s compiler. V8 first runs the module with its baseline compiler (Liftoff), then recompiles the functions an evaluation uses often with its optimizing compiler (TurboFan), whose frames for jlens’s evaluator are about 1.6 times larger. Measured in Node.js 24 once the module is optimized, an audited recursion overflows V8’s stack near these depths (an unaudited one fits 25 to 45% more):
| The recursive function’s body | Overflows near |
|---|---|
[$n, $n]^($f($n - 1)) (order-by) | 660 |
{'a': 1} ~> |$|{'b': $f($n - 1)}| (transform) | 680 |
{'a': $f($n - 1)}, [$n]{'k': $f($n - 1)} (group) | 720 |
[$n][$f($n - 1)] (filter) | 790 |
$f($n - 1) + 1, [$f($n - 1)] | 850 |
$n = 0 ? 0 : 1 + $f($n - 1) | 930 |
The default of 500 leaves room for shapes not measured here, and for engines with smaller stacks. The evaluator chapter has the details.
Expression, Document and LanguageService objects live in WebAssembly memory. The garbage collector
frees them through FinalizationRegistry. Call free(), or use using, to release them
promptly in loops.
TypeScript
The package ships jlens.d.ts. Every argument and result is typed: AuditResult, AuditTree,
AuditNode, Explanation, Diagnostic, Completions, CompletionItem, ValueRequest,
ValueCondition, Hover, SignatureHelp, FunctionInfo, JsonSchema, SchemaOverride, EvaluateOptions,
AuditOptions and JlensError. Results of evaluate are unknown; narrow them as usual.
The web editor example
examples/web-editor is a
complete page with no build step, published with this book as the
web editor:
- a JSONata editor (CodeMirror 6) with completion, diagnostics, hover and signature help, driven by a schema inferred from the input document;
- a panel of schema overrides, passed to
inferSchemawith the input document, so that the structure still follows the document and the overrides add labels, descriptions, hidden fields and domains; the “Free shipping” example has some; - live evaluation, in a Web Worker (
worker.js), so that a slow expression never blocks typing; - the explanation and an audit tree viewer; clicking a node selects its source;
- the inferred schema;
- ready-made examples, including the samples of try.jsonata.org;
- a host function,
$try(host-functions.js), that calls the function it receives, with an example that uses it: the worker registers it on each expression, and the page declares it to the language service; - a stand-in asynchronous source for open domains (
domains.js), which answers after a short delay, as a server would: the “Open domains” example shows it on three fields, and in the “Free shipping” example,customer.login = 'completes the logins of its domaincustomers.
cargo xtask wasm
cargo xtask serve # then open the printed /examples/web-editor/ address
CodeMirror is loaded from esm.sh through an import map, so the page needs network access. The
page imports the package by its name, jlens-wasm, which the same import map resolves.
cargo xtask site builds the published site in target/site, the book with the editor in
editor/, and cargo xtask serve --site serves it.
Testing
cargo xtask wasm-test builds the package, then runs crates/jlens-wasm/tests/suite.mjs twice:
- in Node.js;
- in a headless Chrome, Chromium or Edge (set
JLENS_BROWSERto choose the executable).
--require-browser fails when no browser is found, instead of skipping. --example also
checks that the web editor loads and evaluates its sample, from the repository and as the site
serves it.