@mark1russell7/coeval 0.3.3 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["entryOf","setOwn","makeRootContext"],"sources":["../src/doc.ts","../src/errors.ts","../src/world.ts","../src/ladder.ts","../src/deref.ts","../src/classify.ts","../src/parts.ts","../src/evaluate.ts","../src/stdlib.ts","../src/order.ts","../src/context.ts","../src/static.ts","../src/formula.ts"],"sourcesContent":["/** A JSON value. A document is JSON. */\nexport type Json = null | boolean | number | string | readonly Json[] | { readonly [key: string]: Json };\n\n/** A JSON record. */\nexport type JsonRecord = { readonly [key: string]: Json };\n\n/** One step of a path that is a plain key: a name, or an index of a list. */\nexport type Key = string | number;\n\n/**\n * The type of a document is a reference into the world (the registry of kinds).\n *\n * - A text is a base reference with one key: `\"add\"`.\n * - A list of keys is a base reference with a path: `[\"git\", \"push\"]`.\n * - A document of type `ref` is the same reference, expanded. Its path starts at the root `world`.\n *\n * The kernel resolves a base reference itself. The expanded form is necessary only to attach more to the\n * reference. Thus the chain of types stops at a base reference.\n */\nexport type TypeRef = string | readonly Key[] | { readonly type: \"ref\"; readonly value: readonly Json[] };\n\n/**\n * A typed document: an envelope with a header and a value. The header names the type of the value. The value is\n * not changed by the envelope at any time. Thus any JSON value can have a type: a number, a list, a text or a record.\n */\nexport type Envelope = {\n /** The type: a reference to a kind of the world. */\n readonly type: TypeRef;\n /** The value. */\n readonly value: Json;\n /** The name of a binding. A sequence gives the result of this document to the later steps under this name. */\n readonly name?: string;\n /** The own entries: one evaluator name for each verb. An own entry changes only this document. */\n readonly own?: Readonly<Record<string, string>>;\n};\n\n/** The keys that an envelope can have. */\nexport const ENVELOPE_KEYS = [\"type\", \"value\", \"name\", \"own\"] as const;\n\n/**\n * This function tells if a value is a plain record: an object with the prototype of a plain object, or with no\n * prototype. A list, `null`, a date, a map and an instance of a class are not plain records.\n *\n * @param value - The value to examine.\n * @returns `true` for a plain record.\n */\nexport function isRecord(value: unknown): value is JsonRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * This function reads a field of a record. It reads only the own fields, thus `constructor` is not a field.\n *\n * @param record - The record.\n * @param key - The name of the field.\n * @returns The value of the field, or `undefined` when the record has no such field.\n */\nexport function field(record: JsonRecord, key: string): Json | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\n/**\n * This function tells if a value is a key of a path: a text, or a whole number from 0.\n *\n * @param value - The value to examine.\n * @returns `true` for a key.\n */\nexport function isKey(value: unknown): value is Key {\n return typeof value === \"string\" || (typeof value === \"number\" && Number.isInteger(value) && value >= 0);\n}\n\n/**\n * This function tells if a value is a reference to a type. The reference is a text, a list of keys, or a document\n * of type `ref` whose path starts at the root `world`.\n *\n * @param value - The value to examine.\n * @returns `true` for a reference to a type.\n */\nexport function isTypeRef(value: unknown): value is TypeRef {\n if (typeof value === \"string\") return value !== \"\";\n if (Array.isArray(value)) return value.length > 0 && (value as readonly unknown[]).every(isKey);\n if (!isRecord(value)) return false;\n const path = field(value, \"value\");\n return field(value, \"type\") === \"ref\" && Array.isArray(path) && (path as readonly Json[])[0] === \"world\";\n}\n\n/**\n * This function gives the path of a reference to a type, from the root of the world.\n *\n * @param type - The reference.\n * @returns The keys from the root of the world, or `undefined` for a computed step that has no fixed key.\n */\nexport function typePath(type: TypeRef): readonly Key[] | undefined {\n if (typeof type === \"string\") return [type];\n if (Array.isArray(type)) return type as readonly Key[];\n const steps = (type as { readonly value: readonly Json[] }).value.slice(1);\n return steps.every(isKey) ? (steps as readonly Key[]) : undefined;\n}\n\n/**\n * This function gives the text of a type for a reader: its keys, joined with a dot.\n *\n * @param type - The reference to the type.\n * @returns The text, for example `git.push`.\n */\nexport function typeName(type: TypeRef): string {\n if (typeof type === \"string\") return type;\n return typePath(type)?.join(\".\") ?? \"(computed)\";\n}\n\nfunction headerFits(value: JsonRecord): boolean {\n if (!isTypeRef(field(value, \"type\")) || !Object.hasOwn(value, \"value\")) return false;\n const name = field(value, \"name\");\n if (name !== undefined && typeof name !== \"string\") return false;\n const own = field(value, \"own\");\n return own === undefined || isRecord(own);\n}\n\n/**\n * This function tells if a value has the form of an envelope. That form is a record with a reference to a type\n * and a `value`. It has no other keys than the keys of an envelope. A contract decides where an envelope is\n * expected. This function only checks the form.\n *\n * @param value - The value to examine.\n * @returns `true` when the value has the form of an envelope.\n */\nexport function isEnvelope(value: unknown): value is JsonRecord & Envelope {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n // The keys come first: most values that are not envelopes have another key, thus the check stops early.\n for (const key in value) {\n if (key !== \"type\" && key !== \"value\" && key !== \"name\" && key !== \"own\" && Object.hasOwn(value, key)) return false;\n }\n return isRecord(value) && headerFits(value);\n}\n\n/** A stored document: an envelope, and the keys of its store beside it, for example `_id`. */\nexport interface Stored {\n readonly envelope: Envelope;\n /** The keys of the store, with their values. */\n readonly header: Readonly<Record<string, Json>>;\n}\n\n/**\n * This function reads a stored document: an envelope that also has the keys of a store, for example `{ _id, type,\n * value }`. Only the keys in the list can be beside the keys of the envelope.\n *\n * @param value - The value to examine.\n * @param header - The keys of the store that the document can have.\n * @returns The envelope and the keys of the store, or `undefined` when the value has another form.\n */\nexport function stored(value: unknown, header: readonly string[]): Stored | undefined {\n if (!isRecord(value) || !headerFits(value)) return undefined;\n const keys: Record<string, Json> = {};\n const own: Record<string, Json> = {};\n for (const key in value) {\n if (!Object.hasOwn(value, key)) continue;\n if ((ENVELOPE_KEYS as readonly string[]).includes(key)) own[key] = value[key] as Json;\n else if (header.includes(key)) keys[key] = value[key] as Json;\n else return undefined;\n }\n return { envelope: fromJson(own) as Envelope, header: keys };\n}\n\n/**\n * This function makes an envelope.\n *\n * @param type - The reference to the kind.\n * @param value - The value.\n * @param header - The optional name and own entries.\n * @returns The envelope.\n */\nexport function typed(type: TypeRef, value: Json, header: { readonly name?: string; readonly own?: Record<string, string> } = {}): Envelope {\n return { type, value, ...(header.name === undefined ? {} : { name: header.name }), ...(header.own === undefined ? {} : { own: header.own }) };\n}\n\n/**\n * This function makes a reference document: a path from a root of the context.\n *\n * @param path - The steps. The first step is a root: `self`, `names`, `world`, `event` or `caps`.\n * @returns The document of type `ref`.\n */\nexport function ref(...path: readonly Json[]): Envelope {\n return typed(\"ref\", path);\n}\n\n/**\n * This function gives an envelope as a JSON record, for a store or for a view.\n *\n * @param doc - The envelope.\n * @returns The same envelope as JSON.\n */\nexport function toJson(doc: Envelope): JsonRecord {\n return {\n type: doc.type as Json,\n value: doc.value,\n ...(doc.name === undefined ? {} : { name: doc.name }),\n ...(doc.own === undefined ? {} : { own: doc.own }),\n };\n}\n\n/**\n * This function reads an envelope from JSON. A value without the form of an envelope gives `undefined`.\n *\n * @param value - The JSON value.\n * @returns The envelope, or `undefined`.\n */\nexport function fromJson(value: unknown): Envelope | undefined {\n if (!isEnvelope(value)) return undefined;\n const own = field(value, \"own\");\n const ownEntries: Record<string, string> = {};\n if (isRecord(own)) {\n for (const [verb, name] of Object.entries(own)) if (typeof name === \"string\") ownEntries[verb] = name;\n }\n const name = field(value, \"name\");\n return typed(field(value, \"type\") as TypeRef, field(value, \"value\") ?? null, {\n ...(typeof name === \"string\" ? { name } : {}),\n ...(isRecord(own) ? { own: ownEntries } : {}),\n });\n}\n\n/**\n * This function tells if two JSON values are equal. Equal values have the same texts, numbers and truth values,\n * the same items in the same order, and the same fields. The order of the fields does not matter. It does not use the stack for the\n * depth, thus a deep document cannot overflow it.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @returns `true` when the values are equal.\n */\nexport function docEquals(a: unknown, b: unknown): boolean {\n const stack: [unknown, unknown][] = [[a, b]];\n while (stack.length > 0) {\n const [x, y] = stack.pop() as [unknown, unknown];\n if (Object.is(x, y)) continue;\n if (typeof x !== \"object\" || typeof y !== \"object\" || x === null || y === null) return false;\n if (Array.isArray(x) !== Array.isArray(y)) return false;\n if (Array.isArray(x)) {\n const ys = y as readonly unknown[];\n if (x.length !== ys.length) return false;\n for (let index = 0; index < x.length; index += 1) stack.push([x[index], ys[index]]);\n continue;\n }\n const xr = x as Readonly<Record<string, unknown>>;\n const yr = y as Readonly<Record<string, unknown>>;\n const keys = Object.keys(xr);\n if (keys.length !== Object.keys(yr).length) return false;\n for (const key of keys) {\n if (!Object.hasOwn(yr, key)) return false;\n stack.push([xr[key], yr[key]]);\n }\n }\n return true;\n}\n","import type { Key } from \"./doc.ts\";\n\n/** The codes that the kernel gives. */\nexport type KernelCode =\n | \"#KIND?\"\n | \"#NOEVAL\"\n | \"#PART?\"\n | \"#NAME?\"\n | \"#REF!\"\n | \"#N/A\"\n | \"#CYCLE!\"\n | \"#STEP?\"\n | \"#VALUE!\"\n | \"#NUM!\"\n | \"#ARGS\"\n | \"#CAP!\"\n | \"#CALC!\"\n | \"#DEPTH!\"\n | \"#ABORT\";\n\n/** The code of an error value. A language can add its own codes. Each code starts with `#`. */\nexport type ErrorCode = KernelCode | `#${string}`;\n\n/**\n * An error value: a code and a reason. An evaluation gives an error value, and it does not throw.\n *\n * - `place`: the keys from the root document to the document that failed.\n * - `cause`: the error of the host that caused this error, for example the exception of an effect.\n */\nexport interface EvalError {\n readonly code: ErrorCode;\n readonly reason: string;\n readonly place?: readonly Key[];\n readonly cause?: unknown;\n}\n\n/** The result of an evaluation: a value, or an error value. A value can be any value of the host. */\nexport type Result<V = unknown> = { readonly ok: true; readonly value: V } | { readonly ok: false; readonly error: EvalError };\n\n/** A result with an error value. */\nexport type Failed = { readonly ok: false; readonly error: EvalError };\n\n/**\n * This function makes a result with a value.\n *\n * @param value - The value.\n * @returns The result.\n */\nexport function ok<V>(value: V): Result<V> {\n return { ok: true, value };\n}\n\n/**\n * This function makes a result with an error value.\n *\n * @param code - The code of the error.\n * @param reason - One sentence that tells the cause.\n * @param more - The place and the cause of the error, when they are known.\n * @returns The result.\n */\nexport function fail(code: ErrorCode, reason: string, more: { readonly place?: readonly Key[]; readonly cause?: unknown } = {}): Failed {\n return {\n ok: false,\n error: { code, reason, ...(more.place === undefined ? {} : { place: more.place }), ...(more.cause === undefined ? {} : { cause: more.cause }) },\n };\n}\n\n/**\n * This function gives a failed result its place, when it has none. A result with a value, or an error with a\n * place, stays the same object.\n *\n * @param result - The result.\n * @param place - The keys from the root document to the document that failed.\n * @returns The result with a place.\n */\nexport function placed<V>(result: Result<V>, place: readonly Key[]): Result<V> {\n if (result.ok || result.error.place !== undefined) return result;\n return { ok: false, error: { ...result.error, place } };\n}\n\n/**\n * An exception that carries an error value through code of the host. A closure of a formula throws it when the\n * host calls the closure and the closure fails. The kernel catches it and gives its error value again.\n */\nexport class Failure extends Error {\n readonly error: EvalError;\n\n /**\n * This constructor makes the exception.\n *\n * @param error - The error value that the exception carries.\n */\n constructor(error: EvalError) {\n super(`${error.code} ${error.reason}`);\n this.name = \"Failure\";\n this.error = error;\n }\n}\n\n/**\n * This function tells if an exception is the overflow of the stack of the host.\n *\n * @param error - The exception.\n * @returns `true` for a stack overflow.\n */\nexport function isStackOverflow(error: unknown): boolean {\n return error instanceof RangeError && /call stack/i.test(error.message);\n}\n\n/**\n * This function changes an exception into an error value. A `Failure` gives its error value. A stack overflow\n * gives `#DEPTH!`. Each other exception gives `#CALC!`, with the exception as the cause.\n *\n * @param error - The exception.\n * @param who - A short text that names the code that threw, for example `the evaluator math.add`.\n * @returns The failed result.\n */\nexport function thrown(error: unknown, who: string): Failed {\n if (error instanceof Failure) return { ok: false, error: error.error };\n if (isStackOverflow(error)) return fail(\"#DEPTH!\", `The nesting of ${who} is too deep for the stack of the host.`, { cause: error });\n return fail(\"#CALC!\", `${upper(who)} threw: ${describe(error)}`, { cause: error });\n}\n\nfunction upper(text: string): string {\n return text.length === 0 ? text : `${text[0]?.toUpperCase() ?? \"\"}${text.slice(1)}`;\n}\n\n/**\n * This function gives a short text for an exception or any value. It does not throw.\n *\n * @param value - The value.\n * @returns The text.\n */\nexport function describe(value: unknown): string {\n try {\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n return String(value);\n } catch {\n return \"(a value without a text)\";\n }\n}\n","import { type Envelope, type Json, type Key, type TypeRef, field, isRecord, typePath } from \"./doc.ts\";\n\n/** The two sides of evaluation. `derive` is pure. `run` causes effects in order. */\nexport type Side = \"derive\" | \"run\";\n\n/**\n * Where the parts of a value are: the shape of the value. A part is a typed document that the evaluator gets\n * sealed. `of` is the type of a bare part: a part without an envelope gets this type from its position.\n *\n * - `none`: the value is data. It has no parts.\n * - `term`: the value itself is one part.\n * - `list`: the value is a list. Each item has the shape `item` (the default is a part).\n * - `map`: the value is a record. Each field has the shape `item` (the default is a part).\n * - `record`: the value is a record. Each named field has its shape. A list of names makes each named field a\n * part. The other fields have the shape `rest` (the default is data). `required` names the fields that must be.\n * - `deep`: each envelope at any depth of the value is a part, and the rest is data.\n */\nexport type Shape =\n | { readonly shape: \"none\" }\n | { readonly shape: \"term\"; readonly of?: string }\n | { readonly shape: \"list\"; readonly of?: string; readonly item?: Shape }\n | { readonly shape: \"map\"; readonly of?: string; readonly item?: Shape }\n | {\n readonly shape: \"record\";\n readonly fields: readonly string[] | Readonly<Record<string, Shape>>;\n readonly of?: string;\n readonly required?: readonly string[];\n readonly rest?: Shape;\n }\n | { readonly shape: \"deep\"; readonly of?: string };\n\n/** The former name of `Shape`. */\nexport type PartsSpec = Shape;\n\n/**\n * Where the names of a scope rule come from.\n *\n * - `fixed`: the names in the list.\n * - `keysAt`: the keys of the record at this path of the value, for example the bindings of a `let`.\n * - `listAt`: the texts of the list at this path of the value, for example the parameters of a `fn`.\n * - `textAt`: the text at this path of the value, or `otherwise` when the value has no text there.\n * - `headers`: the binding name (`name`) of each part that the rule covers.\n */\nexport type NamesSource =\n | { readonly fixed: readonly string[] }\n | { readonly keysAt: readonly Key[] }\n | { readonly listAt: readonly Key[] }\n | { readonly textAt: readonly Key[]; readonly otherwise?: string }\n | { readonly headers: true };\n\n/**\n * A scope rule of a kind: names that the kind binds, and the parts that see them. The static kit reads the rules,\n * and the evaluator of the kind binds the same names when it evaluates the parts.\n */\nexport interface ScopeRule {\n readonly names: NamesSource;\n /** The parts that see the names, as patterns of their paths in the value. The key `\"*\"` matches each key. */\n readonly in: readonly (readonly Key[])[];\n /** `true`: a part sees only the names of the parts before it, as in a sequence. */\n readonly sequential?: boolean;\n}\n\n/** A kind gives the name of an evaluator for each verb, and the contract of its value. */\nexport interface Kind {\n readonly verbs: Readonly<Record<string, string>>;\n /** Where the parts of the value are. The default is `none`. */\n readonly parts?: Shape;\n /** The names that the kind binds for its parts. */\n readonly scope?: readonly ScopeRule[];\n /** The side of the kind. A kind of the run side causes effects. The default is `derive`. */\n readonly side?: Side;\n /**\n * The effects that a document of this kind can cause. It is a list of the kinds of the effects. The text\n * `\"type\"` means that the kind of the effect is the type of the document itself, as for a call.\n */\n readonly effects?: \"type\" | readonly string[];\n /** One sentence that tells what the kind is. */\n readonly summary?: string;\n}\n\n/** A namespace: a group of entries under one key of the world. `fallback` is the kind of each other key in it. */\nexport interface Namespace {\n readonly kinds: Readonly<Record<string, WorldEntry>>;\n readonly fallback?: Kind;\n}\n\n/** An alias: a reference to another entry of the world. The lookup follows it (collapse). */\nexport type Alias = { readonly type: \"ref\"; readonly value: readonly Json[] };\n\n/** One entry of the world: a kind, a namespace, or an alias. */\nexport type WorldEntry = Kind | Namespace | Alias;\n\n/**\n * A world holds the kinds and the defaults that answer the questions. `fallback` is the kind of each first key that\n * the world does not have. A world with a fallback is open: each path that starts with an unknown key names a kind.\n */\nexport interface World {\n readonly kinds: Readonly<Record<string, WorldEntry>>;\n readonly defaults: Readonly<Record<string, string>>;\n readonly fallback?: Kind;\n}\n\n/** The result of a lookup of a type in the world. */\nexport type Lookup =\n | { readonly ok: true; readonly kind: Kind; readonly path: readonly Key[]; readonly aliases: number }\n | { readonly ok: false; readonly reason: \"unknown\" | \"cycle\" | \"not-a-kind\" | \"computed\"; readonly path: readonly Key[] };\n\n/**\n * This function tells if an entry of the world is a kind.\n *\n * @param entry - The entry.\n * @returns `true` for a kind.\n */\nexport function isKind(entry: WorldEntry | undefined): entry is Kind {\n return entry !== undefined && Object.hasOwn(entry, \"verbs\");\n}\n\n/**\n * This function tells if an entry of the world is an alias.\n *\n * @param entry - The entry.\n * @returns `true` for an alias.\n */\nexport function isAlias(entry: WorldEntry | undefined): entry is Alias {\n return entry !== undefined && (entry as { type?: unknown }).type === \"ref\" && Array.isArray((entry as { value?: unknown }).value);\n}\n\n/**\n * This function tells if an entry of the world is a namespace.\n *\n * @param entry - The entry.\n * @returns `true` for a namespace.\n */\nexport function isNamespace(entry: WorldEntry | undefined): entry is Namespace {\n return entry !== undefined && !isKind(entry) && !isAlias(entry) && Object.hasOwn(entry, \"kinds\");\n}\n\nfunction entryAt(entries: Readonly<Record<string, WorldEntry>>, key: Key): WorldEntry | undefined {\n const name = String(key);\n return Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * This function finds the kind that a type names. It walks the path from the root of the world, one key at a\n * time. An alias on the way is followed until a kind answers (collapse). A cycle of aliases stops the lookup. In a\n * namespace with a fallback, a key that the namespace does not have gets the fallback kind. In an open world, a first\n * key that the world does not have gets the fallback kind of the world.\n *\n * @param world - The world.\n * @param type - The reference to the type.\n * @returns The kind and the path of the kind after each alias, or the reason of a failure.\n */\nexport function lookupKind(world: World, type: TypeRef): Lookup {\n const start = typePath(type);\n if (start === undefined) return { ok: false, reason: \"computed\", path: [] };\n let path: readonly Key[] = start;\n let aliases = 0;\n for (;;) {\n let entries = world.kinds;\n let fallback: Kind | undefined = world.fallback;\n let entry: WorldEntry | undefined;\n let followed = false;\n for (let index = 0; index < path.length; index += 1) {\n const key = path[index] as Key;\n entry = entryAt(entries, key);\n if (entry === undefined) {\n if (fallback !== undefined) return { ok: true, kind: fallback, path, aliases };\n return { ok: false, reason: \"unknown\", path };\n }\n if (isAlias(entry)) {\n aliases += 1;\n if (aliases > 32) return { ok: false, reason: \"cycle\", path };\n const target = entry.value.slice(1);\n if (entry.value[0] !== \"world\" || !target.every((item) => typeof item === \"string\" || typeof item === \"number\")) {\n return { ok: false, reason: \"not-a-kind\", path };\n }\n path = [...(target as readonly Key[]), ...path.slice(index + 1)];\n followed = true;\n break;\n }\n if (index < path.length - 1) {\n if (!isNamespace(entry)) return { ok: false, reason: \"not-a-kind\", path };\n entries = entry.kinds;\n fallback = entry.fallback;\n }\n }\n if (followed) continue;\n if (!isKind(entry)) return { ok: false, reason: \"not-a-kind\", path };\n return { ok: true, kind: entry, path, aliases };\n }\n}\n\n/**\n * This function gives the entries of a world as a JSON record, so that a reference can walk it. A kind is a\n * record with its verbs, an alias is a reference document, and a namespace is a record of its entries.\n *\n * @param entries - The entries.\n * @returns The JSON form.\n */\nexport function entriesAsJson(entries: Readonly<Record<string, WorldEntry>>): Json {\n const out: Record<string, Json> = {};\n for (const [key, entry] of Object.entries(entries)) {\n if (isAlias(entry)) out[key] = { type: \"ref\", value: entry.value };\n else if (isKind(entry)) out[key] = JSON.parse(JSON.stringify(entry)) as Json;\n else out[key] = entriesAsJson((entry as Namespace).kinds);\n }\n return out;\n}\n\nfunction describeShape(shape: Shape | undefined): Json {\n if (shape === undefined || shape.shape === \"none\") return \"none\";\n if (shape.shape === \"term\") return `a part${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n if (shape.shape === \"deep\") return \"each document in the value\";\n if (shape.shape === \"list\") return `a list${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n if (shape.shape === \"map\") return `a record of parts${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n const names = Array.isArray(shape.fields) ? shape.fields : Object.keys(shape.fields);\n return `the fields ${names.join(\", \")}`;\n}\n\n/**\n * This function makes the document of a kind, so that a view can draw it as each other document.\n *\n * @param name - The name of the kind.\n * @param kind - The kind.\n * @returns The document of type `kind`.\n */\nexport function kindDocument(name: string, kind: Kind): Envelope {\n return {\n type: \"kind\",\n value: { name, verbs: { ...kind.verbs }, parts: describeShape(kind.parts), side: kind.side ?? \"derive\", summary: kind.summary ?? \"\" },\n };\n}\n\n/**\n * This function tells if a JSON value is the record of a kind.\n *\n * @param value - The value.\n * @returns `true` when the value has verbs.\n */\nexport function looksLikeKind(value: unknown): boolean {\n return isRecord(value) && isRecord(field(value, \"verbs\"));\n}\n","import { type TypeRef, typeName } from \"./doc.ts\";\nimport { type Kind, type World, lookupKind } from \"./world.ts\";\n\nexport type { Kind, Namespace, PartsSpec, Side, World, WorldEntry } from \"./world.ts\";\n\n/** The rungs of the ladder, in the order that a question visits them. */\nexport const RUNGS = [\"own\", \"kind\", \"default\"] as const;\n\n/** One rung of the ladder. */\nexport type Rung = (typeof RUNGS)[number];\n\n/** The place where the ladder found the type. */\nexport type KindSource = \"document\" | \"container\";\n\n/**\n * The outcome of one rung.\n *\n * - `answers`: the rung gives an evaluator.\n * - `no-entry`: the rung has nothing for this verb, thus the question goes to the next rung.\n * - `skipped`: the rung does not apply, because no type is known.\n * - `unknown-kind`: the type is not a kind of the world. The question stops.\n */\nexport type Outcome = \"answers\" | \"no-entry\" | \"skipped\" | \"unknown-kind\";\n\n/** The record of one rung that a question visited. */\nexport interface Step {\n readonly rung: Rung;\n readonly outcome: Outcome;\n /** The evaluator, when the outcome is `answers`. */\n readonly evaluator?: string;\n /** The text of the type, at the kind rung. */\n readonly kind?: string;\n /** The place of the type, at the kind rung. */\n readonly source?: KindSource;\n}\n\n/** The answer to a question. It keeps the record of each rung that the question visited. */\nexport interface Answer {\n readonly verb: string;\n /** The evaluator that answers. A question that stops with an error has no evaluator. */\n readonly evaluator?: string;\n /** The rung that answered. */\n readonly rung?: Rung;\n /** The reason when no rung answers. */\n readonly error?: \"unknown-kind\" | \"no-answer\";\n readonly steps: readonly Step[];\n}\n\n/**\n * The header that the ladder reads: the type and the own entries. An envelope is a header. A bare value has an\n * empty header, and its position can declare its type.\n */\nexport interface Header {\n readonly type?: TypeRef;\n readonly own?: Readonly<Record<string, string>>;\n}\n\n/** The options of a question. */\nexport interface AskOptions {\n /** The type that the position of a bare value declares. The type of an envelope wins. */\n readonly declaredType?: string;\n}\n\nfunction entryOf(verbs: Readonly<Record<string, string>> | undefined, verb: string): string | undefined {\n return verbs !== undefined && Object.hasOwn(verbs, verb) ? verbs[verb] : undefined;\n}\n\n/**\n * This function finds the kind that a type names, and follows each alias. It gives `undefined` for an unknown\n * type.\n *\n * @param world - The world.\n * @param type - The reference to the type.\n * @returns The kind, or `undefined`.\n */\nexport function kindOf(world: World, type: TypeRef): Kind | undefined {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : undefined;\n}\n\n/**\n * This function finds a kind by a text type. It is the same as `kindOf` for a one-key reference.\n *\n * @param world - The world.\n * @param name - The text of the type.\n * @returns The kind, or `undefined`.\n */\nexport function kindNamed(world: World, name: TypeRef): Kind | undefined {\n return kindOf(world, name);\n}\n\n/**\n * This function asks a document a question, and gives the evaluator that answers it.\n *\n * The question visits the rungs in order: the own entry of the envelope, then its kind, then the default of the\n * world. The type comes from the envelope, or else from the type that the position declares. The type is a\n * reference into the world. The ladder does not guess a type from the shape of a value.\n *\n * @param world - The kinds and the defaults.\n * @param doc - The header of the document: an envelope, or `{}` for a bare value.\n * @param verb - The verb of the question, for example `eval` or `view`.\n * @param options - The type that the position declares.\n * @returns The answer, with the record of each rung that the question visited.\n */\nexport function ask(world: World, doc: Header, verb: string, options: AskOptions = {}): Answer {\n const steps: Step[] = [];\n\n const own = entryOf(doc.own, verb);\n if (own !== undefined) {\n steps.push({ rung: \"own\", outcome: \"answers\", evaluator: own });\n return { verb, evaluator: own, rung: \"own\", steps };\n }\n steps.push({ rung: \"own\", outcome: \"no-entry\" });\n\n const type: TypeRef | undefined = doc.type ?? options.declaredType;\n if (type === undefined) {\n steps.push({ rung: \"kind\", outcome: \"skipped\" });\n } else {\n const source: KindSource = doc.type === undefined ? \"container\" : \"document\";\n const name = typeName(type);\n const kind = kindOf(world, type);\n if (kind === undefined) {\n steps.push({ rung: \"kind\", outcome: \"unknown-kind\", kind: name, source });\n return { verb, error: \"unknown-kind\", steps };\n }\n const entry = entryOf(kind.verbs, verb);\n if (entry !== undefined) {\n steps.push({ rung: \"kind\", outcome: \"answers\", evaluator: entry, kind: name, source });\n return { verb, evaluator: entry, rung: \"kind\", steps };\n }\n steps.push({ rung: \"kind\", outcome: \"no-entry\", kind: name, source });\n }\n\n const fallback = entryOf(world.defaults, verb);\n if (fallback !== undefined) {\n steps.push({ rung: \"default\", outcome: \"answers\", evaluator: fallback });\n return { verb, evaluator: fallback, rung: \"default\", steps };\n }\n steps.push({ rung: \"default\", outcome: \"no-entry\" });\n return { verb, error: \"no-answer\", steps };\n}\n","import { type Envelope, type Json, type JsonRecord, type Key, type TypeRef, field, isEnvelope, isKey, isRecord, typePath } from \"./doc.ts\";\nimport { type World, entriesAsJson, lookupKind } from \"./world.ts\";\n\n/**\n * The brand of a host thing: an object of the host that answers the steps of a path itself. The brand is a\n * global symbol, thus two copies of the kernel in one program know the things of each other.\n */\nexport const THING: unique symbol = Symbol.for(\"coeval.thing\") as never;\n\n/**\n * A host thing: an object that answers the steps of a path itself, for example a node of a live tree. It is the\n * own entry of the ladder for the verb `deref`.\n */\nexport interface HostThing {\n readonly [THING]: true;\n /** A short text for a reader, for example `node card`. */\n readonly label: string;\n /**\n * This function answers one step.\n *\n * @param key - The key of the step.\n * @returns What the step reaches, or `undefined` when it reaches nothing.\n */\n deref(key: Key): Thing | undefined;\n /**\n * This function gives the thing as a value, when a reference ends on it.\n *\n * @returns The value.\n */\n toJson(): unknown;\n /**\n * This optional function answers all the steps of a path that are keys, in one call. A store uses it to read a\n * path without one call for each step.\n *\n * @param keys - The keys.\n * @returns What the keys reach, or `undefined` when they reach nothing.\n */\n resolve?(keys: readonly Key[]): { readonly thing: Thing } | undefined;\n}\n\n/** Something that a path can reach: any value of the host, or a host thing. */\nexport type Thing = unknown;\n\n/**\n * This function tells if a thing is a host thing.\n *\n * @param thing - The thing.\n * @returns `true` for a host thing.\n */\nexport function isHostThing(thing: unknown): thing is HostThing {\n return typeof thing === \"object\" && thing !== null && (thing as Partial<HostThing>)[THING] === true;\n}\n\n/** The roots of a context. Each path starts with one of them. */\nexport const ROOTS = [\"self\", \"names\", \"world\", \"event\", \"caps\"] as const;\n\n/** One root of a context. */\nexport type Root = (typeof ROOTS)[number];\n\n/**\n * A capability: the name of a kind of effect, or its keys. A capability permits its kind and each kind under it.\n * Keys are necessary when a key has a dot in it.\n */\nexport type Cap = string | readonly Key[];\n\n/**\n * The context of a term: a record with five roots. A reference reaches outside its term only through them.\n *\n * - `self`: the node that the term is part of.\n * - `names`: the values that the evaluators around the term bound.\n * - `world`: the registry of kinds.\n * - `event`: the event that started a run.\n * - `caps`: the effects that the term can cause.\n */\nexport interface Context {\n readonly self: Thing;\n readonly names: Readonly<Record<string, unknown>>;\n readonly world: Thing;\n readonly event: Thing;\n readonly caps: readonly Cap[];\n}\n\n/** The code of a `deref` evaluator: it answers one step of a path on a document of its kind. */\nexport type DerefCode = (doc: Envelope, key: Key) => Thing | undefined;\n\n/** The result of a step document: what it reached, or the reason of a failure. */\nexport type WalkResult = { readonly ok: true; readonly thing: Thing } | { readonly ok: false; readonly reason: string };\n\n/** The input of a walker: the code of a step document, for example `nearest`. */\nexport interface WalkInput {\n /** The value of the step document. */\n readonly data: Json;\n /** The thing that the path reached before this step. */\n readonly here: Thing;\n readonly context: Context;\n /**\n * This function answers one step on a thing, through the ladder.\n *\n * @param thing - The thing.\n * @param key - The key.\n * @returns What the step reaches, or `undefined`.\n */\n deref(thing: Thing, key: Key): Thing | undefined;\n}\n\n/** A walker: the code of the verb `step` of a kind of step documents. */\nexport type Walker = (input: WalkInput) => WalkResult;\n\n/**\n * What a resolution needs: the world, and the code of the `deref` evaluators and of the walkers.\n *\n * - `plain`: `true` when the values are data. Then a step does not ask the kind of an envelope, and a reference\n * that a step reaches stays a value (no collapse).\n * - `roots`: the roots that a path can start at. The default is each root.\n * - `adopt`: the thing of each value that a path reaches. A host gives its own values a host thing with this\n * function, for example a value whose fields read through signals. A host thing is not followed as a reference.\n */\nexport interface Navigator {\n readonly world: World;\n readonly derefs?: Readonly<Record<string, DerefCode>>;\n readonly walkers?: Readonly<Record<string, Walker>>;\n readonly plain?: boolean;\n readonly roots?: readonly Root[];\n readonly adopt?: (value: unknown) => Thing;\n}\n\n/** The way that one hop of a path was answered. */\nexport type HopBy = \"root\" | \"own\" | \"kind\" | \"default\" | \"step\" | \"collapse\";\n\n/** One hop of a path: the step, what it reached, and who answered it. */\nexport interface Hop {\n readonly step: Json;\n readonly thing: Thing;\n readonly by: HopBy;\n}\n\n/** The codes of a failed resolution. */\nexport type ResolveCode = \"#REF!\" | \"#NAME?\" | \"#N/A\" | \"#CYCLE!\" | \"#STEP?\";\n\n/** The result of a resolution: what the path reached, with each hop, or an error with the hops before it. */\nexport type Resolution =\n | { readonly ok: true; readonly thing: Thing; readonly hops: readonly Hop[] }\n | { readonly ok: false; readonly code: ResolveCode; readonly reason: string; readonly hops: readonly Hop[] };\n\n/** The options of a resolution. */\nexport interface ResolveOptions {\n /** `false`: do not record the hops. The default is `true`. */\n readonly hops?: boolean;\n}\n\nfunction entryOf(verbs: Readonly<Record<string, string>> | undefined, verb: string): string | undefined {\n return verbs !== undefined && Object.hasOwn(verbs, verb) ? verbs[verb] : undefined;\n}\n\n/** The own fields of a value: the items and the length of a list, and the own properties of an object. */\nfunction plainStep(thing: unknown, key: Key): { readonly found: true; readonly value: unknown } | undefined {\n if (Array.isArray(thing)) {\n if (key === \"length\") return { found: true, value: thing.length };\n const index = typeof key === \"number\" ? key : /^\\d+$/.test(key) ? Number(key) : -1;\n return index >= 0 && index < thing.length ? { found: true, value: (thing as readonly unknown[])[index] } : undefined;\n }\n if (typeof thing === \"object\" && thing !== null) {\n const name = String(key);\n return Object.hasOwn(thing, name) ? { found: true, value: (thing as Readonly<Record<string, unknown>>)[name] } : undefined;\n }\n return undefined;\n}\n\n/**\n * This function answers one step of a path on a thing, through the ladder of the verb `deref`. A host thing\n * answers for itself (own). A document asks its own entry, then its kind. The default goes into the value: an own\n * field of an object, or an item of a list.\n *\n * @param nav - The world and the code of the evaluators.\n * @param thing - The thing that the path reached.\n * @param key - The key of the step.\n * @returns What the step reaches and the rung that answered, or `undefined` when it reaches nothing.\n */\nexport function derefStep(nav: Navigator, thing: Thing, key: Key): { readonly thing: Thing; readonly by: HopBy } | undefined {\n if (isHostThing(thing)) {\n const reached = thing.deref(key);\n return reached === undefined ? undefined : { thing: reached, by: \"own\" };\n }\n if (nav.plain !== true && isEnvelope(thing)) {\n const envelope = thing as JsonRecord & Envelope;\n const ownEntries = field(envelope, \"own\");\n const own = isRecord(ownEntries) ? entryOf(ownEntries as Readonly<Record<string, string>>, \"deref\") : undefined;\n const ownCode = own === undefined ? undefined : nav.derefs?.[own];\n if (ownCode !== undefined) {\n const reached = ownCode(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: \"own\" };\n }\n const found = lookupKind(nav.world, envelope.type);\n const name = found.ok ? entryOf(found.kind.verbs, \"deref\") : undefined;\n const code = name === undefined ? undefined : nav.derefs?.[name];\n if (code !== undefined) {\n const reached = code(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: \"kind\" };\n }\n const reached = plainStep(envelope.value, key);\n return reached === undefined ? undefined : { thing: reached.value, by: \"default\" };\n }\n const reached = plainStep(thing, key);\n return reached === undefined ? undefined : { thing: reached.value, by: \"default\" };\n}\n\n/**\n * This function tells if a thing is a reference document: an envelope of the type `ref` with a list for its path.\n *\n * @param thing - The thing.\n * @returns `true` for a reference document.\n */\nexport function isRef(thing: unknown): thing is Envelope & { readonly value: readonly Json[] } {\n if (!isEnvelope(thing) || !Array.isArray(thing.value)) return false;\n const path = typePath(thing.type as TypeRef);\n return path !== undefined && path.length === 1 && path[0] === \"ref\";\n}\n\nconst worlds = new WeakMap<World, Json>();\n\n/**\n * This function makes the thing of the root `world`: the entries of the world as JSON. An alias is a reference\n * document in it, thus a walk through the world follows each alias (collapse). The thing of a world is made one\n * time.\n *\n * @param world - The world.\n * @returns The thing.\n */\nexport function worldThing(world: World): Json {\n let thing = worlds.get(world);\n if (thing === undefined) {\n thing = entriesAsJson(world.kinds);\n worlds.set(world, thing);\n }\n return thing;\n}\n\n/**\n * This function makes a context. The world comes from the navigator when the call gives none.\n *\n * @param parts - The roots to set.\n * @returns The context.\n */\nexport function context(parts: Partial<Context> = {}): Context {\n return {\n self: parts.self ?? null,\n names: parts.names ?? {},\n world: parts.world ?? null,\n event: parts.event ?? null,\n caps: parts.caps ?? [],\n };\n}\n\nconst MAX_COLLAPSE = 64;\nconst NO_HOPS: readonly Hop[] = Object.freeze([]);\n\n/** A value that can be a reference document: a record with the type `ref`. The full check comes after. */\nfunction mayBeRef(thing: unknown): boolean {\n return typeof thing === \"object\" && thing !== null && (thing as { readonly type?: unknown }).type === \"ref\";\n}\n\n/** This function tells if each step of a path from an index is a key. */\nfunction keysFrom(path: readonly unknown[], start: number): boolean {\n for (let index = start; index < path.length; index += 1) if (!isKey(path[index])) return false;\n return true;\n}\n\n/**\n * This function resolves the common path without a record of hops: a root, then keys. Plain values answer the\n * keys, or a host thing answers all of them in one call. It gives `undefined` when the path needs the full\n * algorithm. Examples are a host thing without `resolve`, an envelope, a reference to follow, a step document and a\n * failure of a step (for its exact reason).\n */\nfunction resolveQuick(nav: Navigator, ctx: Context, path: readonly unknown[]): Resolution | undefined {\n const root = path[0];\n if (root !== \"names\" && root !== \"self\" && root !== \"event\" && root !== \"world\") return undefined;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return undefined;\n if (nav.adopt !== undefined) return undefined;\n let here: unknown = ctx[root];\n const plain = nav.plain === true;\n for (let index = 1; index < path.length; index += 1) {\n if (typeof here !== \"object\" || here === null) return undefined;\n if (!plain && mayBeRef(here)) return undefined;\n if ((here as Partial<HostThing>)[THING] === true) {\n const thing = here as HostThing;\n if (thing.resolve === undefined || !keysFrom(path, index)) return undefined;\n const keys = path.slice(index) as readonly Key[];\n const reached = thing.resolve(keys);\n if (reached === undefined) return { ok: false, code: \"#N/A\", reason: `The path ${keys.join(\".\")} reaches nothing.`, hops: NO_HOPS };\n if (!plain && mayBeRef(reached.thing)) return undefined;\n return { ok: true, thing: reached.thing, hops: NO_HOPS };\n }\n const step = path[index];\n if (Array.isArray(here)) {\n if (typeof step !== \"number\" || !Number.isInteger(step) || step < 0 || step >= here.length) return undefined;\n here = (here as readonly unknown[])[step];\n continue;\n }\n if (typeof step !== \"string\" || !Object.hasOwn(here, step)) return undefined;\n if (!plain && isEnvelope(here)) return undefined;\n here = (here as Readonly<Record<string, unknown>>)[step];\n }\n if (!plain && mayBeRef(here)) return undefined;\n return { ok: true, thing: here, hops: NO_HOPS };\n}\n\n/**\n * This function resolves a path from a context, and records each hop.\n *\n * The first step is a root of the context. Each later step is a key or a step document. A key goes up the ladder\n * of the verb `deref` on the thing that the path reached. A step document is evaluated by the walker of its kind,\n * with the thing that the path reached. After each hop, a reference document is followed until the path reaches\n * something else (collapse), except in a plain navigation.\n *\n * The codes of a failure:\n *\n * - `#REF!`: the path has no root, or a root that is not open here.\n * - `#NAME?`: the root `names` has no such name.\n * - `#N/A`: a step reaches nothing.\n * - `#STEP?`: a step is not a key and not a step document.\n * - `#CYCLE!`: the references form a cycle.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The steps.\n * @param options - `hops: false` does not record the hops.\n * @returns What the path reached and each hop, or an error.\n */\nexport function resolve(nav: Navigator, ctx: Context, path: readonly unknown[], options: ResolveOptions = {}): Resolution {\n if (options.hops === false) {\n const quick = resolveQuick(nav, ctx, path);\n if (quick !== undefined) return quick;\n }\n const hops: Hop[] | undefined = options.hops === false ? undefined : [];\n const done = hops ?? NO_HOPS;\n const failed = (code: ResolveCode, reason: string): Resolution => ({ ok: false, code, reason, hops: done });\n let collapses = 0;\n const adopt = nav.adopt ?? ((value: unknown): Thing => value);\n\n const collapse = (thing: Thing): Resolution => {\n let here = thing;\n if (nav.plain === true) return { ok: true, thing: here, hops: done };\n while (isRef(here)) {\n collapses += 1;\n if (collapses > MAX_COLLAPSE) return failed(\"#CYCLE!\", \"The references form a cycle.\");\n const inner = walk(here.value);\n if (!inner.ok) return inner;\n here = adopt(inner.thing);\n hops?.push({ step: \"collapse\", thing: here, by: \"collapse\" });\n }\n return { ok: true, thing: here, hops: done };\n };\n\n const walk = (steps: readonly unknown[]): Resolution => {\n const root = steps[0];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) {\n return failed(\"#REF!\", `A path starts with a root: ${ROOTS.join(\", \")}.`);\n }\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) {\n return failed(\"#REF!\", `The root ${root} is not open here. The open roots are ${nav.roots.join(\", \")}.`);\n }\n let here: Thing = adopt(ctx[root as Root]);\n hops?.push({ step: root, thing: here, by: \"root\" });\n const first = collapse(here);\n if (!first.ok) return first;\n here = first.thing;\n for (let index = 1; index < steps.length; index += 1) {\n const step = steps[index];\n if (isHostThing(here) && here.resolve !== undefined && steps.slice(index).every(isKey)) {\n const keys = steps.slice(index) as readonly Key[];\n const reached = here.resolve(keys);\n if (reached === undefined) return failed(\"#N/A\", `The path ${keys.join(\".\")} reaches nothing.`);\n const thing = adopt(reached.thing);\n hops?.push({ step: keys as readonly Json[], thing, by: \"own\" });\n return collapse(thing);\n }\n if (isKey(step)) {\n const reached = derefStep(nav, here, step);\n if (reached === undefined) {\n if (root === \"names\" && index === 1) return failed(\"#NAME?\", `The context has no name ${String(step)}.`);\n return failed(\"#N/A\", `The step ${String(step)} reaches nothing.`);\n }\n here = adopt(reached.thing);\n hops?.push({ step, thing: here, by: reached.by });\n } else {\n const envelope = isEnvelope(step) ? step : undefined;\n const found = envelope === undefined ? undefined : lookupKind(nav.world, envelope.type);\n const name = found?.ok === true ? entryOf(found.kind.verbs, \"step\") : undefined;\n const walker = name === undefined ? undefined : nav.walkers?.[name];\n if (envelope === undefined || walker === undefined) {\n return failed(\"#STEP?\", \"A step is a key, or a document of a kind with the verb step.\");\n }\n const result = walker({\n data: envelope.value,\n here,\n context: ctx,\n deref: (thing, key) => {\n const reached = derefStep(nav, thing, key);\n return reached === undefined ? undefined : adopt(reached.thing);\n },\n });\n if (!result.ok) return failed(\"#N/A\", result.reason);\n here = adopt(result.thing);\n hops?.push({ step: envelope as Json, thing: here, by: \"step\" });\n }\n const next = collapse(here);\n if (!next.ok) return next;\n here = next.thing;\n }\n return { ok: true, thing: here, hops: done };\n };\n\n if (path.length === 0) return failed(\"#REF!\", \"A path has at least one step: its root.\");\n return walk(path);\n}\n\n/**\n * This function gives the value of a thing: the value that a host thing gives, or else the thing itself.\n *\n * @param thing - The thing.\n * @returns The value.\n */\nexport function valueOfThing(thing: Thing): unknown {\n return isHostThing(thing) ? thing.toJson() : thing;\n}\n","import { type Envelope, type Json, field, isRecord, typed } from \"./doc.ts\";\n\n/** A shape proposes a kind for each document that has all of its fields. */\nexport interface Shape {\n readonly name: string;\n readonly fields: readonly string[];\n readonly kind: string;\n}\n\n/** The result of a classification. */\nexport interface Classification {\n /** The kind of the one most specific shape. */\n readonly kind?: string;\n /** The names of the most specific shapes. */\n readonly candidates: readonly string[];\n /** `no-match`: no shape applies. `ambiguous`: two or more shapes match equally well. */\n readonly error?: \"no-match\" | \"ambiguous\";\n}\n\nfunction isStrictSuperset(larger: readonly string[], smaller: readonly string[]): boolean {\n return larger.length > smaller.length && smaller.every((name) => larger.includes(name));\n}\n\n/**\n * This function proposes a kind for a value without a type, from the fields that the value has.\n * A shape applies when the value has each field of the shape. The most specific shapes are the ones that\n * no other applicable shape contains. A host uses a classifier when data comes in, and then tags the data.\n * The ladder does not call a classifier.\n *\n * @param shapes - The shapes to examine.\n * @param value - The value without a type.\n * @returns The proposed kind, or an error with the candidates.\n */\nexport function classify(shapes: readonly Shape[], value: Json): Classification {\n const applicable = isRecord(value)\n ? shapes.filter((shape) => shape.fields.every((name) => field(value, name) !== undefined))\n : [];\n const best = applicable.filter((shape) => !applicable.some((other) => isStrictSuperset(other.fields, shape.fields)));\n const candidates = best.map((shape) => shape.name);\n const only = best.length === 1 ? best[0] : undefined;\n if (only !== undefined) return { kind: only.kind, candidates };\n return { candidates, error: best.length === 0 ? \"no-match\" : \"ambiguous\" };\n}\n\n/**\n * This function puts a value in an envelope with a type. The value does not change.\n *\n * @param value - The value.\n * @param kind - The name of the kind.\n * @returns The envelope.\n */\nexport function tag(value: Json, kind: string): Envelope {\n return typed(kind, value);\n}\n","import { type Json, type Key, isEnvelope, isRecord } from \"./doc.ts\";\nimport type { Shape } from \"./world.ts\";\n\n/** One part of a value: its place in the value, the JSON of the part, and the type that its position declares. */\nexport interface PartSlot {\n /** The keys from the value of the document to the part. */\n readonly path: readonly Key[];\n /** The path as one text, with a dot between the keys, for example `bind.x`. A part of a list has its index. */\n readonly key: string;\n readonly item: Json;\n readonly of?: string;\n}\n\ntype Template =\n | { readonly t: \"data\"; readonly value: unknown }\n | { readonly t: \"slot\"; readonly index: number }\n | { readonly t: \"list\"; readonly items: readonly Template[] }\n | { readonly t: \"record\"; readonly fields: readonly (readonly [string, Template])[] };\n\n/** The value of a document, split into its parts, by the shape that its kind declares. */\nexport type Split =\n | {\n readonly ok: true;\n /** The parts, in the order of the value. */\n readonly parts: readonly PartSlot[];\n /** The value without the parts: a field that holds a part is not in it, and a list of parts gives `null`. */\n readonly data: Json;\n /**\n * This function gives the value with a handle in the place of each part.\n *\n * @param handles - One handle for each part, in the order of `parts`.\n * @returns The value with the handles.\n */\n fill<P>(handles: readonly P[]): unknown;\n }\n | { readonly ok: false; readonly reason: string; readonly at: readonly Key[] };\n\nclass Bad {\n constructor(\n readonly reason: string,\n readonly at: readonly Key[],\n ) {}\n}\n\n/** This function sets an own data property. Only the key `__proto__` needs `defineProperty`. */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nconst NO_SLOTS: readonly PartSlot[] = Object.freeze([]);\n\nfunction hasSlots(template: Template): boolean {\n return template.t !== \"data\";\n}\n\n/**\n * This function splits a value into its parts, by the shape that its kind declares. The evaluator, the view and\n * the static kit use the same split, thus each one sees the same parts.\n *\n * @param shape - The shape of the value. The default is data.\n * @param value - The value of the document.\n * @returns The parts and a way to fill their places, or the reason why the value does not have the shape.\n */\nexport function splitParts(shape: Shape | undefined, value: Json): Split {\n // A value without parts is data: the split needs no template.\n if (shape === undefined || shape.shape === \"none\") return { ok: true, parts: NO_SLOTS, data: value, fill: () => value };\n const parts: PartSlot[] = [];\n const slot = (item: Json, path: readonly Key[], of: string | undefined): Template => {\n parts.push({ path, key: path.join(\".\"), item, ...(of === undefined ? {} : { of }) });\n return { t: \"slot\", index: parts.length - 1 };\n };\n\n const deep = (item: Json, path: readonly Key[], of: string | undefined): Template => {\n if (isEnvelope(item)) return slot(item, path, of);\n if (Array.isArray(item)) {\n const items = (item as readonly Json[]).map((child, index) => deep(child, [...path, index], of));\n return items.some(hasSlots) ? { t: \"list\", items } : { t: \"data\", value: item };\n }\n if (isRecord(item)) {\n const fields = Object.keys(item).map((key) => [key, deep(item[key] as Json, [...path, key], of)] as const);\n return fields.some(([, child]) => hasSlots(child)) ? { t: \"record\", fields } : { t: \"data\", value: item };\n }\n return { t: \"data\", value: item };\n };\n\n const walk = (spec: Shape | undefined, item: Json, path: readonly Key[]): Template => {\n if (spec === undefined || spec.shape === \"none\") return { t: \"data\", value: item };\n if (spec.shape === \"term\") return slot(item, path, spec.of);\n if (spec.shape === \"deep\") return deep(item, path, spec.of);\n if (spec.shape === \"list\") {\n if (!Array.isArray(item)) throw new Bad(\"The value must be a list.\", path);\n const each: Shape = spec.item ?? { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) };\n return { t: \"list\", items: (item as readonly Json[]).map((child, index) => walk(each, child, [...path, index])) };\n }\n if (!isRecord(item)) throw new Bad(\"The value must be a record.\", path);\n if (spec.shape === \"map\") {\n const each: Shape = spec.item ?? { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) };\n return { t: \"record\", fields: Object.keys(item).map((key) => [key, walk(each, item[key] as Json, [...path, key])] as const) };\n }\n for (const name of spec.required ?? []) {\n if (!Object.hasOwn(item, name)) throw new Bad(`The field ${name} is missing.`, path);\n }\n const named: Readonly<Record<string, Shape>> = Array.isArray(spec.fields)\n ? Object.fromEntries((spec.fields as readonly string[]).map((name) => [name, { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) } as Shape]))\n : (spec.fields as Readonly<Record<string, Shape>>);\n const fields: (readonly [string, Template])[] = [];\n for (const key of Object.keys(item)) {\n const fieldShape = Object.hasOwn(named, key) ? named[key] : spec.rest;\n fields.push([key, walk(fieldShape, item[key] as Json, [...path, key])]);\n }\n return { t: \"record\", fields };\n };\n\n let template: Template;\n try {\n template = walk(shape, value, []);\n } catch (error) {\n if (error instanceof Bad) return { ok: false, reason: error.reason, at: error.at };\n throw error;\n }\n\n const strip = (node: Template): Json | undefined => {\n if (node.t === \"data\") return node.value as Json;\n if (node.t === \"slot\") return undefined;\n if (node.t === \"list\") return node.items.every((child) => child.t === \"slot\") ? null : (node.items.map((child) => strip(child) ?? null) as Json);\n const out: Record<string, Json> = {};\n for (const [key, child] of node.fields) {\n const kept = strip(child);\n if (kept !== undefined) setOwn(out, key, kept);\n }\n return out;\n };\n\n const fillWith = <P>(node: Template, handles: readonly P[]): unknown => {\n if (node.t === \"data\") return node.value;\n if (node.t === \"slot\") return handles[node.index];\n if (node.t === \"list\") return node.items.map((child) => fillWith(child, handles));\n const out: Record<string, unknown> = {};\n for (const [key, child] of node.fields) setOwn(out, key, fillWith(child, handles));\n return out;\n };\n\n return { ok: true, parts, data: strip(template) ?? null, fill: (handles) => fillWith(template, handles) };\n}\n\n/**\n * This function tells if the path of a part matches a pattern of a scope rule. The key `\"*\"` of a pattern matches\n * each key.\n *\n * @param path - The path of the part.\n * @param pattern - The pattern.\n * @returns `true` when the path matches.\n */\nexport function pathMatches(path: readonly Key[], pattern: readonly Key[]): boolean {\n if (path.length !== pattern.length) return false;\n for (let index = 0; index < path.length; index += 1) {\n const want = pattern[index];\n if (want !== \"*\" && String(want) !== String(path[index])) return false;\n }\n return true;\n}\n","import { type Envelope, type Json, type Key, type TypeRef, isEnvelope, typeName } from \"./doc.ts\";\nimport { type Split, splitParts } from \"./parts.ts\";\nimport { ask, type Answer } from \"./ladder.ts\";\nimport { type Lookup, type Side, type World, lookupKind } from \"./world.ts\";\nimport { type ErrorCode, type EvalError, type Result, fail, ok, placed, thrown, describe } from \"./errors.ts\";\nimport {\n type Cap,\n type Context,\n type Navigator,\n type Resolution,\n type ResolveOptions,\n type Thing,\n context as makeRootContext,\n isHostThing,\n resolve,\n worldThing,\n} from \"./deref.ts\";\n\nexport type { Context } from \"./deref.ts\";\nexport type { ErrorCode, EvalError, Result } from \"./errors.ts\";\nexport { fail, ok } from \"./errors.ts\";\n\n/**\n * This function makes a context with names and capabilities. The other roots are empty, and an evaluation sets\n * the world.\n *\n * @param names - The names and their values.\n * @param caps - The effects that the term can cause.\n * @param self - The node of the term, if it has one.\n * @returns The context.\n */\nexport function makeContext(names: Readonly<Record<string, unknown>> = {}, caps: readonly Cap[] = [], self: Thing = null): Context {\n return makeRootContext({ names, caps, self });\n}\n\n/**\n * This function gives the keys of a capability or of a kind of effect: a text is split at its dots.\n *\n * @param kind - The text or the keys.\n * @returns The keys, as texts.\n */\nexport function capKeys(kind: Cap): readonly string[] {\n return typeof kind === \"string\" ? kind.split(\".\") : kind.map(String);\n}\n\n/**\n * This function tells if the capabilities permit an effect. A capability permits the kind of its name, and each kind\n * under it: `store` permits `store.update`. The comparison is key by key, thus `fs.read` does not permit the\n * kind with the keys `fs` and `read.json`.\n *\n * @param caps - The capabilities of the context.\n * @param kind - The kind of the effect: a text with dots, or its keys.\n * @returns `true` when one capability permits it.\n */\nexport function permits(caps: readonly Cap[], kind: Cap): boolean {\n const want = capKeys(kind);\n return caps.some((cap) => {\n const have = capKeys(cap);\n return have.length <= want.length && have.every((key, index) => key === want[index]);\n });\n}\n\n/**\n * This function narrows a context for a part: the part keeps only the capabilities that the context of its parent\n * permits. Thus an evaluator cannot give a part more effects than it has.\n *\n * @param parent - The context of the parent.\n * @param next - The context that the evaluator gives the part.\n * @returns The context of the part.\n */\nexport function narrow(parent: Context, next: Context): Context {\n if (next === parent || next.caps === parent.caps) return next;\n const caps = next.caps.filter((cap) => permits(parent.caps, cap));\n return caps.length === next.caps.length ? next : { ...next, caps };\n}\n\n/**\n * The steps of an evaluation that can wait. It yields a promise only when the host makes it wait. A runner takes the\n * result of a part with `yield*`, thus a run goes on at once until an effect waits. A runner does not yield a\n * promise itself: it uses `yield*` on the steps that the kernel gives.\n */\nexport type Steps = Generator<Promise<unknown>, Result, unknown>;\n\n/** An effect that an evaluation caused, in the order of the effects. */\nexport interface Effect {\n readonly index: number;\n /** The kind of the effect, as a text with dots. */\n readonly kind: string;\n /** The keys of the kind of the effect. */\n readonly path: readonly Key[];\n readonly payload: unknown;\n /** The ID of the trace node that caused the effect, or -1 without a trace. */\n readonly node: number;\n /** The number of events before the effect. The effect comes before the end of its node. */\n readonly at: number;\n /** The keys from the root document to the document that caused the effect. */\n readonly place: readonly Key[];\n /** The context of the document that caused the effect: its names, its node and its capabilities. */\n readonly context: Context;\n}\n\n/** The host side of a run: it does one effect, and gives its result. A throw or a rejection is an error value. */\nexport type Perform = (effect: Effect) => unknown;\n\n/**\n * The runtime of one evaluation or run. Compiled code gets it with the context, and asks it to resolve paths and\n * to cause effects.\n */\nexport interface Runtime {\n readonly machine: Machine;\n /** `true` in a run: the host does each effect, and a part that waits needs a parent that can wait. */\n readonly running: boolean;\n /**\n * This function resolves a path from a context.\n *\n * @param ctx - The context.\n * @param path - The steps. The first step is a root.\n * @param options - `hops: true` records each hop. The default records them only in a traced evaluation.\n * @returns What the path reached, or an error.\n */\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect from an evaluator. In a run, an evaluator cannot cause an effect: the host does\n * each effect, thus only a runner can wait for it.\n *\n * @param ctx - The context of the document.\n * @param kind - The kind of the effect.\n * @param payload - The data of the effect.\n * @param place - The place of the document.\n * @returns The payload, or an error value.\n */\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result;\n /**\n * This function causes an effect from a runner. In a run, the host does it, and the steps wait when the host\n * waits.\n *\n * @param ctx - The context of the document.\n * @param kind - The kind of the effect.\n * @param payload - The data of the effect.\n * @param place - The place of the document.\n * @returns The steps that give the result of the host, or an error value.\n */\n runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps;\n /**\n * This function drives several steps at the same time. When one waits, the others go on.\n *\n * @param list - One function for each item. Each function starts the steps of its item.\n * @param options - The most items that run at the same time, and the stop at the first failure.\n * @returns The steps that give each result, in the order of the list.\n */\n all(list: readonly (() => Steps)[], options?: AllOptions): Generator<Promise<unknown>, readonly Result[], unknown>;\n}\n\n/**\n * The options of a drive of parts at the same time.\n *\n * - `concurrency`: the most parts that run at the same time. The default is each part.\n * - `failFast`: `true` stops at the first part that fails. The parts that did not start do not start, the parts that\n * run stop at their wait, and the results come at once. Each part without a result gives `#ABORT`.\n */\nexport interface AllOptions {\n readonly concurrency?: number;\n readonly failFast?: boolean;\n}\n\n/** Compiled code: the evaluation of a document in a context. */\nexport type Code = (ctx: Context, rt: Runtime) => Result;\n\n/** Compiled code that can wait: the run of a document in a context. */\nexport type RunCode = (ctx: Context, rt: Runtime) => Steps;\n\n/** A compiled part: its place in its parent, its binding name, and its code. It has no field with its value. */\nexport interface CompiledPart {\n /** The path in the value of the parent as one text, for example `0` or `bind.x`. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /** The code that evaluates the part. */\n readonly code: Code;\n /** The code that runs the part. Its steps can wait. */\n readonly run: RunCode;\n}\n\n/** The input of a compiler: the document, its kind, and its parts, compiled. */\nexport interface CompileInput {\n /** The text of the type of the document, for example `add` or `math.sum` after its alias. */\n readonly kind: string;\n /** The keys of the kind after each alias. */\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a compiled part in the place of each part. */\n readonly value: unknown;\n /** The value of the document without its parts. */\n readonly data: Json;\n /** The compiled parts, in the order of the value. */\n readonly parts: readonly CompiledPart[];\n /** The keys from the root document to this document. */\n readonly place: readonly Key[];\n readonly machine: Machine;\n /**\n * This function gives the value of the document with an item in the place of each part. The containers on the way\n * to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`, for example the results of the parts.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n}\n\n/**\n * A sealed part. An evaluator can read the binding name of a part and evaluate it. It cannot read the value of the\n * part, thus two parts that give the same results can replace each other.\n */\nexport interface Part {\n /** The path in the value of the parent as one text, for example `0` or `bind.x`. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /**\n * This function evaluates the part. Each call is a new evaluation.\n *\n * @param context - The context for the part. The default is the context of the parent.\n * @returns The result of the part.\n */\n evaluate(context?: Context): Result;\n}\n\n/** The input of an evaluator. */\nexport interface EvalInput {\n /** The text of the type of the document, for example `add` or `math.sum` after its alias. */\n readonly kind: string;\n /** The keys of the kind after each alias. */\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a sealed part in the place of each part. */\n readonly value: unknown;\n /** The value of the document without its parts. */\n readonly data: Json;\n /** The parts, in the order of the value. */\n readonly parts: readonly Part[];\n /** The context of the document. */\n readonly context: Context;\n /** The keys from the root document to this document. */\n readonly place: readonly Key[];\n /**\n * This function resolves a path from the context of the document.\n *\n * @param path - The steps. The first step is a root.\n * @param options - `hops: true` records each hop.\n * @returns What the path reached, or an error.\n */\n resolve(path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect. The context must have the capability for the kind of the effect. In a run, an\n * evaluator cannot cause an effect: the host does each effect, thus only a runner can wait for it.\n *\n * @param kind - The kind of the effect, for example `log`.\n * @param payload - The data of the effect.\n * @returns The payload, or the error `#CAP!`.\n */\n effect(kind: Cap, payload: unknown): Result;\n /**\n * This function gives the value of the document with an item in the place of each part, for example the result of\n * each part. The containers on the way to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n}\n\n/** A part for a runner. Its evaluation can wait for the effects in it. */\nexport interface RunPart {\n /** The path in the value of the parent as one text. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /**\n * This function evaluates the part. Each call is a new evaluation. Take its result with `yield*`.\n *\n * @param context - The context for the part. The default is the context of the parent.\n * @returns The steps of the evaluation of the part.\n */\n evaluate(context?: Context): Steps;\n}\n\n/** The input of a runner: the input of an evaluator, with parts and effects that can wait. */\nexport interface RunInput {\n readonly kind: string;\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a part for a runner in the place of each part. */\n readonly value: unknown;\n readonly data: Json;\n readonly parts: readonly RunPart[];\n readonly context: Context;\n readonly place: readonly Key[];\n resolve(path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect. In a run, the host does the effect, and the steps wait when the host waits. In\n * an evaluation, the effect gives its payload. Take its result with `yield*`.\n *\n * @param kind - The kind of the effect, for example `log`.\n * @param payload - The data of the effect.\n * @returns The steps that give the result of the host, or an error value.\n */\n effect(kind: Cap, payload: unknown): Steps;\n /**\n * This function evaluates parts at the same time. Take the results with `yield*`. A runner can give its own parts,\n * for example a part with a different context: each part needs only the function `evaluate`.\n *\n * @param parts - The parts.\n * @param options - The most parts that run at the same time, and the stop at the first failure.\n * @returns The steps that give each result, in the order of the parts.\n */\n all(parts: readonly RunPart[], options?: AllOptions): Generator<Promise<unknown>, readonly Result[], unknown>;\n /**\n * This function gives the value of the document with an item in the place of each part, for example the result of\n * each part. The containers on the way to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n}\n\n/** An evaluator that is a function of its input. The kernel calls it for each evaluation. */\nexport type EvalFn = (input: EvalInput) => Result;\n\n/** An evaluator that compiles a document one time into code. The code then evaluates it many times. */\nexport interface CompiledEvaluator {\n /**\n * This function compiles a document.\n *\n * @param input - The document, its kind and its compiled parts.\n * @returns The code that evaluates the document.\n */\n readonly compile: (input: CompileInput) => Code;\n}\n\n/** An evaluator: a function of its input, or a compiler. */\nexport type Evaluator = EvalFn | CompiledEvaluator;\n\n/** A runner that is a generator function of its input. */\nexport type RunFn = (input: RunInput) => Steps;\n\n/** A runner that compiles a document one time into code that can wait. */\nexport interface CompiledRunner {\n /**\n * This function compiles a document.\n *\n * @param input - The document, its kind and its compiled parts.\n * @returns The code that runs the document.\n */\n readonly compileRun: (input: CompileInput) => RunCode;\n}\n\n/**\n * A runner: the code of a kind whose parts or effects can wait. The same runner serves an evaluation, which does\n * not wait at any time, and a run, in which the host does each effect.\n */\nexport type Runner = RunFn | CompiledRunner;\n\n/**\n * A machine: a world of kinds, and the code of each evaluator name, of each `deref` and of each walker.\n *\n * - `maxDepth`: the deepest nesting of documents. The default is 1000.\n * - `permits`: the rule of the host for an effect. The default is the function `permits` on the capabilities.\n */\nexport interface Machine extends Navigator {\n readonly evaluators: Readonly<Record<string, Evaluator>>;\n /** The runners, by evaluator name. A runner wins over an evaluator of the same name. */\n readonly runners?: Readonly<Record<string, Runner>>;\n readonly maxDepth?: number;\n readonly permits?: (caps: readonly Cap[], kind: readonly Key[], context: Context) => boolean;\n}\n\n/** One evaluation in a trace. The children are the evaluations of its parts, in the order that they started. */\nexport interface TraceNode {\n readonly id: number;\n /** The keys from the root document to this document, as texts. */\n readonly path: readonly string[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** `true` when the type came from the container and not from an envelope. */\n readonly declared: boolean;\n /** The answer of the ladder to the verb `eval`. */\n readonly answer: Answer;\n readonly side: Side;\n /** The names that the document could read when its evaluation started. */\n readonly names: readonly string[];\n /** The names and their values when the evaluation started. */\n readonly scope: Readonly<Record<string, unknown>>;\n /** The capabilities that the document had when its evaluation started. */\n readonly caps: readonly Cap[];\n /** A short text for the root `self` when the evaluation started. */\n readonly self: string;\n /** The time of the start. Each start and each end takes one tick. */\n readonly enter: number;\n /** The time of the end. */\n readonly exit: number;\n readonly result: Result;\n readonly children: readonly TraceNode[];\n /** The indices of the effects that this document caused itself. */\n readonly effects: readonly number[];\n}\n\n/** The record of one evaluation of a document. */\nexport interface Run {\n readonly result: Result;\n readonly trace: TraceNode;\n readonly effects: readonly Effect[];\n /** The number of ticks. */\n readonly time: number;\n}\n\ninterface Building {\n id: number;\n path: readonly string[];\n doc: Envelope;\n declared: boolean;\n answer: Answer;\n side: Side;\n names: readonly string[];\n scope: Readonly<Record<string, unknown>>;\n caps: readonly Cap[];\n self: string;\n enter: number;\n exit: number;\n result: Result;\n children: Building[];\n effects: number[];\n}\n\n/** What a trace node knows from the compilation. */\ninterface Meta {\n readonly path: readonly string[];\n readonly doc: Envelope;\n readonly declared: boolean;\n readonly answer: Answer;\n readonly side: Side;\n}\n\nfunction selfLabel(self: Thing): string {\n try {\n if (isHostThing(self)) return self.label;\n if (self === null || self === undefined) return \"none\";\n return (JSON.stringify(self) ?? describe(self)).slice(0, 40);\n } catch {\n return describe(self).slice(0, 40);\n }\n}\n\nconst NO_ANSWER: Answer = { verb: \"eval\", error: \"no-answer\", steps: [] };\n\n/** A signal of the host that stops a run: the shape of the standard `AbortSignal`. */\nexport interface StopSignal {\n readonly aborted: boolean;\n readonly reason?: unknown;\n addEventListener(type: \"abort\", listener: () => void, options?: { readonly once?: boolean }): void;\n}\n\n/** The options of a run. */\nexport interface RunOptions {\n /** The host code that does each effect. Without it, an effect gives its payload, as in an evaluation. */\n readonly perform?: Perform;\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** A signal of the host. When it aborts, the run stops with `#ABORT`. */\n readonly signal?: StopSignal;\n}\n\n/** The options of an evaluation of a plan. */\nexport interface EvalOptions {\n /** A list that gets each effect, in its order. */\n readonly effects?: Effect[];\n}\n\n/** The options of a resolution without a record of hops, and with one. One object of each serves each call. */\nconst WITHOUT_HOPS: ResolveOptions = Object.freeze({ hops: false });\nconst WITH_HOPS: ResolveOptions = Object.freeze({ hops: true });\n\n/** This class holds the state of one evaluation or run: the machine, the effects, the clock and the trace. */\nclass Session implements Runtime {\n /** The list of the effects. It is made at the first effect, thus an evaluation without effects makes no list. */\n private list: Effect[] | undefined;\n tick = 0;\n nextId = 0;\n current: Building | undefined;\n readonly holder: Building | undefined;\n\n constructor(\n readonly machine: Machine,\n readonly running: boolean,\n readonly traced: boolean,\n readonly perform: Perform | undefined,\n readonly signal: StopSignal | undefined,\n effects: Effect[] | undefined,\n ) {\n this.list = effects;\n this.holder = traced ? holderNode() : undefined;\n this.current = this.holder;\n }\n\n /** The effects of the evaluation, in their order. */\n get effects(): Effect[] {\n return (this.list ??= []);\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const hops = options?.hops ?? this.traced;\n return resolve(this.machine, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n }\n\n private permitted(ctx: Context, keys: readonly Key[]): boolean {\n return this.machine.permits === undefined ? permits(ctx.caps, keys) : this.machine.permits(ctx.caps, keys, ctx);\n }\n\n private record(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result | Effect {\n const keys = typeof kind === \"string\" ? kind.split(\".\") : kind;\n const text = keys.join(\".\");\n if (!this.permitted(ctx, keys)) return fail(\"#CAP!\", `The context has no capability for the effect ${text}.`, { place });\n const node = this.current;\n const list = this.effects;\n const effect: Effect = { index: list.length, kind: text, path: keys, payload, node: node?.id ?? -1, at: this.tick, place, context: ctx };\n list.push(effect);\n if (node !== undefined) node.effects.push(effect.index);\n return effect;\n }\n\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const text = typeof kind === \"string\" ? kind : kind.join(\".\");\n if (this.running) return fail(\"#CALC!\", `The effect ${text} needs a runner: in a run, the host does each effect.`, { place });\n const made = this.record(ctx, kind, payload, place);\n return \"ok\" in made ? made : ok(payload);\n }\n\n *runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps {\n const made = this.record(ctx, kind, payload, place);\n if (\"ok\" in made) return made;\n const perform = this.perform;\n if (!this.running || perform === undefined) return ok(payload);\n const failed = (error: unknown): Result => fail(\"#CALC!\", `The host failed the effect ${made.kind}: ${describe(error)}`, { place, cause: error });\n let done: unknown;\n try {\n done = perform(made);\n } catch (error) {\n return failed(error);\n }\n if (!(done instanceof Promise)) return ok(done);\n return (yield done.then((value: unknown) => ok(value), failed)) as Result;\n }\n\n *all(list: readonly (() => Steps)[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n const results: Result[] = new Array<Result>(list.length);\n const limit = Math.max(1, options.concurrency ?? list.length);\n const failFast = options.failFast === true;\n let failed = false;\n interface Active {\n readonly index: number;\n readonly steps: Steps;\n pending: Promise<unknown>;\n }\n const active: Active[] = [];\n let next = 0;\n const settle = (index: number, result: Result): void => {\n results[index] = result;\n if (failFast && !result.ok) failed = true;\n };\n const advance = (index: number, steps: Steps, input: { readonly value?: unknown; readonly error?: unknown; readonly threw: boolean }): void => {\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = input.threw ? steps.throw(input.error) : steps.next(input.value);\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n return;\n }\n if (step.done === true) {\n settle(index, step.value);\n return;\n }\n const item: Active = { index, steps, pending: Promise.resolve() };\n item.pending = step.value.then(\n (value) => ({ item, value, threw: false }),\n (error: unknown) => ({ item, error, threw: true }),\n );\n active.push(item);\n };\n const start = (): void => {\n while (!failed && active.length < limit && next < list.length) {\n const index = next;\n next += 1;\n const begin = list[index] as () => Steps;\n let steps: Steps;\n try {\n steps = begin();\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n continue;\n }\n advance(index, steps, { threw: false });\n }\n };\n start();\n while (active.length > 0 && !failed) {\n const settled = (yield Promise.race(active.map((item) => item.pending))) as {\n readonly item: Active;\n readonly value?: unknown;\n readonly error?: unknown;\n readonly threw: boolean;\n };\n active.splice(active.indexOf(settled.item), 1);\n advance(settled.item.index, settled.item.steps, settled);\n start();\n }\n if (!failed) return results;\n const stopped = fail(\"#ABORT\", \"The part stopped: a part before it failed, and the parts run with failFast.\");\n for (const item of active) {\n try {\n item.steps.return(stopped);\n } catch {\n // The finally code of a part threw. The part stops with the abort.\n }\n }\n for (let index = 0; index < list.length; index += 1) if (results[index] === undefined) results[index] = stopped;\n return results;\n }\n\n enter(meta: Meta, ctx: Context): Building {\n const node: Building = {\n id: this.nextId,\n path: meta.path,\n doc: meta.doc,\n declared: meta.declared,\n answer: meta.answer,\n side: meta.side,\n names: Object.keys(ctx.names),\n scope: ctx.names,\n caps: ctx.caps,\n self: selfLabel(ctx.self),\n enter: this.tick,\n exit: this.tick,\n result: fail(\"#NOEVAL\", \"The evaluation did not end.\"),\n children: [],\n effects: [],\n };\n this.nextId += 1;\n this.tick += 1;\n (this.current ?? (this.holder as Building)).children.push(node);\n return node;\n }\n\n exit(node: Building, result: Result): void {\n node.result = result;\n node.exit = this.tick;\n this.tick += 1;\n }\n}\n\nfunction holderNode(): Building {\n return {\n id: -1,\n path: [],\n doc: { type: \"?\", value: null },\n declared: false,\n answer: NO_ANSWER,\n side: \"derive\",\n names: [],\n scope: {},\n caps: [],\n self: \"none\",\n enter: 0,\n exit: 0,\n result: ok(null),\n children: [],\n effects: [],\n };\n}\n\n/** This function drives steps that cannot wait. */\nfunction drive(steps: Steps): Result {\n const step = steps.next();\n if (step.done === true) return step.value;\n void step.value.catch(() => undefined);\n void steps.return(fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\"));\n return fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\");\n}\n\nconst ABORTED = Symbol(\"aborted\");\n\n/** This function drives steps that can wait. The steps before the first wait happen at once, in the call. */\nasync function driveWaiting(steps: Steps, signal: StopSignal | undefined): Promise<Result> {\n const abort = (): Result => {\n const reason = fail(\"#ABORT\", `The host stopped the run: ${describe(signal?.reason ?? \"no reason\")}`, { cause: signal?.reason });\n try {\n steps.return(reason);\n } catch {\n // The finally code of a runner threw. The run stops with the abort.\n }\n return reason;\n };\n const aborted =\n signal === undefined\n ? undefined\n : new Promise<typeof ABORTED>((resolve) => {\n if (signal.aborted) resolve(ABORTED);\n else signal.addEventListener(\"abort\", () => resolve(ABORTED), { once: true });\n });\n if (signal?.aborted === true) return abort();\n let step = steps.next();\n while (step.done !== true) {\n let value: unknown;\n try {\n value = aborted === undefined ? await step.value : await Promise.race([step.value, aborted]);\n } catch (error) {\n step = steps.throw(error);\n continue;\n }\n if (value === ABORTED) return abort();\n step = steps.next(value);\n }\n return step.value;\n}\n\nfunction isCompiledEvaluator(evaluator: Evaluator): evaluator is CompiledEvaluator {\n return typeof evaluator === \"object\" && evaluator !== null && typeof (evaluator as CompiledEvaluator).compile === \"function\";\n}\n\nfunction isCompiledRunner(runner: Runner): runner is CompiledRunner {\n return typeof runner === \"object\" && runner !== null && typeof (runner as CompiledRunner).compileRun === \"function\";\n}\n\n/** The options of a compilation. */\nexport interface PrepareOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** `true`: each evaluation records a trace. The default is `false`. */\n readonly trace?: boolean;\n}\n\n/** A compiled document. It evaluates many times, and it does the work of the ladder one time. */\nexport interface Plan {\n readonly machine: Machine;\n /** `true` when each evaluation records a trace. */\n readonly traced: boolean;\n /** The compiled root document. */\n readonly root: CompiledPart;\n /**\n * This function evaluates the document. It does not wait, and the host does no effect.\n *\n * @param context - The names and the capabilities at the root.\n * @param options - A list that gets the effects.\n * @returns The result.\n */\n evaluate(context?: Context, options?: EvalOptions): Result;\n /**\n * This function runs the document: the host does each effect, and the run waits when the host waits.\n *\n * @param context - The names and the capabilities at the root.\n * @param options - The host code that does the effects, and a signal to stop the run.\n * @returns The result, when the run ends.\n */\n run(context?: Context, options?: RunOptions): Promise<Result>;\n}\n\ninterface Compiler {\n readonly machine: Machine;\n readonly traced: boolean;\n readonly maxDepth: number;\n}\n\nfunction failing(c: Compiler, meta: Meta, place: readonly Key[], code: ErrorCode, reason: string): { readonly code: Code; readonly run: RunCode } {\n const result = fail(code, reason, { place });\n const plain: Code = () => result;\n return finish(c, meta, plain, function* () {\n return result;\n });\n}\n\nfunction finish(c: Compiler, meta: Meta, code: Code, run: RunCode): { readonly code: Code; readonly run: RunCode } {\n if (!c.traced) return { code, run };\n const tracedCode: Code = (ctx, rt) => {\n const s = rt as Session;\n const node = s.enter(meta, ctx);\n const before = s.current;\n s.current = node;\n let result: Result;\n try {\n result = code(ctx, rt);\n } finally {\n s.current = before;\n }\n s.exit(node, result);\n return result;\n };\n const tracedRun: RunCode = function* (ctx, rt) {\n const s = rt as Session;\n const node = s.enter(meta, ctx);\n const steps = run(ctx, rt);\n let input: unknown;\n let threw = false;\n for (;;) {\n const before = s.current;\n s.current = node;\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = threw ? steps.throw(input) : steps.next(input);\n } finally {\n s.current = before;\n }\n if (step.done === true) {\n s.exit(node, step.value);\n return step.value;\n }\n try {\n input = yield step.value;\n threw = false;\n } catch (error) {\n input = error;\n threw = true;\n }\n }\n };\n return { code: tracedCode, run: tracedRun };\n}\n\n/**\n * This function finds the evaluator of the verb `eval` without the record of the rungs, for a compilation without a\n * trace. It gives the same evaluator as `ask`: the own entry, then the kind, then the default of the world.\n */\nfunction evaluatorOf(world: World, envelope: Envelope | undefined, found: Lookup): { readonly name?: string; readonly unknown: boolean } {\n const own = envelope?.own;\n const ownName = own !== undefined && Object.hasOwn(own, \"eval\") ? own[\"eval\"] : undefined;\n if (ownName !== undefined) return { name: ownName, unknown: false };\n if (!found.ok) return { unknown: true };\n const verbs = found.kind.verbs;\n const name = Object.hasOwn(verbs, \"eval\") ? verbs[\"eval\"] : Object.hasOwn(world.defaults, \"eval\") ? world.defaults[\"eval\"] : undefined;\n return name === undefined ? { unknown: false } : { name, unknown: false };\n}\n\n/** The meta of a node of a compilation without a trace. Only a trace reads the meta of a node. */\nconst NO_META: Meta = Object.freeze({ path: [], doc: { type: \"?\", value: null }, declared: false, answer: NO_ANSWER, side: \"derive\" });\n\nfunction compileNode(c: Compiler, value: unknown, place: readonly Key[], declared: string | undefined, depth: number): { readonly code: Code; readonly run: RunCode } {\n const envelope = isEnvelope(value) ? (value as Envelope) : undefined;\n const doc: Envelope = envelope ?? { type: declared ?? \"?\", value: value as Json };\n const meta0: Meta = c.traced ? { path: place.map(String), doc, declared: envelope === undefined, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n if (envelope === undefined && declared === undefined) {\n return failing(c, meta0, place, \"#PART?\", \"The value has no envelope, and its position declares no type.\");\n }\n if (depth > c.maxDepth) return failing(c, meta0, place, \"#DEPTH!\", `The nesting is deeper than ${c.maxDepth} documents.`);\n\n const world = c.machine.world;\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n let meta = meta0;\n let name: string | undefined;\n let unknown: boolean;\n if (c.traced) {\n const answer = ask(world, envelope ?? {}, \"eval\", declared === undefined ? {} : { declaredType: declared });\n meta = { ...meta0, answer, side: kind?.side ?? \"derive\" };\n name = answer.evaluator;\n unknown = answer.error === \"unknown-kind\";\n } else {\n const quick = evaluatorOf(world, envelope, found);\n name = quick.name;\n unknown = quick.unknown;\n }\n const kindText = typeName(doc.type);\n if (unknown) return failing(c, meta, place, \"#KIND?\", `The world has no kind ${kindText}.`);\n const runners = c.machine.runners ?? {};\n const runner = name !== undefined && Object.hasOwn(runners, name) ? runners[name] : undefined;\n const evaluator = name !== undefined && Object.hasOwn(c.machine.evaluators, name) ? c.machine.evaluators[name] : undefined;\n if (name === undefined || (runner === undefined && evaluator === undefined)) {\n return failing(c, meta, place, \"#NOEVAL\", `No rung gives an evaluator for ${kindText}.`);\n }\n\n const split = splitParts(kind?.parts, doc.value);\n if (!split.ok) {\n const at = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n return failing(c, meta, place, \"#VALUE!\", `${split.reason}${at} The kind is ${kindText}.`);\n }\n const parts: CompiledPart[] = split.parts.map((slot) => {\n const item = slot.item;\n const compiled = compileNode(c, item, place.concat(slot.path), slot.of, depth + 1);\n // The binding name is in the header of an envelope. Most parts have no name, thus the cheap test comes first.\n const header = typeof (item as { readonly name?: unknown } | null)?.name === \"string\" && isEnvelope(item) ? (item as { readonly name: string }).name : undefined;\n return header === undefined\n ? { key: slot.key, path: slot.path, code: compiled.code, run: compiled.run }\n : { key: slot.key, path: slot.path, name: header, code: compiled.code, run: compiled.run };\n });\n const typePath = found.ok ? found.path : [];\n const input: CompileInput = {\n kind: kindText,\n typePath,\n doc,\n value: split.parts.length === 0 ? doc.value : split.fill(parts),\n data: split.data,\n parts,\n place,\n machine: c.machine,\n fill: fillOf(split, doc),\n };\n if (runner !== undefined) {\n const inner: RunCode = isCompiledRunner(runner) ? runner.compileRun(input) : interpretRun(runner, input, split.fill);\n const run = placedRun(inner, place, name);\n return finish(c, meta, runnerCode(run, place, kindText), run);\n }\n\n const inner: Code = isCompiledEvaluator(evaluator as Evaluator)\n ? (evaluator as CompiledEvaluator).compile(input)\n : interpret(evaluator as EvalFn, input, split.fill);\n const code = placedCode(inner, place, name);\n return finish(c, meta, code, runOf(code));\n}\n\n/*\n * The helpers below make the closures that a plan keeps. Each one has its own small scope. A closure that a\n * compilation made in its own scope keeps each variable of that scope that any closure there reads, for example\n * the split of the value. Thus a plan with these helpers keeps only its code.\n */\n\n/** This function gives the code of a document: the code of its evaluator, with the place of each error and of each exception. */\nfunction placedCode(inner: Code, place: readonly Key[], name: string): Code {\n return (ctx, rt) => {\n try {\n return placed(inner(ctx, rt), place);\n } catch (error) {\n return placed(thrown(error, `the evaluator ${name}`), place);\n }\n };\n}\n\n/** This function gives the steps of a runner, with the place of each error and of each exception. */\nfunction placedRun(inner: RunCode, place: readonly Key[], name: string): RunCode {\n return function* (ctx, rt) {\n try {\n return placed(yield* inner(ctx, rt), place);\n } catch (error) {\n return placed(thrown(error, `the runner ${name}`), place);\n }\n };\n}\n\n/** This function gives the code of a runner in an evaluation: its steps, which cannot wait. */\nfunction runnerCode(run: RunCode, place: readonly Key[], kindText: string): Code {\n return (ctx, rt) =>\n rt.running\n ? fail(\"#CALC!\", `${kindText} waits for effects, and its parent cannot wait. Give the parent a runner.`, { place })\n : drive(run(ctx, rt));\n}\n\n/** This function gives the steps of a run of an evaluator. The code runs at the first step, and it does not wait. */\nfunction runOf(code: Code): RunCode {\n return function* (ctx, rt) {\n return code(ctx, rt);\n };\n}\n\n/** This function gives the fill of a compile input: the value with an item in the place of each part. */\nfunction fillOf(split: Extract<Split, { readonly ok: true }>, doc: Envelope): <P>(items: readonly P[]) => unknown {\n return (items) => (split.parts.length === 0 ? doc.value : split.fill(items));\n}\n\n\nfunction interpret(fn: EvalFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): Code {\n const { kind, typePath, doc, data, place } = input;\n const compiled = input.parts;\n const hasParts = compiled.length > 0;\n return (ctx, rt) => {\n const parts: Part[] = compiled.map((part) => ({\n key: part.key,\n path: part.path,\n ...(part.name === undefined ? {} : { name: part.name }),\n evaluate: (override?: Context) => part.code(override === undefined ? ctx : narrow(ctx, override), rt),\n }));\n return fn({\n kind,\n typePath,\n doc,\n value: hasParts ? fill(parts) : doc.value,\n data,\n parts,\n context: ctx,\n place,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.effect(ctx, effectKind, payload, place),\n fill: input.fill,\n });\n };\n}\n\nfunction interpretRun(fn: RunFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): RunCode {\n const { kind, typePath, doc, data, place } = input;\n const compiled = input.parts;\n const hasParts = compiled.length > 0;\n return (ctx, rt) => {\n const parts: RunPart[] = compiled.map((part) => ({\n key: part.key,\n path: part.path,\n ...(part.name === undefined ? {} : { name: part.name }),\n evaluate: (override?: Context) => part.run(override === undefined ? ctx : narrow(ctx, override), rt),\n }));\n return fn({\n kind,\n typePath,\n doc,\n value: hasParts ? fill(parts) : doc.value,\n data,\n parts,\n context: ctx,\n place,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.runEffect(ctx, effectKind, payload, place),\n all: (list, options) => rt.all(list.map((part) => () => part.evaluate()), options),\n fill: input.fill,\n });\n };\n}\n\nfunction rootContext(machine: Machine, ctx: Context): Context {\n return ctx.world === null ? { ...ctx, world: worldThing(machine.world) } : ctx;\n}\n\n/**\n * This function compiles a document into a plan. The ladder, the kinds and the parts are known after it. A plan\n * evaluates many times. A document that does not compile gives a plan that fails with the reason, when it evaluates.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, and a trace.\n * @returns The plan.\n */\nexport function prepare(machine: Machine, doc: unknown, options: PrepareOptions = {}): Plan {\n const c: Compiler = { machine, traced: options.trace === true, maxDepth: machine.maxDepth ?? 1000 };\n let root: { readonly code: Code; readonly run: RunCode };\n try {\n root = compileNode(c, doc, [], options.declaredType, 0);\n } catch (error) {\n const result = thrown(error, \"the compilation\");\n root = {\n code: () => result,\n run: function* () {\n return result;\n },\n };\n }\n const compiled: CompiledPart = { key: \"\", path: [], code: root.code, run: root.run };\n return planOf(machine, c.traced, compiled);\n}\n\n/** This function makes the object of a plan. Its closures keep only the machine and the compiled root. */\nfunction planOf(machine: Machine, traced: boolean, root: CompiledPart): Plan {\n return {\n machine,\n traced,\n root,\n evaluate(context: Context = makeContext(), evalOptions?: EvalOptions): Result {\n const s = new Session(machine, false, traced, undefined, undefined, evalOptions?.effects);\n return root.code(rootContext(machine, context), s);\n },\n run(context: Context = makeContext(), runOptions: RunOptions = {}): Promise<Result> {\n const s = new Session(machine, true, traced, runOptions.perform, runOptions.signal, undefined);\n return driveWaiting(root.run(rootContext(machine, context), s), runOptions.signal);\n },\n };\n}\n\n/**\n * This function makes a cache of plans for one machine. A document object compiles one time. Use it only for\n * documents that do not change after they are made.\n *\n * @param machine - The machine.\n * @param options - The options of each compilation.\n * @returns A function that gives the plan of a document.\n */\nexport function planner(machine: Machine, options: PrepareOptions = {}): (doc: unknown) => Plan {\n const objects = new WeakMap<object, Plan>();\n const values = new Map<unknown, Plan>();\n return (doc) => {\n if (typeof doc === \"object\" && doc !== null) {\n let plan = objects.get(doc);\n if (plan === undefined) {\n plan = prepare(machine, doc, options);\n objects.set(doc, plan);\n }\n return plan;\n }\n let plan = values.get(doc);\n if (plan === undefined) {\n plan = prepare(machine, doc, options);\n if (values.size > 1000) values.clear();\n values.set(doc, plan);\n }\n return plan;\n };\n}\n\nfunction record(s: Session, result: Result): Run {\n const root = s.holder?.children[0];\n if (root === undefined) throw new Error(\"The evaluation made no trace.\");\n return { result, trace: root as TraceNode, effects: s.effects, time: s.tick };\n}\n\n/**\n * This function evaluates a document, and records each evaluation in a trace.\n *\n * The verb `eval` goes up the ladder for each document. The kind of the document tells where its parts are. The\n * evaluator gets each part sealed: it can evaluate the part, and it cannot read its value. A failure gives an error\n * value, and the function does not throw. An effect is recorded in its order, and nothing does it.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param context - The names and the capabilities at the root.\n * @param declaredType - The type of a bare root value.\n * @returns The result, the trace and the effects in their order.\n */\nexport function evaluate(machine: Machine, doc: unknown, context: Context = makeContext(), declaredType?: string): Run {\n const plan = prepare(machine, doc, { trace: true, ...(declaredType === undefined ? {} : { declaredType }) });\n const s = new Session(machine, false, true, undefined, undefined, undefined);\n const result = plan.root.code(rootContext(machine, context), s);\n return record(s, result);\n}\n\n/**\n * This function runs a document: an evaluation in which the host does each effect. A runner waits for its\n * parts and for its effects, thus a step can read the result of the step before. The part of the run before the\n * first wait happens at once, in the call. The run records a trace.\n *\n * @param machine - The world, the evaluators and the runners.\n * @param doc - The document, as JSON.\n * @param context - The names and the capabilities at the root.\n * @param options - The host code that does the effects, the type of a bare root value, and a signal.\n * @returns The result, the trace and the effects in their order, when the run ends.\n */\nexport async function run(machine: Machine, doc: unknown, context: Context = makeContext(), options: RunOptions = {}): Promise<Run> {\n const plan = prepare(machine, doc, { trace: true, ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }) });\n const s = new Session(machine, true, true, options.perform, options.signal, undefined);\n const result = await driveWaiting(plan.root.run(rootContext(machine, context), s), options.signal);\n return record(s, result);\n}\n\n/**\n * This function finds a node of a trace by its path.\n *\n * @param trace - The root of the trace.\n * @param path - The keys from the root.\n * @returns The first evaluation at that path, or `undefined` when the document did not evaluate.\n */\nexport function nodeAt(trace: TraceNode, path: readonly Key[]): TraceNode | undefined {\n const want = path.map(String);\n let node: TraceNode | undefined = trace;\n let at = 0;\n while (node !== undefined && at < want.length) {\n const here: TraceNode = node;\n node = here.children.find((child) => {\n const tail = child.path.slice(here.path.length);\n return tail.length > 0 && tail.every((key, index) => key === want[at + index]);\n });\n if (node !== undefined) at += node.path.length - here.path.length;\n }\n return node;\n}\n\n/**\n * This function lists the nodes of a trace in the order of their start.\n *\n * @param trace - The root of the trace.\n * @returns Each node, the root first.\n */\nexport function flatten(trace: TraceNode): readonly TraceNode[] {\n const out: TraceNode[] = [];\n const stack: TraceNode[] = [trace];\n while (stack.length > 0) {\n const node = stack.pop() as TraceNode;\n out.push(node);\n for (let index = node.children.length - 1; index >= 0; index -= 1) stack.push(node.children[index] as TraceNode);\n }\n return out.sort((a, b) => a.enter - b.enter);\n}\n\n/**\n * This function lists the errors of a trace: each node whose result is an error and whose parts did not fail\n * the same way. These nodes are where each error started.\n *\n * @param trace - The root of the trace.\n * @returns The errors, in the order of their start.\n */\nexport function failures(trace: TraceNode): readonly EvalError[] {\n return flatten(trace)\n .filter((node) => !node.result.ok && !node.children.some((child) => !child.result.ok && child.result.error === (node.result as { error: EvalError }).error))\n .map((node) => (node.result as { readonly error: EvalError }).error);\n}\n\n/** The type of a document as a reference: re-exported for the compilers. */\nexport type { TypeRef };\n","import { type Json, type Key, field, isRecord } from \"./doc.ts\";\nimport { type Context, type Evaluator, type Machine, type Part, type Result, type RunPart, type Runner, type Steps, fail, ok } from \"./evaluate.ts\";\nimport { type HostThing, type Thing, type Walker, THING, isHostThing, valueOfThing } from \"./deref.ts\";\nimport type { World } from \"./ladder.ts\";\n\n/**\n * The world of the examples: small kinds for numbers, lists, conditions, names, sequences and effects.\n * Each kind names an evaluator for `eval` and a view for `view`. The site draws each document with its view.\n */\nexport const STD_WORLD: World = {\n kinds: {\n number: { verbs: { eval: \"data.number\", view: \"view.value\" }, summary: \"A number. Its value is the result.\" },\n text: { verbs: { eval: \"data.text\", view: \"view.value\" }, summary: \"A text. Its value is the result.\" },\n bool: { verbs: { eval: \"data.bool\", view: \"view.value\" }, summary: \"A truth value. Its value is the result.\" },\n add: {\n verbs: { eval: \"math.add\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"The sum of its parts. A bare number in its list gets the type number.\",\n },\n multiply: {\n verbs: { eval: \"math.multiply\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"The product of its parts.\",\n },\n greater: {\n verbs: { eval: \"math.greater\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"True when the first part is greater than the second part.\",\n },\n list: { verbs: { eval: \"list.all\", view: \"view.op\" }, parts: { shape: \"list\" }, summary: \"The results of its parts, as a list.\" },\n if: {\n verbs: { eval: \"control.if\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"test\", \"then\", \"else\"] },\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n ref: {\n verbs: { eval: \"ref.resolve\", view: \"view.ref\" },\n summary: \"A path from a root of the context. Each step goes up the ladder of the verb deref.\",\n },\n nearest: {\n verbs: { step: \"walk.nearest\", view: \"view.card\" },\n summary: \"A step of a path: it follows a key again and again, until it reaches a node of a type.\",\n },\n panel: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n summary: \"A node of a tree. Its parts see it as self, and each node links to its parent.\",\n },\n box: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n summary: \"A node of a tree, as panel. A formula in a box can read the parent of the box.\",\n },\n math: {\n kinds: {\n sum: { type: \"ref\", value: [\"world\", \"add\"] },\n product: { type: \"ref\", value: [\"world\", \"multiply\"] },\n },\n },\n seq: {\n verbs: { eval: \"control.seq\", view: \"view.seq\" },\n parts: { shape: \"list\" },\n scope: [\n { names: { headers: true }, in: [[\"*\"]], sequential: true },\n { names: { fixed: [\"last\"] }, in: [[\"*\"]], sequential: true },\n ],\n summary: \"Its steps, in order. The result of a named step is a name for the later steps.\",\n },\n pure: {\n verbs: { eval: \"control.pure\", view: \"view.op\" },\n parts: { shape: \"list\" },\n summary: \"It evaluates its part without capabilities, thus an effect in it fails.\",\n },\n log: {\n verbs: { eval: \"effect.log\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"text\" },\n side: \"run\",\n summary: \"It writes the result of its part to the log. This is an effect.\",\n },\n write: {\n verbs: { eval: \"effect.write\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"value\"] },\n side: \"run\",\n summary: \"It writes the result of its part to the store, at its key. This is an effect.\",\n },\n },\n defaults: { view: \"view.card\" },\n};\n\nfunction isNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/** This function evaluates each part, collects the errors, and gives the values when no part failed. */\nfunction allValues(results: readonly Result[]): { readonly values: readonly unknown[] } | { readonly error: Result } {\n const errors = results.filter((result) => !result.ok);\n const first = errors[0];\n if (first !== undefined && errors.length === 1) return { error: first };\n if (errors.length > 1) return { error: fail(\"#ARGS\", `${errors.length} parts failed.`) };\n return { values: results.map((result) => (result.ok ? result.value : null)) };\n}\n\nfunction numbers(values: readonly unknown[], kind: string): readonly number[] | Result {\n const bad = values.findIndex((value) => !isNumber(value));\n if (bad !== -1) return fail(\"#VALUE!\", `Part ${bad} of ${kind} is not a number.`);\n return values.filter(isNumber);\n}\n\nfunction dataOf(type: \"number\" | \"string\" | \"boolean\"): Evaluator {\n return ({ data }) =>\n typeof data === type && (type !== \"number\" || isNumber(data))\n ? ok(data)\n : fail(\"#VALUE!\", `The value must be a ${type === \"string\" ? \"text\" : type}.`);\n}\n\n/** The code of the evaluators of the standard world, by name. */\nexport const STD_EVALUATORS: Readonly<Record<string, Evaluator>> = {\n \"data.number\": dataOf(\"number\"),\n \"data.text\": dataOf(\"string\"),\n \"data.bool\": dataOf(\"boolean\"),\n \"math.add\": ({ parts }) => {\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"add\");\n return Array.isArray(values) ? ok(values.reduce((sum, value) => sum + value, 0)) : (values as Result);\n },\n \"math.multiply\": ({ parts }) => {\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"multiply\");\n return Array.isArray(values) ? ok(values.reduce((product, value) => product * value, 1)) : (values as Result);\n },\n \"math.greater\": ({ parts }) => {\n if (parts.length !== 2) return fail(\"#VALUE!\", \"greater needs exactly two parts.\");\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"greater\");\n if (!Array.isArray(values)) return values as Result;\n const [a, b] = values as readonly number[];\n return ok((a ?? 0) > (b ?? 0));\n },\n \"ref.resolve\": ({ data, resolve }) => {\n if (!Array.isArray(data) || data.length === 0) {\n return fail(\"#VALUE!\", \"The value of ref is a path: a list that starts with a root, for example [\\\"names\\\", \\\"a\\\"].\");\n }\n const found = resolve(data as readonly Json[]);\n return found.ok ? ok(valueOfThing(found.thing)) : fail(found.code, found.reason);\n },\n \"tree.node\": (input) => treeNode(input.parts, input.context, input.kind),\n};\n\n/**\n * This function evaluates a node of a tree. The node is a host thing. A step `parent` reaches the node that holds\n * it. A step with the name of a part evaluates that part on demand, one time. Each part sees the node as self.\n */\nfunction treeNode(parts: readonly Part[], context: Context, type: string): Result {\n const memo = new Map<string, Result>();\n const read = (key: string): Result | undefined => {\n const known = memo.get(key);\n if (known !== undefined) return known;\n const part = parts.find((item) => item.key === key);\n if (part === undefined) return undefined;\n const result = part.evaluate({ ...context, self: me });\n memo.set(key, result);\n return result;\n };\n const me: HostThing & { readonly type: string } = {\n [THING]: true,\n type,\n label: `node ${type}`,\n deref(key: Key): Thing | undefined {\n if (key === \"parent\") return context.self;\n if (key === \"type\") return type;\n const result = read(String(key));\n return result?.ok === true ? result.value : undefined;\n },\n toJson(): unknown {\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key);\n out[part.key] = result?.ok === true ? result.value : null;\n }\n return out;\n },\n };\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key);\n if (result === undefined) continue;\n if (!result.ok) return result;\n out[part.key] = result.value;\n }\n return ok(out);\n}\n\n/** The options of a walker `nearest`. */\nexport interface NearestOptions {\n /**\n * This function tells if a node has the wanted type. The default compares the field `type` of a host thing.\n *\n * @param node - The node that the walk reached.\n * @param wanted - The type that the step document asks for.\n * @returns `true` when the node has the type.\n */\n readonly matches?: (node: Thing, wanted: Json | undefined) => boolean;\n /** The most hops of one walk. The default is 256. */\n readonly maxHops?: number;\n}\n\nfunction hostType(node: Thing, wanted: Json | undefined): boolean {\n return isHostThing(node) && (node as { readonly type?: unknown }).type === wanted;\n}\n\n/**\n * This function makes a walker `nearest`. The walker follows a key (the default is `parent`) until the node that it\n * reaches has the wanted type. With `self: true`, the node where the walk starts is the first candidate. A node\n * without that key ends the walk with an error.\n *\n * @param options - The test of a type and the most hops.\n * @returns The walker.\n */\nexport function nearestWalker(options: NearestOptions = {}): Walker {\n const matches = options.matches ?? hostType;\n const maxHops = options.maxHops ?? 256;\n return ({ data, here, deref }) => {\n const follow = isRecord(data) && typeof field(data, \"follow\") === \"string\" ? String(field(data, \"follow\")) : \"parent\";\n const wanted = isRecord(data) ? field(data, \"type\") : undefined;\n const fromSelf = isRecord(data) && field(data, \"self\") === true;\n let at: Thing | undefined = here;\n for (let hops = 0; hops < maxHops; hops += 1) {\n if (hops > 0 || !fromSelf) at = at === undefined || at === null ? undefined : deref(at, follow);\n if (at === undefined || at === null) return { ok: false, reason: `No node of the type ${String(wanted)} is on the way.` };\n if (matches(at, wanted)) return { ok: true, thing: at };\n }\n return { ok: false, reason: \"The walk is too long.\" };\n };\n}\n\nconst nearest: Walker = nearestWalker();\n\n/** The walkers of the standard world, by name. */\nexport const STD_WALKERS: Readonly<Record<string, Walker>> = { \"walk.nearest\": nearest };\n\n/** This function evaluates parts one after the other, and stops at the first error. */\nfunction* inOrder(parts: readonly RunPart[]): Generator<Promise<unknown>, { readonly values: readonly unknown[] } | { readonly error: Result }, unknown> {\n const values: unknown[] = [];\n for (const part of parts) {\n const result = yield* part.evaluate();\n if (!result.ok) return { error: result };\n values.push(result.value);\n }\n return { values };\n}\n\n/**\n * The runners of the standard world, by name: the kinds that can hold effects. Each one evaluates its parts in\n * order. In a run, an effect ends before the next step starts.\n */\nexport const STD_RUNNERS: Readonly<Record<string, Runner>> = {\n \"control.seq\": function* ({ parts, context }): Steps {\n let names: Record<string, unknown> = { ...context.names };\n let last: unknown = null;\n for (const part of parts) {\n const result = yield* part.evaluate({ ...context, names });\n if (!result.ok) return result;\n names = { ...names, last: result.value };\n if (part.name !== undefined) names = { ...names, [part.name]: result.value };\n last = result.value;\n }\n return ok(last);\n },\n \"control.pure\": function* ({ parts, context }) {\n const only = parts[0];\n if (only === undefined) return fail(\"#VALUE!\", \"pure needs one part.\");\n return yield* only.evaluate({ ...context, caps: [] });\n },\n \"control.if\": function* ({ parts }) {\n const test = parts.find((part) => part.key === \"test\");\n if (test === undefined) return fail(\"#VALUE!\", \"if needs a test.\");\n const chosen = yield* test.evaluate();\n if (!chosen.ok) return chosen;\n if (typeof chosen.value !== \"boolean\") return fail(\"#VALUE!\", \"The test of if must give a truth value.\");\n const branch = parts.find((part) => part.key === (chosen.value === true ? \"then\" : \"else\"));\n return branch === undefined ? ok(null) : yield* branch.evaluate();\n },\n \"list.all\": function* ({ parts }) {\n const all = yield* inOrder(parts);\n return \"error\" in all ? all.error : ok(all.values);\n },\n \"effect.log\": function* ({ parts, effect }) {\n const all = yield* inOrder(parts);\n if (\"error\" in all) return all.error;\n return yield* effect(\"log\", all.values.length === 1 ? (all.values[0] ?? null) : all.values);\n },\n \"effect.write\": function* ({ parts, data, effect }) {\n const key = isRecord(data) ? field(data, \"key\") : undefined;\n if (typeof key !== \"string\") return fail(\"#VALUE!\", \"write needs a text key.\");\n const value = parts.find((part) => part.key === \"value\");\n if (value === undefined) return fail(\"#VALUE!\", \"write needs a value.\");\n const result = yield* value.evaluate();\n if (!result.ok) return result;\n return yield* effect(\"write\", { key, value: result.value });\n },\n};\n\n/** The machine of the examples: the standard world, its evaluators, its runners and its walkers. */\nexport const STD_MACHINE: Machine = { world: STD_WORLD, evaluators: STD_EVALUATORS, runners: STD_RUNNERS, walkers: STD_WALKERS };\n\n/** The capabilities of the examples at the root: the two effects of the standard world. */\nexport const STD_CAPS: readonly string[] = [\"log\", \"write\"];\n","/** One step of a sequence: its name, the names of the earlier steps that it reads, and if it has an effect. */\nexport interface StepSpec {\n readonly id: string;\n readonly reads: readonly string[];\n readonly effect: boolean;\n}\n\n/** An edge from a step that must come first to a step that must come after it. */\nexport type Edge = readonly [before: string, after: string];\n\n/** A reference that a sequence cannot resolve. */\nexport interface OrderProblem {\n readonly step: string;\n readonly reads: string;\n /** `unknown-name`: no step has this name. `read-before-defined`: the step with this name comes later. */\n readonly problem: \"unknown-name\" | \"read-before-defined\";\n}\n\n/**\n * This function finds the references that a sequence cannot resolve. A step can read only the steps before it.\n *\n * @param steps - The steps, in the written order.\n * @returns One problem for each bad reference, in the written order.\n */\nexport function checkSteps(steps: readonly StepSpec[]): readonly OrderProblem[] {\n const problems: OrderProblem[] = [];\n steps.forEach((step, index) => {\n for (const name of step.reads) {\n const at = steps.findIndex((other) => other.id === name);\n if (at === -1) problems.push({ step: step.id, reads: name, problem: \"unknown-name\" });\n else if (at >= index) problems.push({ step: step.id, reads: name, problem: \"read-before-defined\" });\n }\n });\n return problems;\n}\n\n/**\n * This function gives the data edges: a step comes after each earlier step that it reads.\n *\n * @param steps - The steps, in the written order.\n * @returns The edges. A bad reference gives no edge.\n */\nexport function dataEdges(steps: readonly StepSpec[]): readonly Edge[] {\n const edges: Edge[] = [];\n steps.forEach((step, index) => {\n for (const name of step.reads) {\n const at = steps.findIndex((other) => other.id === name);\n if (at !== -1 && at < index) edges.push([name, step.id]);\n }\n });\n return edges;\n}\n\n/**\n * This function gives the effect edges: each step with an effect comes after the previous step with an effect.\n * Effects keep their written order. Steps without an effect get no effect edge.\n *\n * @param steps - The steps, in the written order.\n * @returns The edges, one for each pair of consecutive effect steps.\n */\nexport function effectEdges(steps: readonly StepSpec[]): readonly Edge[] {\n const edges: Edge[] = [];\n let previous: string | undefined;\n for (const step of steps) {\n if (!step.effect) continue;\n if (previous !== undefined) edges.push([previous, step.id]);\n previous = step.id;\n }\n return edges;\n}\n\n/**\n * This function tells if an order of the steps gives the same meaning as the written order.\n * The order must contain each step one time, and it must obey the data edges and the effect edges.\n *\n * @param steps - The steps, in the written order.\n * @param order - The names of the steps in the order to examine.\n * @returns `true` when the order is permitted.\n */\nexport function isAllowedOrder(steps: readonly StepSpec[], order: readonly string[]): boolean {\n if (order.length !== steps.length) return false;\n if (new Set(order).size !== order.length) return false;\n if (!steps.every((step) => order.includes(step.id))) return false;\n const position = new Map(order.map((id, index) => [id, index] as const));\n return [...dataEdges(steps), ...effectEdges(steps)].every(\n ([before, after]) => (position.get(before) ?? 0) < (position.get(after) ?? 0),\n );\n}\n\n/**\n * This function puts the steps in layers. Each step goes one layer after the last step that it must follow.\n * The steps of one layer do not depend on each other, thus they can run at the same time.\n *\n * @param steps - The steps, in the written order.\n * @returns The layers, first to last. Each layer keeps the written order.\n */\nexport function layers(steps: readonly StepSpec[]): readonly (readonly string[])[] {\n const edges = [...dataEdges(steps), ...effectEdges(steps)];\n const depth = new Map<string, number>();\n for (const step of steps) {\n const before = edges.filter(([, after]) => after === step.id).map(([first]) => depth.get(first) ?? 0);\n depth.set(step.id, before.length === 0 ? 0 : Math.max(...before) + 1);\n }\n const result: string[][] = [];\n for (const step of steps) {\n const at = depth.get(step.id) ?? 0;\n while (result.length <= at) result.push([]);\n result[at]?.push(step.id);\n }\n return result;\n}\n","import type { Envelope } from \"./doc.ts\";\nimport type { Side } from \"./ladder.ts\";\n\n/** The parts of a context. A term can reach outside itself only through these parts. */\nexport const PARTS = [\"self\", \"names\", \"world\", \"event\", \"caps\"] as const;\n\n/** One part of a context. */\nexport type Part = (typeof PARTS)[number];\n\n/** The description of one part of a context. */\nexport interface PartInfo {\n readonly part: Part;\n readonly title: string;\n /** What a reference through this part reaches. */\n readonly reaches: string;\n /** The direction in which a reference through this part goes. */\n readonly direction: string;\n}\n\n/** The descriptions of the parts, in the order of `PARTS`. */\nexport const PART_INFO: readonly PartInfo[] = [\n {\n part: \"self\",\n title: \"Self\",\n reaches: \"A position in a structure: the node itself, its parent, its children or its siblings.\",\n direction: \"Any direction that a move permits: up, down or to the side.\",\n },\n {\n part: \"names\",\n title: \"Names\",\n reaches: \"The values that a binding gives: a let, a parameter, or the result of an earlier step.\",\n direction: \"Back, to the place where the program binds the name.\",\n },\n\n {\n part: \"world\",\n title: \"World\",\n reaches: \"The stored documents and collections, by an absolute ID or by a query.\",\n direction: \"Out, to the store.\",\n },\n {\n part: \"event\",\n title: \"Event\",\n reaches: \"The trigger of a run: the event and its values.\",\n direction: \"From the past, to the run that the event starts.\",\n },\n {\n part: \"caps\",\n title: \"Capabilities\",\n reaches: \"The effects that a term can cause. A part of the term gets the same set or a smaller set.\",\n direction: \"Down, and only smaller.\",\n },\n];\n\n/**\n * What a construct gives the parts of its body, for one part of the context.\n *\n * - `same`: the parts get the same value.\n * - `extends`: the parts get the value with more names.\n * - `moves`: the parts get a new position.\n * - `narrows`: the parts get a smaller set.\n * - `sets`: the parts get a new value.\n * - `none`: the parts get nothing.\n */\nexport type Give = \"same\" | \"extends\" | \"moves\" | \"narrows\" | \"sets\" | \"none\";\n\n/** How a construct uses one part of the context. */\nexport interface Use {\n readonly reads: boolean;\n readonly gives: Give;\n readonly note: string;\n}\n\n/** A construct of a language, and how it uses each part of the context. */\nexport interface Construct {\n readonly id: string;\n readonly title: string;\n readonly side: Side;\n readonly summary: string;\n readonly example: Envelope;\n readonly uses: Readonly<Record<Part, Use>>;\n}\n\nconst NONE: Use = { reads: false, gives: \"none\", note: \"It does not use this part.\" };\n\n/** Six constructs that show the range of the context. */\nexport const CONSTRUCTS: readonly Construct[] = [\n {\n id: \"formula\",\n title: \"Formula\",\n side: \"derive\",\n summary: \"A pure formula that gives a value at one position of a structure.\",\n example: {\n type: \"let\",\n value: {\n bind: { gap: 8 },\n body: { type: [\"ops\", \"add\"], value: [{ type: \"ref\", value: [\"self\", \"parent\", \"width\"] }, { type: \"ref\", value: [\"names\", \"gap\"] }] },\n },\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"A let binds names for its body.\" },\n self: { reads: true, gives: \"moves\", note: \"A move reads the parent. An axis moves self to each target.\" },\n world: NONE,\n event: NONE,\n caps: { reads: false, gives: \"none\", note: \"A formula causes no effect, thus its parts get no capability.\" },\n },\n },\n {\n id: \"sequence\",\n title: \"Sequence\",\n side: \"run\",\n summary: \"A list of steps. A step can read the result of each earlier step by its name.\",\n example: {\n type: \"seq\",\n value: [\n { type: [\"store\", \"find\"], value: { match: { board: \"b1\" } }, name: \"cards\" },\n { type: [\"store\", \"patch\"], value: { ids: { type: \"ref\", value: [\"names\", \"cards\", \"ids\"] }, set: { done: true } } },\n ],\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"The result of each step is a name for the later steps.\" },\n self: NONE,\n world: { reads: true, gives: \"same\", note: \"A step reads and writes the store through a procedure.\" },\n event: { reads: false, gives: \"same\", note: \"The steps get the event of the run without a change.\" },\n caps: { reads: true, gives: \"narrows\", note: \"A nested call gets the same capabilities or fewer.\" },\n },\n },\n {\n id: \"node\",\n title: \"Tree node\",\n side: \"derive\",\n summary: \"A node of a document tree. Its data and its box go down to its children.\",\n example: {\n type: \"node\",\n value: { data: { title: \"Notes\" }, children: [{ type: \"text\", value: { type: \"ref\", value: [\"names\", \"title\"] } }] },\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"The data of the node becomes a name for its children.\" },\n self: { reads: true, gives: \"moves\", note: \"Each child becomes self for its own part.\" },\n world: { reads: true, gives: \"same\", note: \"A node can show stored documents.\" },\n event: NONE,\n caps: NONE,\n },\n },\n {\n id: \"rule\",\n title: \"Layout rule\",\n side: \"derive\",\n summary: \"A rule that gives the box of a child from the box of its parent.\",\n example: { type: [\"layouts\", \"stack\"], value: { gap: 8 } },\n uses: {\n names: { reads: true, gives: \"none\", note: \"The rule reads its parameters.\" },\n self: { reads: true, gives: \"none\", note: \"The rule reads the box of the parent and the key of the child.\" },\n world: NONE,\n event: NONE,\n caps: NONE,\n },\n },\n {\n id: \"handler\",\n title: \"Event handler\",\n side: \"run\",\n summary: \"A run that an event starts. It holds a sequence as data until the event comes.\",\n example: {\n type: \"on\",\n value: {\n event: \"click\",\n run: { type: \"seq\", value: [{ type: [\"card\", \"toggle\"], value: { id: { type: \"ref\", value: [\"event\", \"target\"] } } }] },\n },\n },\n uses: {\n names: { reads: true, gives: \"same\", note: \"The handler reads the names of its place.\" },\n self: { reads: true, gives: \"same\", note: \"The handler knows the node that got the event.\" },\n world: { reads: true, gives: \"same\", note: \"The run reads and writes the store.\" },\n event: { reads: true, gives: \"sets\", note: \"The handler gives the event to its run.\" },\n caps: { reads: true, gives: \"narrows\", note: \"The run gets only the capabilities of the handler.\" },\n },\n },\n {\n id: \"query\",\n title: \"Query\",\n side: \"derive\",\n summary: \"A selection of stored documents. A storage adapter decides where it runs.\",\n example: { type: \"query\", value: { collection: \"cards\", match: { board: { type: \"ref\", value: [\"names\", \"board\"] } } } },\n uses: {\n names: { reads: true, gives: \"none\", note: \"The query reads its parameters.\" },\n self: NONE,\n world: { reads: true, gives: \"none\", note: \"The query reads one collection.\" },\n event: NONE,\n caps: NONE,\n },\n },\n];\n","import { type Envelope, type Json, type Key, isEnvelope, isKey, isRecord, typeName } from \"./doc.ts\";\nimport { type Kind, type NamesSource, type ScopeRule, type World, lookupKind } from \"./world.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type PartSlot, pathMatches, splitParts } from \"./parts.ts\";\nimport { type Cap, type Root, ROOTS, isRef } from \"./deref.ts\";\nimport type { ErrorCode } from \"./errors.ts\";\nimport { type Machine, permits } from \"./evaluate.ts\";\n\n/** One document that a walk visits. */\nexport interface DocVisit {\n /** The keys from the root document to this document, through the parts. It is the place of an error. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to this document. A change at this path changes this document. */\n readonly at: readonly Key[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** `true` when the type came from the position and not from an envelope. */\n readonly declared: boolean;\n /** The kind of the document, when the world has it. */\n readonly kind?: Kind;\n /** The keys of the kind after each alias. */\n readonly typePath?: readonly Key[];\n /** The number of documents around this document. The root has 0. */\n readonly depth: number;\n /** The names that the kinds around this document bind for it. */\n readonly names: ReadonlySet<string>;\n /** The names that a sequence around this document binds only for the parts after it. */\n readonly later: ReadonlySet<string>;\n}\n\n/** A position that a walk cannot read as a document. */\nexport interface WalkProblem {\n readonly place: readonly Key[];\n readonly at: readonly Key[];\n readonly code: \"#PART?\" | \"#VALUE!\";\n readonly reason: string;\n}\n\n/** The options of a walk. */\nexport interface WalkOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The names that the host binds at the root. */\n readonly names?: readonly string[];\n /**\n * This function gets each position that is not a document.\n *\n * @param problem - The position and the reason.\n */\n readonly problem?: (problem: WalkProblem) => void;\n}\n\nfunction valueAt(value: unknown, path: readonly Key[]): unknown {\n let here: unknown = value;\n for (const key of path) {\n if (Array.isArray(here)) here = here[Number(key)];\n else if (isRecord(here) && Object.hasOwn(here, String(key))) here = here[String(key)];\n else return undefined;\n }\n return here;\n}\n\nfunction headerName(item: Json): string | undefined {\n return isEnvelope(item) && typeof (item as { readonly name?: unknown }).name === \"string\" ? (item as { readonly name: string }).name : undefined;\n}\n\nfunction namesOf(source: NamesSource, value: unknown, covered: readonly PartSlot[]): readonly string[] {\n if (\"fixed\" in source) return source.fixed;\n if (\"keysAt\" in source) {\n const at = valueAt(value, source.keysAt);\n return isRecord(at) ? Object.keys(at) : [];\n }\n if (\"listAt\" in source) {\n const at = valueAt(value, source.listAt);\n return Array.isArray(at) ? (at as readonly unknown[]).filter((item): item is string => typeof item === \"string\") : [];\n }\n if (\"textAt\" in source) {\n const at = valueAt(value, source.textAt);\n if (typeof at === \"string\") return [at];\n return source.otherwise === undefined ? [] : [source.otherwise];\n }\n return covered.map((slot) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n}\n\n/** The names that the scope rules of a kind give each part, and the names that only later parts see. */\nfunction scopesOf(rules: readonly ScopeRule[] | undefined, value: unknown, slots: readonly PartSlot[]): { readonly sees: readonly (readonly string[])[]; readonly later: readonly (readonly string[])[] } {\n const sees: string[][] = slots.map(() => []);\n const later: string[][] = slots.map(() => []);\n for (const rule of rules ?? []) {\n const covered = slots.map((slot, index) => ({ slot, index })).filter(({ slot }) => rule.in.some((pattern) => pathMatches(slot.path, pattern)));\n if (rule.sequential !== true) {\n const names = namesOf(rule.names, value, covered.map(({ slot }) => slot));\n for (const { index } of covered) sees[index]?.push(...names);\n continue;\n }\n if (\"headers\" in rule.names) {\n covered.forEach(({ index }, position) => {\n const before = covered.slice(0, position).map(({ slot }) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n const after = covered.slice(position).map(({ slot }) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n sees[index]?.push(...before);\n later[index]?.push(...after);\n });\n continue;\n }\n const names = namesOf(rule.names, value, covered.map(({ slot }) => slot));\n covered.forEach(({ index }, position) => {\n if (position > 0) sees[index]?.push(...names);\n else later[index]?.push(...names);\n });\n }\n return { sees, later };\n}\n\n/** The names of a walk without names. A walk does not change a set at any time: it makes a new set to add names. */\nconst NO_NAMES: ReadonlySet<string> = new Set();\n\n/** This function gives the options of a walk without the names of the host. */\nfunction withoutNames(options: WalkOptions): WalkOptions {\n const { names: _host, ...rest } = options;\n return rest;\n}\n\n/**\n * This function visits each document of a document: the root and each part at each depth, by the contracts of the\n * kinds. A part of a kind that the world does not have is not visited. The walk uses no stack of the host for the\n * depth, thus a deep document cannot overflow it.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param visit - The function that gets each document. It gives `\"skip\"` to not visit the parts of a document.\n * @param options - The type of a bare root value, the names of the host, and a function for the problems.\n */\nexport function walk(world: World, doc: unknown, visit: (visit: DocVisit) => void | \"skip\", options: WalkOptions = {}): void {\n interface Item {\n readonly value: unknown;\n readonly place: readonly Key[];\n readonly at: readonly Key[];\n readonly declared: string | undefined;\n readonly depth: number;\n readonly names: ReadonlySet<string>;\n readonly later: ReadonlySet<string>;\n }\n const names: ReadonlySet<string> = options.names === undefined || options.names.length === 0 ? NO_NAMES : new Set(options.names);\n const stack: Item[] = [{ value: doc, place: [], at: [], declared: options.declaredType, depth: 0, names, later: NO_NAMES }];\n while (stack.length > 0) {\n const item = stack.pop() as Item;\n const envelope = isEnvelope(item.value) ? (item.value as Envelope) : undefined;\n if (envelope === undefined && item.declared === undefined) {\n options.problem?.({ place: item.place, at: item.at, code: \"#PART?\", reason: \"The value has no envelope, and its position declares no type.\" });\n continue;\n }\n const doc: Envelope = envelope ?? { type: item.declared ?? \"?\", value: item.value as Json };\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n const seen: DocVisit =\n kind === undefined\n ? { place: item.place, at: item.at, doc, declared: envelope === undefined, depth: item.depth, names: item.names, later: item.later }\n : {\n place: item.place,\n at: item.at,\n doc,\n declared: envelope === undefined,\n kind,\n typePath: found.ok ? found.path : [],\n depth: item.depth,\n names: item.names,\n later: item.later,\n };\n const answer = visit(seen);\n if (answer === \"skip\" || kind === undefined) continue;\n const split = splitParts(kind.parts, doc.value);\n if (!split.ok) {\n const at = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n options.problem?.({ place: item.place, at: item.at, code: \"#VALUE!\", reason: `${split.reason}${at} The kind is ${typeName(doc.type)}.` });\n continue;\n }\n const { sees, later } = scopesOf(kind.scope, doc.value, split.parts);\n const base = envelope === undefined ? item.at : [...item.at, \"value\"];\n for (let index = split.parts.length - 1; index >= 0; index -= 1) {\n const slot = split.parts[index] as PartSlot;\n const extra = sees[index] ?? [];\n const hidden = later[index] ?? [];\n stack.push({\n value: slot.item,\n place: [...item.place, ...slot.path],\n at: [...base, ...slot.path],\n declared: slot.of,\n depth: item.depth + 1,\n names: extra.length === 0 ? item.names : new Set([...item.names, ...extra]),\n later: hidden.length === 0 ? item.later : new Set([...item.later, ...hidden]),\n });\n }\n }\n}\n\n/** One reference of a document. */\nexport interface RefUse {\n /** The place of the reference document, through the parts. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to the reference document. */\n readonly at: readonly Key[];\n /** The path of the reference: its root and its steps. */\n readonly path: readonly Json[];\n readonly root: string;\n /** `false` when a kind around the reference binds its first name. A reference to another root is free. */\n readonly free: boolean;\n}\n\n/**\n * This function finds each reference of a document: each document of the type `ref` that a walk reaches. A\n * reference to a name that a kind around it binds is not free. The others are what the document reads from\n * outside: its dependencies.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value. The names of the host do not change the result.\n * @returns The references, in the order of the document.\n */\nexport function refsOf(world: World, doc: unknown, options: WalkOptions = {}): readonly RefUse[] {\n const out: RefUse[] = [];\n // The walk gets no names of the host: a name that the host binds is a dependency, thus its reference is free.\n const rest: WalkOptions = options.names === undefined ? options : withoutNames(options);\n walk(\n world,\n doc,\n (v) => {\n if (!isRef(v.doc)) return undefined;\n const path = v.doc.value as readonly Json[];\n const root = typeof path[0] === \"string\" ? path[0] : \"\";\n const first = path[1];\n const bound = root === \"names\" && isKey(first) && v.names.has(String(first));\n out.push({ place: v.place, at: v.at, path, root, free: !bound });\n return \"skip\";\n },\n rest,\n );\n return out;\n}\n\nfunction setAt(value: unknown, path: readonly Key[], next: unknown): unknown {\n if (path.length === 0) return next;\n const [key, ...rest] = path as [Key, ...Key[]];\n if (Array.isArray(value)) {\n const copy = [...value];\n copy[Number(key)] = setAt(value[Number(key)], rest, next);\n return copy;\n }\n const record = (isRecord(value) ? value : {}) as Readonly<Record<string, unknown>>;\n const copy: Record<string, unknown> = {};\n for (const name of Object.keys(record)) Object.defineProperty(copy, name, { value: record[name], enumerable: true, writable: true, configurable: true });\n Object.defineProperty(copy, String(key), { value: setAt(record[String(key)], rest, next), enumerable: true, writable: true, configurable: true });\n return copy;\n}\n\n/**\n * This function changes the free references of a document. The document is not changed: the function gives a new\n * document that shares each part without a change.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param change - The function that gives the new document of a reference, or `undefined` to keep it.\n * @param options - The type of a bare root value, and the names that the host binds at the root.\n * @returns The new document.\n */\nexport function mapRefs(world: World, doc: unknown, change: (use: RefUse) => unknown, options: WalkOptions = {}): unknown {\n let out = doc;\n for (const use of refsOf(world, doc, options)) {\n if (!use.free) continue;\n const next = change(use);\n if (next !== undefined) out = setAt(out, use.at, next);\n }\n return out;\n}\n\n/** A problem that a check finds before a document runs. */\nexport interface Issue {\n readonly code: ErrorCode;\n /** The keys from the root document to the document with the problem. */\n readonly place: readonly Key[];\n readonly reason: string;\n}\n\n/** The options of a check. */\nexport interface CheckOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The names that the host binds at the root. `\"any\"` does not check the names. The default is no names. */\n readonly names?: readonly string[] | \"any\";\n /** The capabilities at the root. Without them, the check does not check the effects. */\n readonly caps?: readonly Cap[];\n}\n\n/**\n * This function checks a document before an evaluation, by the contracts of its kinds. It finds the problems\n * that an evaluation finds when it reaches them:\n *\n * - `#KIND?`: a kind that the world does not have.\n * - `#NOEVAL`: no evaluator.\n * - `#VALUE!`: a value without the shape of its kind.\n * - `#PART?`: a value without a type.\n * - `#DEPTH!`: too much nesting.\n * - `#REF!` and `#STEP?`: a bad path.\n * - `#NAME?`: a name that nothing binds.\n * - `#CAP!`: an effect that the capabilities do not permit.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, the names of the host and the capabilities.\n * @returns The problems, in the order of the document.\n */\nexport function check(machine: Machine, doc: unknown, options: CheckOptions = {}): readonly Issue[] {\n const issues: Issue[] = [];\n const maxDepth = machine.maxDepth ?? 1000;\n const anyName = options.names === \"any\";\n const roots: readonly string[] = machine.roots ?? ROOTS;\n const has = (table: Readonly<Record<string, unknown>> | undefined, name: string): boolean => table !== undefined && Object.hasOwn(table, name);\n walk(\n machine.world,\n doc,\n (v) => {\n if (v.depth > maxDepth) {\n issues.push({ code: \"#DEPTH!\", place: v.place, reason: `The nesting is deeper than ${maxDepth} documents.` });\n return \"skip\";\n }\n const header = v.declared ? {} : v.doc;\n const answer = ask(machine.world, header, \"eval\", v.declared ? { declaredType: typeName(v.doc.type) } : {});\n if (answer.error === \"unknown-kind\") {\n issues.push({ code: \"#KIND?\", place: v.place, reason: `The world has no kind ${typeName(v.doc.type)}.` });\n return \"skip\";\n }\n const name = answer.evaluator;\n if (name === undefined || (!has(machine.evaluators, name) && !has(machine.runners, name))) {\n issues.push({ code: \"#NOEVAL\", place: v.place, reason: `No rung gives an evaluator for ${typeName(v.doc.type)}.` });\n }\n if (options.caps !== undefined && v.kind?.effects !== undefined) {\n const kinds: readonly (readonly Key[])[] = v.kind.effects === \"type\" ? [v.typePath ?? []] : v.kind.effects.map((kind) => kind.split(\".\"));\n for (const kind of kinds) {\n if (!permits(options.caps, kind)) issues.push({ code: \"#CAP!\", place: v.place, reason: `The capabilities do not permit the effect ${kind.join(\".\")}.` });\n }\n }\n if (!isRef(v.doc)) return undefined;\n const path = v.doc.value as readonly Json[];\n const root = path[0];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) {\n issues.push({ code: \"#REF!\", place: v.place, reason: `A path starts with a root: ${ROOTS.join(\", \")}.` });\n return \"skip\";\n }\n if (!roots.includes(root)) {\n issues.push({ code: \"#REF!\", place: v.place, reason: `The root ${root} is not open here. The open roots are ${roots.join(\", \")}.` });\n }\n const first = path[1];\n if (root === (\"names\" as Root) && !anyName && isKey(first) && !v.names.has(String(first))) {\n const later = v.later.has(String(first));\n issues.push({\n code: \"#NAME?\",\n place: v.place,\n reason: later ? `The name ${String(first)} is bound by a later step.` : `Nothing binds the name ${String(first)}.`,\n });\n }\n path.slice(1).forEach((step) => {\n if (isKey(step)) return;\n const found = isEnvelope(step) ? lookupKind(machine.world, step.type) : undefined;\n const walker = found?.ok === true && Object.hasOwn(found.kind.verbs, \"step\") ? found.kind.verbs[\"step\"] : undefined;\n if (walker === undefined || !has(machine.walkers, walker)) {\n issues.push({ code: \"#STEP?\", place: v.place, reason: \"A step is a key, or a document of a kind with the verb step.\" });\n }\n });\n return \"skip\";\n },\n {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(Array.isArray(options.names) ? { names: options.names } : {}),\n problem: (problem) => issues.push({ code: problem.code, place: problem.place, reason: problem.reason }),\n },\n );\n return issues;\n}\n","import { type Json, isRecord } from \"./doc.ts\";\nimport type { Kind, WorldEntry } from \"./world.ts\";\nimport { valueOfThing } from \"./deref.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, thrown } from \"./errors.ts\";\nimport type { Code, CompileInput, CompiledEvaluator, CompiledPart, Evaluator, Machine } from \"./evaluate.ts\";\n\n/** An operation of a formula language: a function of the values of its arguments. */\nexport type OpFn = (...args: never[]) => unknown;\n\n/**\n * A lazy operation: it gets one function for each argument. It evaluates only the arguments that it needs, for\n * example a default for an error.\n */\nexport type LazyOp = (args: readonly (() => Result)[]) => Result;\n\n/** The code of an extension: it gives the value of the data of an extension document. */\nexport type ExtFn = (data: Json) => Result;\n\n/**\n * The rules of one formula language: its operations, and the rules that differ between languages.\n *\n * - `ops`: the operations of the namespace `ops`, by their name (the keys after `ops`, with dots between them).\n * - `lazy`: the operations that evaluate their arguments themselves.\n * - `ext`: the extensions of the namespace `ext`, by their name. The kit has `ext.undefined` and `ext.number`.\n * - `truthy`: the truth of a value for `if`, `and` and `or`. `undefined` is an error `#VALUE!`. The default\n * accepts only `true` and `false`.\n * - `otherwise`: the value of an `if` without `else`. The default is `null`. A profile with this key gives its value,\n * also `undefined`.\n * - `logic`: what `and` and `or` give: a truth value (the default), or the value that decided.\n * - `omit`: the errors that leave a field out of a `record`, as an absent value.\n * - `missing`: the values that a reference cannot give. Such a value gives `#N/A`.\n * - `check`: a check of the value of an operation, for example \"a number must be finite\".\n */\nexport interface FormulaProfile {\n readonly ops?: Readonly<Record<string, OpFn>> | ((name: string) => OpFn | undefined);\n readonly lazy?: Readonly<Record<string, LazyOp>>;\n readonly ext?: Readonly<Record<string, ExtFn>>;\n readonly truthy?: (value: unknown) => boolean | undefined;\n readonly otherwise?: unknown;\n readonly logic?: \"boolean\" | \"value\";\n readonly omit?: (error: EvalError) => boolean;\n readonly missing?: (value: unknown) => boolean;\n readonly check?: (value: unknown, op: string) => Result | undefined;\n}\n\n/** The value of a name whose binding failed. A reference to the name gives the error. */\nexport class Held {\n constructor(readonly error: EvalError) {}\n}\n\nconst CLOSURE: unique symbol = Symbol.for(\"coeval.closure\") as never;\n\n/** A function that the construct `fn` made. It throws a `Failure` when its body fails. */\nexport type Closure = ((...args: readonly unknown[]) => unknown) & { readonly [CLOSURE]: { readonly params: readonly string[] } };\n\n/**\n * This function tells if a value is a function that the construct `fn` made.\n *\n * @param value - The value.\n * @returns `true` for a closure.\n */\nexport function isClosure(value: unknown): value is Closure {\n return typeof value === \"function\" && (value as Partial<Closure>)[CLOSURE] !== undefined;\n}\n\n/** The standard extensions: the values that JSON cannot write. */\nexport const STD_EXT: Readonly<Record<string, ExtFn>> = {\n undefined: () => ok(undefined),\n number: (data) => {\n if (data === \"NaN\") return ok(Number.NaN);\n if (data === \"Infinity\") return ok(Number.POSITIVE_INFINITY);\n if (data === \"-Infinity\") return ok(Number.NEGATIVE_INFINITY);\n if (data === \"-0\") return ok(-0);\n return fail(\"#VALUE!\", \"The value of ext.number is NaN, Infinity, -Infinity or -0.\");\n },\n};\n\n/** The truth of a value in the rules of JavaScript: `0`, `\"\"`, `null`, `undefined` and `NaN` are false. */\nexport function jsTruthy(value: unknown): boolean {\n return Boolean(value);\n}\n\nfunction strictTruthy(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\n/**\n * This function sets an own data property. Only the key `__proto__` needs `defineProperty`: an assignment to it\n * changes the prototype. An assignment is faster for each other key of a new plain object.\n */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nfunction compiled(compile: (input: CompileInput) => Code): CompiledEvaluator {\n return { compile };\n}\n\nfunction partsOf(value: unknown): Readonly<Record<string, CompiledPart>> {\n return isRecord(value) ? (value as unknown as Readonly<Record<string, CompiledPart>>) : {};\n}\n\nconst LIT_SUMMARY = \"A literal: its value is the result.\";\n\n/**\n * This function makes the kinds of the formula kit, for a world. The kinds are the shared constructs of D13 and\n * the namespaces `ops` and `ext`. A bare value in a position of a term is a literal.\n *\n * @returns The entries of the world, by their key.\n */\nexport function formulaKinds(): Readonly<Record<string, WorldEntry>> {\n const term = { shape: \"term\", of: \"lit\" } as const;\n const terms = { shape: \"list\", of: \"lit\" } as const;\n const kinds: Record<string, Kind | WorldEntry> = {\n lit: { verbs: { eval: \"formula.lit\" }, summary: LIT_SUMMARY },\n ref: { verbs: { eval: \"formula.ref\" }, summary: \"A path from a root of the context. Its result is what the path reaches.\" },\n record: { verbs: { eval: \"formula.record\" }, parts: { shape: \"map\", of: \"lit\" }, summary: \"A record: each field is a term.\" },\n list: { verbs: { eval: \"formula.list\" }, parts: terms, summary: \"A list: each item is a term.\" },\n let: {\n verbs: { eval: \"formula.let\" },\n parts: { shape: \"record\", fields: { bind: { shape: \"map\", of: \"lit\" }, body: term }, required: [\"bind\", \"body\"] },\n scope: [{ names: { keysAt: [\"bind\"] }, in: [[\"body\"]] }],\n summary: \"Names for the body. Each binding sees the names around the let, not the other bindings.\",\n },\n fn: {\n verbs: { eval: \"formula.fn\" },\n parts: { shape: \"record\", fields: { body: term }, required: [\"params\", \"body\"] },\n scope: [{ names: { listAt: [\"params\"] }, in: [[\"body\"]] }],\n summary: \"A function: its parameters are names for its body.\",\n },\n call: {\n verbs: { eval: \"formula.call\" },\n parts: { shape: \"record\", fields: { fn: term, args: terms }, required: [\"fn\"] },\n summary: \"It calls a function with the values of its arguments.\",\n },\n if: {\n verbs: { eval: \"formula.if\" },\n parts: { shape: \"record\", fields: { test: term, then: term, else: term }, required: [\"test\", \"then\"] },\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n and: { verbs: { eval: \"formula.and\" }, parts: terms, summary: \"True when each term is true. It stops at the first false term.\" },\n or: { verbs: { eval: \"formula.or\" }, parts: terms, summary: \"True when one term is true. It stops at the first true term.\" },\n ops: { kinds: {}, fallback: { verbs: { eval: \"formula.op\" }, parts: terms, summary: \"An operation of the language, applied to the values of its terms.\" } },\n ext: { kinds: {}, fallback: { verbs: { eval: \"formula.ext\" }, summary: \"An extension of the language. Its value is data.\" } },\n };\n return kinds as Readonly<Record<string, WorldEntry>>;\n}\n\n/**\n * This function makes the evaluators of the formula kit for one language. Each evaluator compiles its document\n * one time into code.\n *\n * @param profile - The operations and the rules of the language.\n * @returns The evaluators, by their name.\n */\nexport function formulaEvaluators(profile: FormulaProfile = {}): Readonly<Record<string, Evaluator>> {\n const truthy = profile.truthy ?? strictTruthy;\n const otherwise = ok(Object.hasOwn(profile, \"otherwise\") ? profile.otherwise : null);\n const logicValue = profile.logic === \"value\";\n const omit = profile.omit;\n const missing = profile.missing;\n const check = profile.check;\n const lookup = (name: string): OpFn | undefined => {\n const ops = profile.ops;\n if (ops === undefined) return undefined;\n if (typeof ops === \"function\") return ops(name);\n return Object.hasOwn(ops, name) ? ops[name] : undefined;\n };\n const notTruth = (what: string): Failed => fail(\"#VALUE!\", `The ${what} must give a truth value.`);\n\n return {\n \"formula.lit\": compiled(({ doc }) => {\n const result = ok(doc.value);\n return () => result;\n }),\n\n \"formula.ref\": compiled(({ doc }) => {\n const path = doc.value;\n if (!Array.isArray(path) || path.length === 0) {\n const bad = fail(\"#VALUE!\", 'The value of ref is a path: a list that starts with a root, for example [\"names\", \"a\"].');\n return () => bad;\n }\n // A path through a name whose binding failed gives the error of the binding.\n const head = path[0] === \"names\" && typeof path[1] === \"string\" ? path[1] : undefined;\n return (ctx, rt) => {\n if (head !== undefined && Object.hasOwn(ctx.names, head)) {\n const bound = ctx.names[head];\n if (bound instanceof Held) return { ok: false, error: bound.error };\n }\n const found = rt.resolve(ctx, path);\n if (!found.ok) return fail(found.code, found.reason);\n const value = valueOfThing(found.thing);\n if (value instanceof Held) return { ok: false, error: value.error };\n if (missing !== undefined && missing(value)) return fail(\"#N/A\", \"The path reaches no value.\");\n return ok(value);\n };\n }),\n\n \"formula.record\": compiled(({ value }) => {\n const fields = partsOf(value);\n const keys = Object.keys(fields);\n const codes = keys.map((key) => (fields[key] as CompiledPart).code);\n return (ctx, rt) => {\n const out: Record<string, unknown> = {};\n for (let index = 0; index < keys.length; index += 1) {\n const result = (codes[index] as Code)(ctx, rt);\n if (!result.ok) {\n if (omit !== undefined && omit(result.error)) continue;\n return result;\n }\n setOwn(out, keys[index] as string, result.value);\n }\n return ok(out);\n };\n }),\n\n \"formula.list\": compiled(({ parts }) => (ctx, rt) => {\n const out = new Array<unknown>(parts.length);\n for (let index = 0; index < parts.length; index += 1) {\n const result = (parts[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n out[index] = result.value;\n }\n return ok(out);\n }),\n\n \"formula.let\": compiled(({ value }) => {\n const record = partsOf(value);\n const bindings = Object.entries(partsOf(record[\"bind\"]));\n const body = record[\"body\"] as CompiledPart;\n return (ctx, rt) => {\n const names: Record<string, unknown> = { ...ctx.names };\n for (const [name, part] of bindings) {\n const result = part.code(ctx, rt);\n setOwn(names, name, result.ok ? result.value : new Held(result.error));\n }\n return body.code({ ...ctx, names }, rt);\n };\n }),\n\n \"formula.fn\": compiled(({ value, data }) => {\n const params = isRecord(data) ? data[\"params\"] : undefined;\n if (!Array.isArray(params) || !params.every((param) => typeof param === \"string\") || new Set(params).size !== params.length) {\n const bad = fail(\"#VALUE!\", \"The params of fn are a list of different texts.\");\n return () => bad;\n }\n const names = params as readonly string[];\n const body = partsOf(value)[\"body\"] as CompiledPart;\n return (ctx, rt) => {\n const closure = (...args: readonly unknown[]): unknown => {\n const scope: Record<string, unknown> = { ...ctx.names };\n names.forEach((name, index) => setOwn(scope, name, args[index]));\n const result = body.code({ ...ctx, names: scope }, rt);\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n };\n Object.defineProperty(closure, CLOSURE, { value: { params: names } });\n return ok(closure);\n };\n }),\n\n \"formula.call\": compiled(({ value }) => {\n const record = partsOf(value);\n const fnPart = record[\"fn\"] as CompiledPart;\n const args = Array.isArray(record[\"args\"]) ? (record[\"args\"] as unknown as readonly CompiledPart[]) : [];\n return (ctx, rt) => {\n const fn = fnPart.code(ctx, rt);\n if (!fn.ok) return fn;\n if (typeof fn.value !== \"function\") return fail(\"#VALUE!\", \"The fn of call must give a function.\");\n const values = new Array<unknown>(args.length);\n for (let index = 0; index < args.length; index += 1) {\n const result = (args[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n values[index] = result.value;\n }\n try {\n return ok((fn.value as (...items: unknown[]) => unknown)(...values));\n } catch (error) {\n return thrown(error, \"the function of call\");\n }\n };\n }),\n\n \"formula.if\": compiled(({ value }) => {\n const record = partsOf(value);\n const test = record[\"test\"] as CompiledPart;\n const then = record[\"then\"] as CompiledPart;\n const other = record[\"else\"];\n return (ctx, rt) => {\n const chosen = test.code(ctx, rt);\n if (!chosen.ok) return chosen;\n const truth = truthy(chosen.value);\n if (truth === undefined) return notTruth(\"test of if\");\n if (truth) return then.code(ctx, rt);\n return other === undefined ? otherwise : other.code(ctx, rt);\n };\n }),\n\n \"formula.and\": compiled(({ parts }) => (ctx, rt) => {\n let last: Result = ok(true);\n for (const part of parts) {\n last = part.code(ctx, rt);\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return notTruth(\"term of and\");\n if (!truth) return logicValue ? last : ok(false);\n }\n return logicValue ? last : ok(true);\n }),\n\n \"formula.or\": compiled(({ parts }) => (ctx, rt) => {\n let last: Result = ok(false);\n for (const part of parts) {\n last = part.code(ctx, rt);\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return notTruth(\"term of or\");\n if (truth) return logicValue ? last : ok(true);\n }\n return logicValue ? last : ok(false);\n }),\n\n \"formula.op\": compiled(({ typePath, parts }) => {\n const name = typePath.slice(1).join(\".\");\n const lazy = profile.lazy !== undefined && Object.hasOwn(profile.lazy, name) ? profile.lazy[name] : undefined;\n if (lazy !== undefined) {\n return (ctx, rt) => {\n try {\n return lazy(parts.map((part) => () => part.code(ctx, rt)));\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n };\n }\n const fn = lookup(name) as ((...args: unknown[]) => unknown) | undefined;\n if (fn === undefined) {\n const unknown = fail(\"#NAME?\", `The language has no operation ${name}.`);\n return () => unknown;\n }\n const done = (out: unknown): Result => (check === undefined ? ok(out) : (check(out, name) ?? ok(out)));\n const failed = (error: unknown): Result => thrown(error, `the operation ${name}`);\n if (parts.length === 1) {\n const [a] = parts as readonly [CompiledPart];\n return (ctx, rt) => {\n const x = a.code(ctx, rt);\n if (!x.ok) return x;\n try {\n return done(fn(x.value));\n } catch (error) {\n return failed(error);\n }\n };\n }\n if (parts.length === 2) {\n const [a, b] = parts as readonly [CompiledPart, CompiledPart];\n return (ctx, rt) => {\n const x = a.code(ctx, rt);\n if (!x.ok) return x;\n const y = b.code(ctx, rt);\n if (!y.ok) return y;\n try {\n return done(fn(x.value, y.value));\n } catch (error) {\n return failed(error);\n }\n };\n }\n return (ctx, rt) => {\n const values = new Array<unknown>(parts.length);\n for (let index = 0; index < parts.length; index += 1) {\n const result = (parts[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n values[index] = result.value;\n }\n try {\n return done(fn(...values));\n } catch (error) {\n return failed(error);\n }\n };\n }),\n\n \"formula.ext\": compiled(({ typePath, doc }) => {\n const name = typePath.slice(1).join(\".\");\n const own = profile.ext !== undefined && Object.hasOwn(profile.ext, name) ? profile.ext[name] : undefined;\n const handler = own ?? (Object.hasOwn(STD_EXT, name) ? STD_EXT[name] : undefined);\n if (handler === undefined) {\n const unknown = fail(\"#NAME?\", `The language has no extension ${name}.`);\n return () => unknown;\n }\n return () => {\n try {\n return handler(doc.value);\n } catch (error) {\n return thrown(error, `the extension ${name}`);\n }\n };\n }),\n };\n}\n\n/**\n * This function makes a machine for a formula language. The machine has the kinds and the evaluators of the\n * formula kit. It also has the kinds, the evaluators and the walkers that the language adds.\n *\n * @param profile - The operations and the rules of the language.\n * @param more - The parts of a machine that the language adds. Its kinds win over the kinds of the kit.\n * @returns The machine.\n */\nexport function formulaMachine(profile: FormulaProfile = {}, more: Partial<Machine> = {}): Machine {\n return {\n ...more,\n world: { kinds: { ...formulaKinds(), ...more.world?.kinds }, defaults: { ...more.world?.defaults } },\n evaluators: { ...formulaEvaluators(profile), ...more.evaluators },\n };\n}\n"],"mappings":";;AAqCA,MAAa,gBAAgB;CAAC;CAAQ;CAAS;CAAQ;AAAK;;;;;;;;AAS5D,SAAgB,SAAS,O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errors.ts","../src/world.ts","../src/ladder.ts","../src/deref.ts","../src/classify.ts","../src/parts.ts","../src/evaluate.ts","../src/stdlib.ts","../src/order.ts","../src/context.ts","../src/static.ts","../src/formula.ts"],"sourcesContent":["/** A JSON value. A document is JSON. */\nexport type Json = null | boolean | number | string | readonly Json[] | { readonly [key: string]: Json };\n\n/** A JSON record. */\nexport type JsonRecord = { readonly [key: string]: Json };\n\n/** One step of a path that is a plain key: a name, or an index of a list. */\nexport type Key = string | number;\n\n/**\n * The type of a document is a reference into the world (the registry of kinds).\n *\n * - A text is a base reference with one key: `\"add\"`.\n * - A list of keys is a base reference with a path: `[\"git\", \"push\"]`.\n * - A document of type `ref` is the same reference, expanded. Its path starts at the root `world`.\n *\n * The kernel resolves a base reference itself. The expanded form is necessary only to attach more to the\n * reference. Thus the chain of types stops at a base reference.\n */\nexport type TypeRef = string | readonly Key[] | { readonly type: \"ref\"; readonly value: readonly Json[] };\n\n/**\n * A typed document: an envelope with a header and a value. The header names the type of the value. The value is\n * not changed by the envelope at any time. Thus any JSON value can have a type: a number, a list, a text or a record.\n */\nexport type Envelope = {\n /** The type: a reference to a kind of the world. */\n readonly type: TypeRef;\n /** The value. */\n readonly value: Json;\n /** The name of a binding. A sequence gives the result of this document to the later steps under this name. */\n readonly name?: string;\n /** The own entries: one evaluator name for each verb. An own entry changes only this document. */\n readonly own?: Readonly<Record<string, string>>;\n};\n\n/** The keys that an envelope can have. */\nexport const ENVELOPE_KEYS = [\"type\", \"value\", \"name\", \"own\"] as const;\n\n/**\n * This function tells if a value is a plain record: an object with the prototype of a plain object, or with no\n * prototype. A list, `null`, a date, a map and an instance of a class are not plain records.\n *\n * @param value - The value to examine.\n * @returns `true` for a plain record.\n */\nexport function isRecord(value: unknown): value is JsonRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * This function reads a field of a record. It reads only the own fields, thus `constructor` is not a field.\n *\n * @param record - The record.\n * @param key - The name of the field.\n * @returns The value of the field, or `undefined` when the record has no such field.\n */\nexport function field(record: JsonRecord, key: string): Json | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\n/**\n * This function tells if a value is a key of a path: a text, or a whole number from 0.\n *\n * @param value - The value to examine.\n * @returns `true` for a key.\n */\nexport function isKey(value: unknown): value is Key {\n return typeof value === \"string\" || (typeof value === \"number\" && Number.isInteger(value) && value >= 0);\n}\n\n/**\n * This function tells if a value is a reference to a type. The reference is a text, a list of keys, or a document\n * of type `ref` whose path starts at the root `world`.\n *\n * @param value - The value to examine.\n * @returns `true` for a reference to a type.\n */\nexport function isTypeRef(value: unknown): value is TypeRef {\n if (typeof value === \"string\") return value !== \"\";\n if (Array.isArray(value)) return value.length > 0 && (value as readonly unknown[]).every(isKey);\n if (!isRecord(value)) return false;\n const path = field(value, \"value\");\n return field(value, \"type\") === \"ref\" && Array.isArray(path) && (path as readonly Json[])[0] === \"world\";\n}\n\n/**\n * This function gives the path of a reference to a type, from the root of the world.\n *\n * @param type - The reference.\n * @returns The keys from the root of the world, or `undefined` for a computed step that has no fixed key.\n */\nexport function typePath(type: TypeRef): readonly Key[] | undefined {\n if (typeof type === \"string\") return [type];\n if (Array.isArray(type)) return type as readonly Key[];\n const steps = (type as { readonly value: readonly Json[] }).value.slice(1);\n return steps.every(isKey) ? (steps as readonly Key[]) : undefined;\n}\n\n/**\n * This function gives the text of a type for a reader: its keys, joined with a dot.\n *\n * @param type - The reference to the type.\n * @returns The text, for example `git.push`.\n */\nexport function typeName(type: TypeRef): string {\n if (typeof type === \"string\") return type;\n return typePath(type)?.join(\".\") ?? \"(computed)\";\n}\n\nfunction headerFits(value: JsonRecord): boolean {\n if (!isTypeRef(field(value, \"type\")) || !Object.hasOwn(value, \"value\")) return false;\n const name = field(value, \"name\");\n if (name !== undefined && typeof name !== \"string\") return false;\n const own = field(value, \"own\");\n return own === undefined || isRecord(own);\n}\n\n/**\n * This function tells if a value has the form of an envelope. That form is a record with a reference to a type\n * and a `value`. It has no other keys than the keys of an envelope. A contract decides where an envelope is\n * expected. This function only checks the form.\n *\n * @param value - The value to examine.\n * @returns `true` when the value has the form of an envelope.\n */\nexport function isEnvelope(value: unknown): value is JsonRecord & Envelope {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n // The keys come first: most values that are not envelopes have another key, thus the check stops early.\n for (const key in value) {\n if (key !== \"type\" && key !== \"value\" && key !== \"name\" && key !== \"own\" && Object.hasOwn(value, key)) return false;\n }\n return isRecord(value) && headerFits(value);\n}\n\n/** A stored document: an envelope, and the keys of its store beside it, for example `_id`. */\nexport interface Stored {\n readonly envelope: Envelope;\n /** The keys of the store, with their values. */\n readonly header: Readonly<Record<string, Json>>;\n}\n\n/**\n * This function reads a stored document: an envelope that also has the keys of a store, for example `{ _id, type,\n * value }`. Only the keys in the list can be beside the keys of the envelope.\n *\n * @param value - The value to examine.\n * @param header - The keys of the store that the document can have.\n * @returns The envelope and the keys of the store, or `undefined` when the value has another form.\n */\nexport function stored(value: unknown, header: readonly string[]): Stored | undefined {\n if (!isRecord(value) || !headerFits(value)) return undefined;\n const keys: Record<string, Json> = {};\n const own: Record<string, Json> = {};\n for (const key in value) {\n if (!Object.hasOwn(value, key)) continue;\n if ((ENVELOPE_KEYS as readonly string[]).includes(key)) own[key] = value[key] as Json;\n else if (header.includes(key)) keys[key] = value[key] as Json;\n else return undefined;\n }\n return { envelope: fromJson(own) as Envelope, header: keys };\n}\n\n/**\n * This function makes an envelope.\n *\n * @param type - The reference to the kind.\n * @param value - The value.\n * @param header - The optional name and own entries.\n * @returns The envelope.\n */\nexport function typed(type: TypeRef, value: Json, header: { readonly name?: string; readonly own?: Record<string, string> } = {}): Envelope {\n return { type, value, ...(header.name === undefined ? {} : { name: header.name }), ...(header.own === undefined ? {} : { own: header.own }) };\n}\n\n/**\n * This function makes a reference document: a path from a root of the context.\n *\n * @param path - The steps. The first step is a root: `self`, `names`, `world`, `event` or `caps`.\n * @returns The document of type `ref`.\n */\nexport function ref(...path: readonly Json[]): Envelope {\n return typed(\"ref\", path);\n}\n\n/**\n * This function gives an envelope as a JSON record, for a store or for a view.\n *\n * @param doc - The envelope.\n * @returns The same envelope as JSON.\n */\nexport function toJson(doc: Envelope): JsonRecord {\n return {\n type: doc.type as Json,\n value: doc.value,\n ...(doc.name === undefined ? {} : { name: doc.name }),\n ...(doc.own === undefined ? {} : { own: doc.own }),\n };\n}\n\n/**\n * This function reads an envelope from JSON. A value without the form of an envelope gives `undefined`.\n *\n * @param value - The JSON value.\n * @returns The envelope, or `undefined`.\n */\nexport function fromJson(value: unknown): Envelope | undefined {\n if (!isEnvelope(value)) return undefined;\n const own = field(value, \"own\");\n const ownEntries: Record<string, string> = {};\n if (isRecord(own)) {\n for (const [verb, name] of Object.entries(own)) if (typeof name === \"string\") ownEntries[verb] = name;\n }\n const name = field(value, \"name\");\n return typed(field(value, \"type\") as TypeRef, field(value, \"value\") ?? null, {\n ...(typeof name === \"string\" ? { name } : {}),\n ...(isRecord(own) ? { own: ownEntries } : {}),\n });\n}\n\n/**\n * This function tells if two JSON values are equal. Equal values have the same texts, numbers and truth values,\n * the same items in the same order, and the same fields. The order of the fields does not matter. It does not use the stack for the\n * depth, thus a deep document cannot overflow it.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @returns `true` when the values are equal.\n */\nexport function docEquals(a: unknown, b: unknown): boolean {\n const stack: [unknown, unknown][] = [[a, b]];\n while (stack.length > 0) {\n const [x, y] = stack.pop() as [unknown, unknown];\n if (Object.is(x, y)) continue;\n if (typeof x !== \"object\" || typeof y !== \"object\" || x === null || y === null) return false;\n if (Array.isArray(x) !== Array.isArray(y)) return false;\n if (Array.isArray(x)) {\n const ys = y as readonly unknown[];\n if (x.length !== ys.length) return false;\n for (let index = 0; index < x.length; index += 1) stack.push([x[index], ys[index]]);\n continue;\n }\n const xr = x as Readonly<Record<string, unknown>>;\n const yr = y as Readonly<Record<string, unknown>>;\n const keys = Object.keys(xr);\n if (keys.length !== Object.keys(yr).length) return false;\n for (const key of keys) {\n if (!Object.hasOwn(yr, key)) return false;\n stack.push([xr[key], yr[key]]);\n }\n }\n return true;\n}\n","import type { Key } from \"./doc.ts\";\n\n/** The codes that the kernel gives. */\nexport type KernelCode =\n | \"#KIND?\"\n | \"#NOEVAL\"\n | \"#PART?\"\n | \"#NAME?\"\n | \"#REF!\"\n | \"#N/A\"\n | \"#CYCLE!\"\n | \"#STEP?\"\n | \"#VALUE!\"\n | \"#NUM!\"\n | \"#ARGS\"\n | \"#CAP!\"\n | \"#CALC!\"\n | \"#DEPTH!\"\n | \"#ABORT\";\n\n/** The code of an error value. A language can add its own codes. Each code starts with `#`. */\nexport type ErrorCode = KernelCode | `#${string}`;\n\n/**\n * An error value: a code and a reason. An evaluation gives an error value, and it does not throw.\n *\n * - `place`: the keys from the root document to the document that failed.\n * - `cause`: the error of the host that caused this error, for example the exception of an effect.\n */\nexport interface EvalError {\n readonly code: ErrorCode;\n readonly reason: string;\n readonly place?: readonly Key[];\n readonly cause?: unknown;\n}\n\n/** The result of an evaluation: a value, or an error value. A value can be any value of the host. */\nexport type Result<V = unknown> = { readonly ok: true; readonly value: V } | { readonly ok: false; readonly error: EvalError };\n\n/** A result with an error value. */\nexport type Failed = { readonly ok: false; readonly error: EvalError };\n\n/**\n * This function makes a result with a value.\n *\n * @param value - The value.\n * @returns The result.\n */\nexport function ok<V>(value: V): Result<V> {\n return { ok: true, value };\n}\n\n/**\n * This function makes a result with an error value.\n *\n * @param code - The code of the error.\n * @param reason - One sentence that tells the cause.\n * @param more - The place and the cause of the error, when they are known.\n * @returns The result.\n */\nexport function fail(code: ErrorCode, reason: string, more: { readonly place?: readonly Key[]; readonly cause?: unknown } = {}): Failed {\n return {\n ok: false,\n error: { code, reason, ...(more.place === undefined ? {} : { place: more.place }), ...(more.cause === undefined ? {} : { cause: more.cause }) },\n };\n}\n\n/**\n * This function gives a failed result its place, when it has none. A result with a value, or an error with a\n * place, stays the same object.\n *\n * @param result - The result.\n * @param place - The keys from the root document to the document that failed.\n * @returns The result with a place.\n */\nexport function placed<V>(result: Result<V>, place: readonly Key[]): Result<V> {\n if (result.ok || result.error.place !== undefined) return result;\n return { ok: false, error: { ...result.error, place } };\n}\n\n/**\n * An exception that carries an error value through code of the host. A closure of a formula throws it when the\n * host calls the closure and the closure fails. The kernel catches it and gives its error value again.\n */\nexport class Failure extends Error {\n readonly error: EvalError;\n\n /**\n * This constructor makes the exception.\n *\n * @param error - The error value that the exception carries.\n */\n constructor(error: EvalError) {\n super(`${error.code} ${error.reason}`);\n this.name = \"Failure\";\n this.error = error;\n }\n}\n\n/**\n * This function tells if an exception is the overflow of the stack of the host.\n *\n * @param error - The exception.\n * @returns `true` for a stack overflow.\n */\nexport function isStackOverflow(error: unknown): boolean {\n return error instanceof RangeError && /call stack/i.test(error.message);\n}\n\n/**\n * This function changes an exception into an error value. A `Failure` gives its error value. A stack overflow\n * gives `#DEPTH!`. Each other exception gives `#CALC!`, with the exception as the cause.\n *\n * @param error - The exception.\n * @param who - A short text that names the code that threw, for example `the evaluator math.add`.\n * @returns The failed result.\n */\nexport function thrown(error: unknown, who: string): Failed {\n if (error instanceof Failure) return { ok: false, error: error.error };\n if (isStackOverflow(error)) return fail(\"#DEPTH!\", `The nesting of ${who} is too deep for the stack of the host.`, { cause: error });\n return fail(\"#CALC!\", `${upper(who)} threw: ${describe(error)}`, { cause: error });\n}\n\nfunction upper(text: string): string {\n return text.length === 0 ? text : `${text[0]?.toUpperCase() ?? \"\"}${text.slice(1)}`;\n}\n\n/**\n * This function gives a short text for an exception or any value. It does not throw.\n *\n * @param value - The value.\n * @returns The text.\n */\nexport function describe(value: unknown): string {\n try {\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n return String(value);\n } catch {\n return \"(a value without a text)\";\n }\n}\n","import { type Envelope, type Json, type Key, type TypeRef, field, isRecord, typePath } from \"./doc.ts\";\nimport type { Cap } from \"./deref.ts\";\n\n/** The two sides of evaluation. `derive` is pure. `run` causes effects in order. */\nexport type Side = \"derive\" | \"run\";\n\n/**\n * Where the parts of a value are: the shape of the value. A part is a typed document that the evaluator gets\n * sealed. `of` is the type of a bare part: a part without an envelope gets this type from its position.\n *\n * - `none`: the value is data. It has no parts.\n * - `term`: the value itself is one part.\n * - `list`: the value is a list. Each item has the shape `item` (the default is a part).\n * - `map`: the value is a record. Each field has the shape `item` (the default is a part).\n * - `record`: the value is a record. Each named field has its shape. A list of names makes each named field a\n * part. The other fields have the shape `rest` (the default is data). `required` names the fields that must be.\n * - `deep`: each envelope at any depth of the value is a part, and the rest is data.\n * - `text`, `number` and `one`: the value is data of that type. `one` names the values that it permits.\n *\n * A `term` with `address: true` is an address: a reference there gives what its path reaches, not the value. A\n * `term` with `kinds` permits only a part whose type starts with one of the paths. A `record` with `closed: true`\n * permits only its named fields. A `list` with `distinct: true` permits no two equal items.\n */\nexport type Shape =\n | { readonly shape: \"none\" }\n | { readonly shape: \"term\"; readonly of?: string; readonly address?: boolean; readonly kinds?: readonly (readonly Key[])[] }\n | { readonly shape: \"list\"; readonly of?: string; readonly item?: Shape; readonly distinct?: boolean }\n | { readonly shape: \"map\"; readonly of?: string; readonly item?: Shape }\n | {\n readonly shape: \"record\";\n readonly fields: readonly string[] | Readonly<Record<string, Shape>>;\n readonly of?: string;\n readonly required?: readonly string[];\n readonly rest?: Shape;\n readonly closed?: boolean;\n }\n | { readonly shape: \"deep\"; readonly of?: string }\n | { readonly shape: \"text\" }\n | { readonly shape: \"number\"; readonly whole?: boolean; readonly min?: number; readonly max?: number }\n | { readonly shape: \"one\"; readonly values: readonly Json[] };\n\n/** The former name of `Shape`. */\nexport type PartsSpec = Shape;\n\n/**\n * Where the names of a scope rule come from.\n *\n * - `fixed`: the names in the list.\n * - `keysAt`: the keys of the record at this path of the value, for example the bindings of a `let`.\n * - `listAt`: the texts of the list at this path of the value, for example the parameters of a `fn`.\n * - `textAt`: the text at this path of the value, or `otherwise` when the value has no text there.\n * - `headers`: the binding name (`name`) of each part that the rule covers.\n */\nexport type NamesSource =\n | { readonly fixed: readonly string[] }\n | { readonly keysAt: readonly Key[] }\n | { readonly listAt: readonly Key[] }\n | { readonly textAt: readonly Key[]; readonly otherwise?: string }\n | { readonly headers: true };\n\n/**\n * A scope rule of a kind: names that the kind binds, and the parts that see them. The static kit reads the rules,\n * and the evaluator of the kind binds the same names when it evaluates the parts.\n */\nexport interface ScopeRule {\n readonly names: NamesSource;\n /** The parts that see the names, as patterns of their paths in the value. The key `\"*\"` matches each key. */\n readonly in: readonly (readonly Key[])[];\n /** `true`: a part sees only the names of the parts before it, as in a sequence. */\n readonly sequential?: boolean;\n}\n\n/**\n * A capability rule of a kind: what the kind gives some of its parts from the capabilities of its document. A rule\n * only narrows. A part does not get a capability that its document does not have (CAP.NARROW).\n *\n * - `same`: the parts get the capabilities of the document. This is the default.\n * - `mask`: the parts get no capabilities, as the part of `pure`.\n * - `only`: the parts get only the effects that the capabilities of the document and the list `caps` both permit.\n *\n * `in` names the parts that the rule covers, as patterns of their paths in the value. The key `\"*\"` matches each\n * key. A rule without `in` covers each part.\n */\nexport type CapsRule =\n | { readonly rule: \"same\"; readonly in?: readonly (readonly Key[])[] }\n | { readonly rule: \"mask\"; readonly in?: readonly (readonly Key[])[] }\n | { readonly rule: \"only\"; readonly caps: readonly Cap[]; readonly in?: readonly (readonly Key[])[] };\n\n/** A kind gives the name of an evaluator for each verb, and the contract of its value. */\nexport interface Kind {\n readonly verbs: Readonly<Record<string, string>>;\n /** Where the parts of the value are. The default is `none`. */\n readonly parts?: Shape;\n /** The names that the kind binds for its parts. */\n readonly scope?: readonly ScopeRule[];\n /**\n * The capabilities that the kind gives its parts, as rules. A part that no rule covers gets the capabilities of\n * the document. A part that several rules cover gets only what each rule permits. The static kit reads the rules,\n * and the kernel narrows the context of each part by them. Thus an evaluator does not narrow the capabilities\n * itself.\n */\n readonly caps?: readonly CapsRule[];\n /** The side of the kind. A kind of the run side causes effects. The default is `derive`. */\n readonly side?: Side;\n /**\n * The effects that a document of this kind can cause. It is a list of the kinds of the effects. The text\n * `\"type\"` means that the kind of the effect is the type of the document itself, as for a call.\n */\n readonly effects?: \"type\" | readonly string[];\n /** One sentence that tells what the kind is. */\n readonly summary?: string;\n}\n\n/** A namespace: a group of entries under one key of the world. `fallback` is the kind of each other key in it. */\nexport interface Namespace {\n readonly kinds: Readonly<Record<string, WorldEntry>>;\n readonly fallback?: Kind;\n}\n\n/** An alias: a reference to another entry of the world. The lookup follows it (collapse). */\nexport type Alias = { readonly type: \"ref\"; readonly value: readonly Json[] };\n\n/** One entry of the world: a kind, a namespace, or an alias. */\nexport type WorldEntry = Kind | Namespace | Alias;\n\n/**\n * A world holds the kinds and the defaults that answer the questions. `fallback` is the kind of each first key that\n * the world does not have. A world with a fallback is open: each path that starts with an unknown key names a kind.\n */\nexport interface World {\n readonly kinds: Readonly<Record<string, WorldEntry>>;\n readonly defaults: Readonly<Record<string, string>>;\n readonly fallback?: Kind;\n}\n\n/** The result of a lookup of a type in the world. */\nexport type Lookup =\n | { readonly ok: true; readonly kind: Kind; readonly path: readonly Key[]; readonly aliases: number }\n | { readonly ok: false; readonly reason: \"unknown\" | \"cycle\" | \"not-a-kind\" | \"computed\"; readonly path: readonly Key[] };\n\n/**\n * This function tells if an entry of the world is a kind.\n *\n * @param entry - The entry.\n * @returns `true` for a kind.\n */\nexport function isKind(entry: WorldEntry | undefined): entry is Kind {\n return entry !== undefined && Object.hasOwn(entry, \"verbs\");\n}\n\n/**\n * This function tells if an entry of the world is an alias.\n *\n * @param entry - The entry.\n * @returns `true` for an alias.\n */\nexport function isAlias(entry: WorldEntry | undefined): entry is Alias {\n return entry !== undefined && (entry as { type?: unknown }).type === \"ref\" && Array.isArray((entry as { value?: unknown }).value);\n}\n\n/**\n * This function tells if an entry of the world is a namespace.\n *\n * @param entry - The entry.\n * @returns `true` for a namespace.\n */\nexport function isNamespace(entry: WorldEntry | undefined): entry is Namespace {\n return entry !== undefined && !isKind(entry) && !isAlias(entry) && Object.hasOwn(entry, \"kinds\");\n}\n\nfunction entryAt(entries: Readonly<Record<string, WorldEntry>>, key: Key): WorldEntry | undefined {\n const name = String(key);\n return Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * This function finds the kind that a type names. It walks the path from the root of the world, one key at a\n * time. An alias on the way is followed until a kind answers (collapse). A cycle of aliases stops the lookup. In a\n * namespace with a fallback, a key that the namespace does not have gets the fallback kind. In an open world, a first\n * key that the world does not have gets the fallback kind of the world.\n *\n * @param world - The world.\n * @param type - The reference to the type.\n * @returns The kind and the path of the kind after each alias, or the reason of a failure.\n */\nexport function lookupKind(world: World, type: TypeRef): Lookup {\n const start = typePath(type);\n if (start === undefined) return { ok: false, reason: \"computed\", path: [] };\n let path: readonly Key[] = start;\n let aliases = 0;\n for (;;) {\n let entries = world.kinds;\n let fallback: Kind | undefined = world.fallback;\n let entry: WorldEntry | undefined;\n let followed = false;\n for (let index = 0; index < path.length; index += 1) {\n const key = path[index] as Key;\n entry = entryAt(entries, key);\n if (entry === undefined) {\n if (fallback !== undefined) return { ok: true, kind: fallback, path, aliases };\n return { ok: false, reason: \"unknown\", path };\n }\n if (isAlias(entry)) {\n aliases += 1;\n if (aliases > 32) return { ok: false, reason: \"cycle\", path };\n const target = entry.value.slice(1);\n if (entry.value[0] !== \"world\" || !target.every((item) => typeof item === \"string\" || typeof item === \"number\")) {\n return { ok: false, reason: \"not-a-kind\", path };\n }\n path = [...(target as readonly Key[]), ...path.slice(index + 1)];\n followed = true;\n break;\n }\n if (index < path.length - 1) {\n if (!isNamespace(entry)) return { ok: false, reason: \"not-a-kind\", path };\n entries = entry.kinds;\n fallback = entry.fallback;\n }\n }\n if (followed) continue;\n if (!isKind(entry)) return { ok: false, reason: \"not-a-kind\", path };\n return { ok: true, kind: entry, path, aliases };\n }\n}\n\n/**\n * This function gives the entries of a world as a JSON record, so that a reference can walk it. A kind is a\n * record with its verbs, an alias is a reference document, and a namespace is a record of its entries.\n *\n * @param entries - The entries.\n * @returns The JSON form.\n */\nexport function entriesAsJson(entries: Readonly<Record<string, WorldEntry>>): Json {\n const out: Record<string, Json> = {};\n for (const [key, entry] of Object.entries(entries)) {\n if (isAlias(entry)) out[key] = { type: \"ref\", value: entry.value };\n else if (isKind(entry)) out[key] = JSON.parse(JSON.stringify(entry)) as Json;\n else out[key] = entriesAsJson((entry as Namespace).kinds);\n }\n return out;\n}\n\nfunction describeShape(shape: Shape | undefined): Json {\n if (shape === undefined || shape.shape === \"none\") return \"none\";\n if (shape.shape === \"text\") return \"a text\";\n if (shape.shape === \"number\") return \"a number\";\n if (shape.shape === \"one\") return `one of ${JSON.stringify(shape.values)}`;\n if (shape.shape === \"term\") return `a part${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n if (shape.shape === \"deep\") return \"each document in the value\";\n if (shape.shape === \"list\") return `a list${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n if (shape.shape === \"map\") return `a record of parts${shape.of === undefined ? \"\" : ` of ${shape.of}`}`;\n const names = Array.isArray(shape.fields) ? shape.fields : Object.keys(shape.fields);\n return `the fields ${names.join(\", \")}`;\n}\n\n/**\n * This function makes the document of a kind, so that a view can draw it as each other document.\n *\n * @param name - The name of the kind.\n * @param kind - The kind.\n * @returns The document of type `kind`.\n */\nexport function kindDocument(name: string, kind: Kind): Envelope {\n return {\n type: \"kind\",\n value: { name, verbs: { ...kind.verbs }, parts: describeShape(kind.parts), side: kind.side ?? \"derive\", summary: kind.summary ?? \"\" },\n };\n}\n\n/**\n * This function tells if a JSON value is the record of a kind.\n *\n * @param value - The value.\n * @returns `true` when the value has verbs.\n */\nexport function looksLikeKind(value: unknown): boolean {\n return isRecord(value) && isRecord(field(value, \"verbs\"));\n}\n","import { type TypeRef, typeName } from \"./doc.ts\";\nimport { type Kind, type World, lookupKind } from \"./world.ts\";\n\nexport type { Kind, Namespace, PartsSpec, Side, World, WorldEntry } from \"./world.ts\";\n\n/** The rungs of the ladder, in the order that a question visits them. */\nexport const RUNGS = [\"own\", \"kind\", \"default\"] as const;\n\n/** One rung of the ladder. */\nexport type Rung = (typeof RUNGS)[number];\n\n/** The place where the ladder found the type. */\nexport type KindSource = \"document\" | \"container\";\n\n/**\n * The outcome of one rung.\n *\n * - `answers`: the rung gives an evaluator.\n * - `no-entry`: the rung has nothing for this verb, thus the question goes to the next rung.\n * - `skipped`: the rung does not apply, because no type is known.\n * - `unknown-kind`: the type is not a kind of the world. The question stops.\n */\nexport type Outcome = \"answers\" | \"no-entry\" | \"skipped\" | \"unknown-kind\";\n\n/** The record of one rung that a question visited. */\nexport interface Step {\n readonly rung: Rung;\n readonly outcome: Outcome;\n /** The evaluator, when the outcome is `answers`. */\n readonly evaluator?: string;\n /** The text of the type, at the kind rung. */\n readonly kind?: string;\n /** The place of the type, at the kind rung. */\n readonly source?: KindSource;\n}\n\n/** The answer to a question. It keeps the record of each rung that the question visited. */\nexport interface Answer {\n readonly verb: string;\n /** The evaluator that answers. A question that stops with an error has no evaluator. */\n readonly evaluator?: string;\n /** The rung that answered. */\n readonly rung?: Rung;\n /** The reason when no rung answers. */\n readonly error?: \"unknown-kind\" | \"no-answer\";\n readonly steps: readonly Step[];\n}\n\n/**\n * The header that the ladder reads: the type and the own entries. An envelope is a header. A bare value has an\n * empty header, and its position can declare its type.\n */\nexport interface Header {\n readonly type?: TypeRef;\n readonly own?: Readonly<Record<string, string>>;\n}\n\n/** The options of a question. */\nexport interface AskOptions {\n /** The type that the position of a bare value declares. The type of an envelope wins. */\n readonly declaredType?: string;\n}\n\nfunction entryOf(verbs: Readonly<Record<string, string>> | undefined, verb: string): string | undefined {\n return verbs !== undefined && Object.hasOwn(verbs, verb) ? verbs[verb] : undefined;\n}\n\n/**\n * This function finds the kind that a type names, and follows each alias. It gives `undefined` for an unknown\n * type.\n *\n * @param world - The world.\n * @param type - The reference to the type.\n * @returns The kind, or `undefined`.\n */\nexport function kindOf(world: World, type: TypeRef): Kind | undefined {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : undefined;\n}\n\n/**\n * This function finds a kind by a text type. It is the same as `kindOf` for a one-key reference.\n *\n * @param world - The world.\n * @param name - The text of the type.\n * @returns The kind, or `undefined`.\n */\nexport function kindNamed(world: World, name: TypeRef): Kind | undefined {\n return kindOf(world, name);\n}\n\n/**\n * This function asks a document a question, and gives the evaluator that answers it.\n *\n * The question visits the rungs in order: the own entry of the envelope, then its kind, then the default of the\n * world. The type comes from the envelope, or else from the type that the position declares. The type is a\n * reference into the world. The ladder does not guess a type from the shape of a value.\n *\n * @param world - The kinds and the defaults.\n * @param doc - The header of the document: an envelope, or `{}` for a bare value.\n * @param verb - The verb of the question, for example `eval` or `view`.\n * @param options - The type that the position declares.\n * @returns The answer, with the record of each rung that the question visited.\n */\nexport function ask(world: World, doc: Header, verb: string, options: AskOptions = {}): Answer {\n const steps: Step[] = [];\n\n const own = entryOf(doc.own, verb);\n if (own !== undefined) {\n steps.push({ rung: \"own\", outcome: \"answers\", evaluator: own });\n return { verb, evaluator: own, rung: \"own\", steps };\n }\n steps.push({ rung: \"own\", outcome: \"no-entry\" });\n\n const type: TypeRef | undefined = doc.type ?? options.declaredType;\n if (type === undefined) {\n steps.push({ rung: \"kind\", outcome: \"skipped\" });\n } else {\n const source: KindSource = doc.type === undefined ? \"container\" : \"document\";\n const name = typeName(type);\n const kind = kindOf(world, type);\n if (kind === undefined) {\n steps.push({ rung: \"kind\", outcome: \"unknown-kind\", kind: name, source });\n return { verb, error: \"unknown-kind\", steps };\n }\n const entry = entryOf(kind.verbs, verb);\n if (entry !== undefined) {\n steps.push({ rung: \"kind\", outcome: \"answers\", evaluator: entry, kind: name, source });\n return { verb, evaluator: entry, rung: \"kind\", steps };\n }\n steps.push({ rung: \"kind\", outcome: \"no-entry\", kind: name, source });\n }\n\n const fallback = entryOf(world.defaults, verb);\n if (fallback !== undefined) {\n steps.push({ rung: \"default\", outcome: \"answers\", evaluator: fallback });\n return { verb, evaluator: fallback, rung: \"default\", steps };\n }\n steps.push({ rung: \"default\", outcome: \"no-entry\" });\n return { verb, error: \"no-answer\", steps };\n}\n","import { type Envelope, type Json, type JsonRecord, type Key, type TypeRef, field, isEnvelope, isKey, isRecord, typePath } from \"./doc.ts\";\nimport { type World, entriesAsJson, lookupKind } from \"./world.ts\";\nimport type { ErrorCode } from \"./errors.ts\";\n\n/**\n * The brand of a host thing: an object of the host that answers the steps of a path itself. The brand is a\n * global symbol, thus two copies of the kernel in one program know the things of each other.\n */\nexport const THING: unique symbol = Symbol.for(\"coeval.thing\") as never;\n\n/**\n * A host thing: an object that answers the steps of a path itself, for example a node of a live tree. It is the\n * own entry of the ladder for the verb `deref`.\n */\nexport interface HostThing {\n readonly [THING]: true;\n /** A short text for a reader, for example `node card`. */\n readonly label: string;\n /**\n * This function answers one step.\n *\n * @param key - The key of the step.\n * @returns What the step reaches, or `undefined` when it reaches nothing.\n */\n deref(key: Key): Thing | undefined;\n /**\n * This function gives the thing as a value, when a reference ends on it.\n *\n * @returns The value.\n */\n toJson(): unknown;\n /**\n * This optional function answers all the steps of a path that are keys, in one call. A store uses it to read a\n * path without one call for each step.\n *\n * @param keys - The keys.\n * @returns What the keys reach, or `undefined` when they reach nothing.\n */\n resolve?(keys: readonly Key[]): { readonly thing: Thing } | undefined;\n}\n\n/** Something that a path can reach: any value of the host, or a host thing. */\nexport type Thing = unknown;\n\n/**\n * This function tells if a thing is a host thing.\n *\n * @param thing - The thing.\n * @returns `true` for a host thing.\n */\nexport function isHostThing(thing: unknown): thing is HostThing {\n return typeof thing === \"object\" && thing !== null && (thing as Partial<HostThing>)[THING] === true;\n}\n\n/** The roots of a context. Each path starts with one of them. */\nexport const ROOTS = [\"self\", \"names\", \"world\", \"event\", \"caps\"] as const;\n\n/** One root of a context. */\nexport type Root = (typeof ROOTS)[number];\n\n/**\n * A capability: the name of a kind of effect, or its keys. A capability permits its kind and each kind under it.\n * Keys are necessary when a key has a dot in it.\n */\nexport type Cap = string | readonly Key[];\n\n/**\n * The context of a term: a record with five roots. A reference reaches outside its term only through them.\n *\n * - `self`: the node that the term is part of.\n * - `names`: the values that the evaluators around the term bound.\n * - `world`: the registry of kinds.\n * - `event`: the event that started a run.\n * - `caps`: the effects that the term can cause.\n */\nexport interface Context {\n readonly self: Thing;\n readonly names: Readonly<Record<string, unknown>>;\n readonly world: Thing;\n readonly event: Thing;\n readonly caps: readonly Cap[];\n}\n\n/** The code of a `deref` evaluator: it answers one step of a path on a document of its kind. */\nexport type DerefCode = (doc: Envelope, key: Key) => Thing | undefined;\n\n/**\n * The result of a step document: what it reached, or the reason of a failure. A failure can give its code, for\n * example `#REF!` for a position outside a space. The default code is `#N/A`.\n */\nexport type WalkResult = { readonly ok: true; readonly thing: Thing } | { readonly ok: false; readonly reason: string; readonly code?: ErrorCode };\n\n/** The input of a walker: the code of a step document, for example `nearest`. */\nexport interface WalkInput {\n /** The value of the step document. */\n readonly data: Json;\n /** The thing that the path reached before this step. */\n readonly here: Thing;\n readonly context: Context;\n /**\n * This function answers one step on a thing, through the ladder.\n *\n * @param thing - The thing.\n * @param key - The key.\n * @returns What the step reaches, or `undefined`.\n */\n deref(thing: Thing, key: Key): Thing | undefined;\n}\n\n/** A walker: the code of the verb `step` of a kind of step documents. */\nexport type Walker = (input: WalkInput) => WalkResult;\n\n/**\n * What a resolution needs: the world, and the code of the `deref` evaluators and of the walkers.\n *\n * - `plain`: `true` when the values are data. Then a step does not ask the kind of an envelope, and a reference\n * that a step reaches stays a value (no collapse).\n * - `roots`: the roots that a path can start at. The default is each root.\n * - `adopt`: the thing of each value that a path reaches. A host gives its own values a host thing with this\n * function, for example a value whose fields read through signals. A host thing is not followed as a reference.\n */\nexport interface Navigator {\n readonly world: World;\n readonly derefs?: Readonly<Record<string, DerefCode>>;\n readonly walkers?: Readonly<Record<string, Walker>>;\n readonly plain?: boolean;\n readonly roots?: readonly Root[];\n readonly adopt?: (value: unknown) => Thing;\n}\n\n/** The way that one hop of a path was answered. */\nexport type HopBy = \"root\" | \"own\" | \"kind\" | \"default\" | \"step\" | \"collapse\";\n\n/** One hop of a path: the step, what it reached, and who answered it. */\nexport interface Hop {\n readonly step: Json;\n readonly thing: Thing;\n readonly by: HopBy;\n}\n\n/** The codes that a resolution gives itself. A walker can give another code for its failure. */\nexport type ResolveCode = \"#REF!\" | \"#NAME?\" | \"#N/A\" | \"#CYCLE!\" | \"#STEP?\";\n\n/** The result of a resolution: what the path reached, with each hop, or an error with the hops before it. */\nexport type Resolution =\n | { readonly ok: true; readonly thing: Thing; readonly hops: readonly Hop[] }\n | { readonly ok: false; readonly code: ResolveCode | ErrorCode; readonly reason: string; readonly hops: readonly Hop[] };\n\n/** The options of a resolution. */\nexport interface ResolveOptions {\n /** `false`: do not record the hops. The default is `true`. */\n readonly hops?: boolean;\n}\n\nfunction entryOf(verbs: Readonly<Record<string, string>> | undefined, verb: string): string | undefined {\n return verbs !== undefined && Object.hasOwn(verbs, verb) ? verbs[verb] : undefined;\n}\n\n/** The own fields of a value: the items and the length of a list, and the own properties of an object. */\nfunction plainStep(thing: unknown, key: Key): { readonly found: true; readonly value: unknown } | undefined {\n if (Array.isArray(thing)) {\n if (key === \"length\") return { found: true, value: thing.length };\n const index = typeof key === \"number\" ? key : /^\\d+$/.test(key) ? Number(key) : -1;\n return index >= 0 && index < thing.length ? { found: true, value: (thing as readonly unknown[])[index] } : undefined;\n }\n if (typeof thing === \"object\" && thing !== null) {\n const name = String(key);\n return Object.hasOwn(thing, name) ? { found: true, value: (thing as Readonly<Record<string, unknown>>)[name] } : undefined;\n }\n return undefined;\n}\n\n/**\n * This function answers one step of a path on a thing, through the ladder of the verb `deref`. A host thing\n * answers for itself (own). A document asks its own entry, then its kind. The default goes into the value: an own\n * field of an object, or an item of a list.\n *\n * @param nav - The world and the code of the evaluators.\n * @param thing - The thing that the path reached.\n * @param key - The key of the step.\n * @returns What the step reaches and the rung that answered, or `undefined` when it reaches nothing.\n */\nexport function derefStep(nav: Navigator, thing: Thing, key: Key): { readonly thing: Thing; readonly by: HopBy } | undefined {\n if (isHostThing(thing)) {\n const reached = thing.deref(key);\n return reached === undefined ? undefined : { thing: reached, by: \"own\" };\n }\n if (nav.plain !== true && isEnvelope(thing)) {\n const envelope = thing as JsonRecord & Envelope;\n const ownEntries = field(envelope, \"own\");\n const own = isRecord(ownEntries) ? entryOf(ownEntries as Readonly<Record<string, string>>, \"deref\") : undefined;\n const ownCode = own === undefined ? undefined : nav.derefs?.[own];\n if (ownCode !== undefined) {\n const reached = ownCode(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: \"own\" };\n }\n const found = lookupKind(nav.world, envelope.type);\n const name = found.ok ? entryOf(found.kind.verbs, \"deref\") : undefined;\n const code = name === undefined ? undefined : nav.derefs?.[name];\n if (code !== undefined) {\n const reached = code(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: \"kind\" };\n }\n const reached = plainStep(envelope.value, key);\n return reached === undefined ? undefined : { thing: reached.value, by: \"default\" };\n }\n const reached = plainStep(thing, key);\n return reached === undefined ? undefined : { thing: reached.value, by: \"default\" };\n}\n\n/**\n * This function tells if a thing is a reference document: an envelope of the type `ref` with a list for its path.\n *\n * @param thing - The thing.\n * @returns `true` for a reference document.\n */\nexport function isRef(thing: unknown): thing is Envelope & { readonly value: readonly Json[] } {\n if (!isEnvelope(thing) || !Array.isArray(thing.value)) return false;\n const path = typePath(thing.type as TypeRef);\n return path !== undefined && path.length === 1 && path[0] === \"ref\";\n}\n\nconst worlds = new WeakMap<World, Json>();\n\n/**\n * This function makes the thing of the root `world`: the entries of the world as JSON. An alias is a reference\n * document in it, thus a walk through the world follows each alias (collapse). The thing of a world is made one\n * time.\n *\n * @param world - The world.\n * @returns The thing.\n */\nexport function worldThing(world: World): Json {\n let thing = worlds.get(world);\n if (thing === undefined) {\n thing = entriesAsJson(world.kinds);\n worlds.set(world, thing);\n }\n return thing;\n}\n\n/**\n * This function makes a context. The world comes from the navigator when the call gives none.\n *\n * @param parts - The roots to set.\n * @returns The context.\n */\nexport function context(parts: Partial<Context> = {}): Context {\n return {\n self: parts.self ?? null,\n names: parts.names ?? {},\n world: parts.world ?? null,\n event: parts.event ?? null,\n caps: parts.caps ?? [],\n };\n}\n\nconst MAX_COLLAPSE = 64;\nconst NO_HOPS: readonly Hop[] = Object.freeze([]);\n\n/** A value that can be a reference document: a record with the type `ref`. The full check comes after. */\nfunction mayBeRef(thing: unknown): boolean {\n return typeof thing === \"object\" && thing !== null && (thing as { readonly type?: unknown }).type === \"ref\";\n}\n\n/** This function tells if each step of a path from an index is a key. */\nfunction keysFrom(path: readonly unknown[], start: number): boolean {\n for (let index = start; index < path.length; index += 1) if (!isKey(path[index])) return false;\n return true;\n}\n\n/**\n * This function resolves the common path without a record of hops: a root, then keys. Plain values answer the\n * keys, or a host thing answers all of them in one call. It gives `undefined` when the path needs the full\n * algorithm. Examples are a host thing without `resolve`, an envelope, a reference to follow, a step document and a\n * failure of a step (for its exact reason).\n */\nfunction resolveQuick(nav: Navigator, ctx: Context, path: readonly unknown[]): Resolution | undefined {\n const root = path[0];\n if (root !== \"names\" && root !== \"self\" && root !== \"event\" && root !== \"world\") return undefined;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return undefined;\n if (nav.adopt !== undefined) return undefined;\n let here: unknown = ctx[root];\n const plain = nav.plain === true;\n for (let index = 1; index < path.length; index += 1) {\n if (typeof here !== \"object\" || here === null) return undefined;\n if (!plain && mayBeRef(here)) return undefined;\n if ((here as Partial<HostThing>)[THING] === true) {\n const thing = here as HostThing;\n if (thing.resolve === undefined || !keysFrom(path, index)) return undefined;\n const keys = path.slice(index) as readonly Key[];\n const reached = thing.resolve(keys);\n if (reached === undefined) return { ok: false, code: \"#N/A\", reason: `The path ${keys.join(\".\")} reaches nothing.`, hops: NO_HOPS };\n if (!plain && mayBeRef(reached.thing)) return undefined;\n return { ok: true, thing: reached.thing, hops: NO_HOPS };\n }\n const step = path[index];\n if (Array.isArray(here)) {\n if (typeof step !== \"number\" || !Number.isInteger(step) || step < 0 || step >= here.length) return undefined;\n here = (here as readonly unknown[])[step];\n continue;\n }\n if (typeof step !== \"string\" || !Object.hasOwn(here, step)) return undefined;\n if (!plain && isEnvelope(here)) return undefined;\n here = (here as Readonly<Record<string, unknown>>)[step];\n }\n if (!plain && mayBeRef(here)) return undefined;\n return { ok: true, thing: here, hops: NO_HOPS };\n}\n\n/**\n * This function resolves a path from a context, and records each hop.\n *\n * The first step is a root of the context. Each later step is a key or a step document. A key goes up the ladder\n * of the verb `deref` on the thing that the path reached. A step document is evaluated by the walker of its kind,\n * with the thing that the path reached. After each hop, a reference document is followed until the path reaches\n * something else (collapse), except in a plain navigation.\n *\n * The codes of a failure:\n *\n * - `#REF!`: the path has no root, or a root that is not open here.\n * - `#NAME?`: the root `names` has no such name.\n * - `#N/A`: a step reaches nothing.\n * - `#STEP?`: a step is not a key and not a step document.\n * - `#CYCLE!`: the references form a cycle.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The steps.\n * @param options - `hops: false` does not record the hops.\n * @returns What the path reached and each hop, or an error.\n */\nexport function resolve(nav: Navigator, ctx: Context, path: readonly unknown[], options: ResolveOptions = {}): Resolution {\n if (options.hops === false) {\n const quick = resolveQuick(nav, ctx, path);\n if (quick !== undefined) return quick;\n }\n const hops: Hop[] | undefined = options.hops === false ? undefined : [];\n const done = hops ?? NO_HOPS;\n const failed = (code: ResolveCode | ErrorCode, reason: string): Resolution => ({ ok: false, code, reason, hops: done });\n let collapses = 0;\n const adopt = nav.adopt ?? ((value: unknown): Thing => value);\n\n const collapse = (thing: Thing): Resolution => {\n let here = thing;\n if (nav.plain === true) return { ok: true, thing: here, hops: done };\n while (isRef(here)) {\n collapses += 1;\n if (collapses > MAX_COLLAPSE) return failed(\"#CYCLE!\", \"The references form a cycle.\");\n const inner = walk(here.value);\n if (!inner.ok) return inner;\n here = adopt(inner.thing);\n hops?.push({ step: \"collapse\", thing: here, by: \"collapse\" });\n }\n return { ok: true, thing: here, hops: done };\n };\n\n const walk = (steps: readonly unknown[]): Resolution => {\n const root = steps[0];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) {\n return failed(\"#REF!\", `A path starts with a root: ${ROOTS.join(\", \")}.`);\n }\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) {\n return failed(\"#REF!\", `The root ${root} is not open here. The open roots are ${nav.roots.join(\", \")}.`);\n }\n let here: Thing = adopt(ctx[root as Root]);\n hops?.push({ step: root, thing: here, by: \"root\" });\n const first = collapse(here);\n if (!first.ok) return first;\n here = first.thing;\n for (let index = 1; index < steps.length; index += 1) {\n const step = steps[index];\n if (isHostThing(here) && here.resolve !== undefined && steps.slice(index).every(isKey)) {\n const keys = steps.slice(index) as readonly Key[];\n const reached = here.resolve(keys);\n if (reached === undefined) return failed(\"#N/A\", `The path ${keys.join(\".\")} reaches nothing.`);\n const thing = adopt(reached.thing);\n hops?.push({ step: keys as readonly Json[], thing, by: \"own\" });\n return collapse(thing);\n }\n if (isKey(step)) {\n const reached = derefStep(nav, here, step);\n if (reached === undefined) {\n if (root === \"names\" && index === 1) return failed(\"#NAME?\", `The context has no name ${String(step)}.`);\n return failed(\"#N/A\", `The step ${String(step)} reaches nothing.`);\n }\n here = adopt(reached.thing);\n hops?.push({ step, thing: here, by: reached.by });\n } else {\n const envelope = isEnvelope(step) ? step : undefined;\n const found = envelope === undefined ? undefined : lookupKind(nav.world, envelope.type);\n const name = found?.ok === true ? entryOf(found.kind.verbs, \"step\") : undefined;\n const walker = name === undefined ? undefined : nav.walkers?.[name];\n if (envelope === undefined || walker === undefined) {\n return failed(\"#STEP?\", \"A step is a key, or a document of a kind with the verb step.\");\n }\n const result = walker({\n data: envelope.value,\n here,\n context: ctx,\n deref: (thing, key) => {\n const reached = derefStep(nav, thing, key);\n return reached === undefined ? undefined : adopt(reached.thing);\n },\n });\n if (!result.ok) return failed(result.code ?? \"#N/A\", result.reason);\n here = adopt(result.thing);\n hops?.push({ step: envelope as Json, thing: here, by: \"step\" });\n }\n const next = collapse(here);\n if (!next.ok) return next;\n here = next.thing;\n }\n return { ok: true, thing: here, hops: done };\n };\n\n if (path.length === 0) return failed(\"#REF!\", \"A path has at least one step: its root.\");\n return walk(path);\n}\n\n/**\n * This function gives the value of a thing: the value that a host thing gives, or else the thing itself.\n *\n * @param thing - The thing.\n * @returns The value.\n */\nexport function valueOfThing(thing: Thing): unknown {\n return isHostThing(thing) ? thing.toJson() : thing;\n}\n","import { type Envelope, type Json, field, isRecord, typed } from \"./doc.ts\";\n\n/** A shape proposes a kind for each document that has all of its fields. */\nexport interface Shape {\n readonly name: string;\n readonly fields: readonly string[];\n readonly kind: string;\n}\n\n/** The result of a classification. */\nexport interface Classification {\n /** The kind of the one most specific shape. */\n readonly kind?: string;\n /** The names of the most specific shapes. */\n readonly candidates: readonly string[];\n /** `no-match`: no shape applies. `ambiguous`: two or more shapes match equally well. */\n readonly error?: \"no-match\" | \"ambiguous\";\n}\n\nfunction isStrictSuperset(larger: readonly string[], smaller: readonly string[]): boolean {\n return larger.length > smaller.length && smaller.every((name) => larger.includes(name));\n}\n\n/**\n * This function proposes a kind for a value without a type, from the fields that the value has.\n * A shape applies when the value has each field of the shape. The most specific shapes are the ones that\n * no other applicable shape contains. A host uses a classifier when data comes in, and then tags the data.\n * The ladder does not call a classifier.\n *\n * @param shapes - The shapes to examine.\n * @param value - The value without a type.\n * @returns The proposed kind, or an error with the candidates.\n */\nexport function classify(shapes: readonly Shape[], value: Json): Classification {\n const applicable = isRecord(value)\n ? shapes.filter((shape) => shape.fields.every((name) => field(value, name) !== undefined))\n : [];\n const best = applicable.filter((shape) => !applicable.some((other) => isStrictSuperset(other.fields, shape.fields)));\n const candidates = best.map((shape) => shape.name);\n const only = best.length === 1 ? best[0] : undefined;\n if (only !== undefined) return { kind: only.kind, candidates };\n return { candidates, error: best.length === 0 ? \"no-match\" : \"ambiguous\" };\n}\n\n/**\n * This function puts a value in an envelope with a type. The value does not change.\n *\n * @param value - The value.\n * @param kind - The name of the kind.\n * @returns The envelope.\n */\nexport function tag(value: Json, kind: string): Envelope {\n return typed(kind, value);\n}\n","import { type Json, type Key, docEquals, isEnvelope, isRecord, typeName, typePath } from \"./doc.ts\";\nimport type { Shape } from \"./world.ts\";\n\n/** One part of a value: its place in the value, the JSON of the part, and the type that its position declares. */\nexport interface PartSlot {\n /** The keys from the value of the document to the part. */\n readonly path: readonly Key[];\n /** The path as one text, with a dot between the keys, for example `bind.x`. A part of a list has its index. */\n readonly key: string;\n readonly item: Json;\n readonly of?: string;\n /** `true` when the position of the part declares an address: a reference there gives what its path reaches. */\n readonly address?: true;\n}\n\ntype Template =\n | { readonly t: \"data\"; readonly value: unknown }\n | { readonly t: \"slot\"; readonly index: number }\n | { readonly t: \"list\"; readonly items: readonly Template[] }\n | { readonly t: \"record\"; readonly fields: readonly (readonly [string, Template])[] };\n\n/** The value of a document, split into its parts, by the shape that its kind declares. */\nexport type Split =\n | {\n readonly ok: true;\n /** The parts, in the order of the value. */\n readonly parts: readonly PartSlot[];\n /** The value without the parts: a field that holds a part is not in it, and a list of parts gives `null`. */\n readonly data: Json;\n /**\n * This function gives the value with a handle in the place of each part.\n *\n * @param handles - One handle for each part, in the order of `parts`.\n * @returns The value with the handles.\n */\n fill<P>(handles: readonly P[]): unknown;\n }\n | { readonly ok: false; readonly reason: string; readonly at: readonly Key[] };\n\nclass Bad {\n constructor(\n readonly reason: string,\n readonly at: readonly Key[],\n ) {}\n}\n\n/** This function sets an own data property. Only the key `__proto__` needs `defineProperty`. */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nconst NO_SLOTS: readonly PartSlot[] = Object.freeze([]);\n\nfunction hasSlots(template: Template): boolean {\n return template.t !== \"data\";\n}\n\n/** This function gives the reason why a value is not data of a shape, or `undefined` when it is. */\nfunction dataFault(spec: Extract<Shape, { readonly shape: \"text\" | \"number\" | \"one\" }>, item: Json): string | undefined {\n if (spec.shape === \"text\") return typeof item === \"string\" ? undefined : \"The value must be a text.\";\n if (spec.shape === \"one\") return spec.values.some((value) => docEquals(value, item)) ? undefined : `The value must be one of ${JSON.stringify(spec.values)}.`;\n if (typeof item !== \"number\") return \"The value must be a number.\";\n if (spec.whole === true && !Number.isInteger(item)) return \"The value must be a whole number.\";\n if (spec.min !== undefined && !(item >= spec.min)) return `The value must be ${String(spec.min)} or more.`;\n if (spec.max !== undefined && !(item <= spec.max)) return `The value must be ${String(spec.max)} or less.`;\n return undefined;\n}\n\n/** This function stops a split when a part has a type that its position does not permit. */\nfunction kindFault(kinds: readonly (readonly Key[])[], item: Json, of: string | undefined, path: readonly Key[]): void {\n const type = isEnvelope(item) ? typePath(item.type) : of === undefined ? undefined : [of];\n const fits = type !== undefined && kinds.some((kind) => kind.length <= type.length && kind.every((key, index) => String(key) === String(type[index])));\n if (fits) return;\n const names = kinds.map((kind) => kind.join(\".\")).join(\", \");\n const what = isEnvelope(item) ? `The kind ${typeName(item.type)} is not permitted here.` : \"A value without an envelope is not permitted here.\";\n throw new Bad(`${what} The permitted kinds are ${names}.`, path);\n}\n\n/**\n * This function splits a value into its parts, by the shape that its kind declares. The evaluator, the view and\n * the static kit use the same split, thus each one sees the same parts.\n *\n * @param shape - The shape of the value. The default is data.\n * @param value - The value of the document.\n * @returns The parts and a way to fill their places, or the reason why the value does not have the shape.\n */\nexport function splitParts(shape: Shape | undefined, value: Json): Split {\n // A value without parts is data: the split needs no template.\n if (shape === undefined || shape.shape === \"none\") return { ok: true, parts: NO_SLOTS, data: value, fill: () => value };\n const parts: PartSlot[] = [];\n const slot = (item: Json, path: readonly Key[], of: string | undefined, address = false): Template => {\n parts.push({ path, key: path.join(\".\"), item, ...(of === undefined ? {} : { of }), ...(address ? { address: true as const } : {}) });\n return { t: \"slot\", index: parts.length - 1 };\n };\n\n const deep = (item: Json, path: readonly Key[], of: string | undefined): Template => {\n if (isEnvelope(item)) return slot(item, path, of);\n if (Array.isArray(item)) {\n const items = (item as readonly Json[]).map((child, index) => deep(child, [...path, index], of));\n return items.some(hasSlots) ? { t: \"list\", items } : { t: \"data\", value: item };\n }\n if (isRecord(item)) {\n const fields = Object.keys(item).map((key) => [key, deep(item[key] as Json, [...path, key], of)] as const);\n return fields.some(([, child]) => hasSlots(child)) ? { t: \"record\", fields } : { t: \"data\", value: item };\n }\n return { t: \"data\", value: item };\n };\n\n const walk = (spec: Shape | undefined, item: Json, path: readonly Key[]): Template => {\n if (spec === undefined || spec.shape === \"none\") return { t: \"data\", value: item };\n if (spec.shape === \"text\" || spec.shape === \"number\" || spec.shape === \"one\") {\n const reason = dataFault(spec, item);\n if (reason !== undefined) throw new Bad(reason, path);\n return { t: \"data\", value: item };\n }\n if (spec.shape === \"term\") {\n if (spec.kinds !== undefined) kindFault(spec.kinds, item, spec.of, path);\n return slot(item, path, spec.of, spec.address === true);\n }\n if (spec.shape === \"deep\") return deep(item, path, spec.of);\n if (spec.shape === \"list\") {\n if (!Array.isArray(item)) throw new Bad(\"The value must be a list.\", path);\n const list = item as readonly Json[];\n if (spec.distinct === true) {\n const twice = list.findIndex((child, index) => list.slice(0, index).some((before) => docEquals(before, child)));\n if (twice !== -1) throw new Bad(\"The items of the list must be different.\", [...path, twice]);\n }\n const each: Shape = spec.item ?? { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) };\n return { t: \"list\", items: list.map((child, index) => walk(each, child, [...path, index])) };\n }\n if (!isRecord(item)) throw new Bad(\"The value must be a record.\", path);\n if (spec.shape === \"map\") {\n const each: Shape = spec.item ?? { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) };\n return { t: \"record\", fields: Object.keys(item).map((key) => [key, walk(each, item[key] as Json, [...path, key])] as const) };\n }\n for (const name of spec.required ?? []) {\n if (!Object.hasOwn(item, name)) throw new Bad(`The field ${name} is missing.`, path);\n }\n const named: Readonly<Record<string, Shape>> = Array.isArray(spec.fields)\n ? Object.fromEntries((spec.fields as readonly string[]).map((name) => [name, { shape: \"term\", ...(spec.of === undefined ? {} : { of: spec.of }) } as Shape]))\n : (spec.fields as Readonly<Record<string, Shape>>);\n const fields: (readonly [string, Template])[] = [];\n for (const key of Object.keys(item)) {\n if (spec.closed === true && !Object.hasOwn(named, key)) throw new Bad(`The field ${key} is not a field of this kind.`, [...path, key]);\n const fieldShape = Object.hasOwn(named, key) ? named[key] : spec.rest;\n fields.push([key, walk(fieldShape, item[key] as Json, [...path, key])]);\n }\n return { t: \"record\", fields };\n };\n\n let template: Template;\n try {\n template = walk(shape, value, []);\n } catch (error) {\n if (error instanceof Bad) return { ok: false, reason: error.reason, at: error.at };\n throw error;\n }\n\n const strip = (node: Template): Json | undefined => {\n if (node.t === \"data\") return node.value as Json;\n if (node.t === \"slot\") return undefined;\n if (node.t === \"list\") return node.items.every((child) => child.t === \"slot\") ? null : (node.items.map((child) => strip(child) ?? null) as Json);\n const out: Record<string, Json> = {};\n for (const [key, child] of node.fields) {\n const kept = strip(child);\n if (kept !== undefined) setOwn(out, key, kept);\n }\n return out;\n };\n\n const fillWith = <P>(node: Template, handles: readonly P[]): unknown => {\n if (node.t === \"data\") return node.value;\n if (node.t === \"slot\") return handles[node.index];\n if (node.t === \"list\") return node.items.map((child) => fillWith(child, handles));\n const out: Record<string, unknown> = {};\n for (const [key, child] of node.fields) setOwn(out, key, fillWith(child, handles));\n return out;\n };\n\n return { ok: true, parts, data: strip(template) ?? null, fill: (handles) => fillWith(template, handles) };\n}\n\n/**\n * This function tells if the path of a part matches a pattern of a scope rule. The key `\"*\"` of a pattern matches\n * each key.\n *\n * @param path - The path of the part.\n * @param pattern - The pattern.\n * @returns `true` when the path matches.\n */\nexport function pathMatches(path: readonly Key[], pattern: readonly Key[]): boolean {\n if (path.length !== pattern.length) return false;\n for (let index = 0; index < path.length; index += 1) {\n const want = pattern[index];\n if (want !== \"*\" && String(want) !== String(path[index])) return false;\n }\n return true;\n}\n","import { type Envelope, type Json, type Key, type TypeRef, isEnvelope, typeName } from \"./doc.ts\";\nimport { type Split, pathMatches, splitParts } from \"./parts.ts\";\nimport { ask, type Answer } from \"./ladder.ts\";\nimport { type CapsRule, type Lookup, type Side, type World, lookupKind } from \"./world.ts\";\nimport { type ErrorCode, type EvalError, type Result, fail, ok, placed, thrown, describe } from \"./errors.ts\";\nimport {\n type Cap,\n type Context,\n type Navigator,\n type Resolution,\n type ResolveOptions,\n type Thing,\n context as makeRootContext,\n isHostThing,\n resolve,\n worldThing,\n} from \"./deref.ts\";\n\nexport type { Context } from \"./deref.ts\";\nexport type { ErrorCode, EvalError, Result } from \"./errors.ts\";\nexport { fail, ok } from \"./errors.ts\";\n\n/**\n * This function makes a context with names and capabilities. The other roots are empty, and an evaluation sets\n * the world.\n *\n * @param names - The names and their values.\n * @param caps - The effects that the term can cause.\n * @param self - The node of the term, if it has one.\n * @returns The context.\n */\nexport function makeContext(names: Readonly<Record<string, unknown>> = {}, caps: readonly Cap[] = [], self: Thing = null): Context {\n return makeRootContext({ names, caps, self });\n}\n\n/**\n * This function gives the keys of a capability or of a kind of effect: a text is split at its dots.\n *\n * @param kind - The text or the keys.\n * @returns The keys, as texts.\n */\nexport function capKeys(kind: Cap): readonly string[] {\n return typeof kind === \"string\" ? kind.split(\".\") : kind.map(String);\n}\n\n/**\n * This function tells if the capabilities permit an effect. A capability permits the kind of its name, and each kind\n * under it: `store` permits `store.update`. The comparison is key by key, thus `fs.read` does not permit the\n * kind with the keys `fs` and `read.json`.\n *\n * @param caps - The capabilities of the context.\n * @param kind - The kind of the effect: a text with dots, or its keys.\n * @returns `true` when one capability permits it.\n */\nexport function permits(caps: readonly Cap[], kind: Cap): boolean {\n const want = capKeys(kind);\n return caps.some((cap) => {\n const have = capKeys(cap);\n return have.length <= want.length && have.every((key, index) => key === want[index]);\n });\n}\n\n/**\n * This function narrows a context for a part: the part keeps only the capabilities that the context of its parent\n * permits. Thus an evaluator cannot give a part more effects than it has.\n *\n * @param parent - The context of the parent.\n * @param next - The context that the evaluator gives the part.\n * @returns The context of the part.\n */\nexport function narrow(parent: Context, next: Context): Context {\n if (next === parent || next.caps === parent.caps) return next;\n const caps = next.caps.filter((cap) => permits(parent.caps, cap));\n return caps.length === next.caps.length ? next : { ...next, caps };\n}\n\n/** No capabilities. One list serves each masked part. */\nconst NO_CAPS: readonly Cap[] = Object.freeze([]);\n\n/** No capability rules. One list serves each part that no rule narrows. */\nconst NO_RULES: readonly CapsRule[] = Object.freeze([]);\n\n/**\n * This function gives the capabilities that two lists both permit. An effect is permitted by the result when each\n * list permits it. When the list `b` permits each capability of `a`, the result is the list `a` itself.\n *\n * @param a - The first list, for example the capabilities of a document.\n * @param b - The second list, for example the list of a rule `only`.\n * @returns The capabilities that both lists permit.\n */\nexport function intersectCaps(a: readonly Cap[], b: readonly Cap[]): readonly Cap[] {\n if (a.every((cap) => permits(b, cap))) return a;\n const out: Cap[] = [];\n for (const cap of b) if (permits(a, cap)) out.push(cap);\n for (const cap of a) if (permits(b, cap) && !permits(out, cap)) out.push(cap);\n return out;\n}\n\n/** This function gives the capability rules of a kind that cover a part and change its capabilities. */\nfunction rulesFor(rules: readonly CapsRule[] | undefined, path: readonly Key[]): readonly CapsRule[] {\n if (rules === undefined || rules.length === 0) return NO_RULES;\n const out = rules.filter((rule) => rule.rule !== \"same\" && (rule.in === undefined || rule.in.some((pattern) => pathMatches(path, pattern))));\n return out.length === 0 ? NO_RULES : out;\n}\n\n/** This function applies the rules that cover a part to the capabilities of its document. */\nfunction capsUnder(rules: readonly CapsRule[], caps: readonly Cap[]): readonly Cap[] {\n let out = caps;\n for (const rule of rules) {\n if (rule.rule === \"mask\") return NO_CAPS;\n if (rule.rule === \"only\") out = intersectCaps(out, rule.caps);\n }\n return out;\n}\n\n/**\n * This function gives the capabilities that a kind gives one of its parts, by the capability rules of its contract.\n * The kernel and the static kit both use it, thus a run and a check narrow the same way.\n *\n * @param rules - The capability rules of the kind (`Kind.caps`).\n * @param path - The path of the part in the value of the document.\n * @param caps - The capabilities of the document.\n * @returns The capabilities of the part: the same list or a smaller one.\n */\nexport function partCaps(rules: readonly CapsRule[] | undefined, path: readonly Key[], caps: readonly Cap[]): readonly Cap[] {\n return capsUnder(rulesFor(rules, path), caps);\n}\n\n/**\n * The steps of an evaluation that can wait. It yields a promise only when the host makes it wait. A runner takes the\n * result of a part with `yield*`, thus a run goes on at once until an effect waits. A runner does not yield a\n * promise itself: it uses `yield*` on the steps that the kernel gives.\n */\nexport type Steps = Generator<Promise<unknown>, Result, unknown>;\n\n/** An effect that an evaluation caused, in the order of the effects. */\nexport interface Effect {\n readonly index: number;\n /** The kind of the effect, as a text with dots. */\n readonly kind: string;\n /** The keys of the kind of the effect. */\n readonly path: readonly Key[];\n readonly payload: unknown;\n /** The ID of the trace node that caused the effect, or -1 without a trace. */\n readonly node: number;\n /** The number of events before the effect. The effect comes before the end of its node. */\n readonly at: number;\n /** The keys from the root document to the document that caused the effect. */\n readonly place: readonly Key[];\n /** The context of the document that caused the effect: its names, its node and its capabilities. */\n readonly context: Context;\n}\n\n/** The host side of a run: it does one effect, and gives its result. A throw or a rejection is an error value. */\nexport type Perform = (effect: Effect) => unknown;\n\n/**\n * The runtime of one evaluation or run. Compiled code gets it with the context, and asks it to resolve paths and\n * to cause effects.\n */\nexport interface Runtime {\n readonly machine: Machine;\n /** `true` in a run: the host does each effect, and a part that waits needs a parent that can wait. */\n readonly running: boolean;\n /**\n * This function resolves a path from a context.\n *\n * @param ctx - The context.\n * @param path - The steps. The first step is a root.\n * @param options - `hops: true` records each hop. The default records them only in a traced evaluation.\n * @returns What the path reached, or an error.\n */\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect from an evaluator. In a run, an evaluator cannot cause an effect: the host does\n * each effect, thus only a runner can wait for it.\n *\n * @param ctx - The context of the document.\n * @param kind - The kind of the effect.\n * @param payload - The data of the effect.\n * @param place - The place of the document.\n * @returns The payload, or an error value.\n */\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result;\n /**\n * This function causes an effect from a runner. In a run, the host does it, and the steps wait when the host\n * waits.\n *\n * @param ctx - The context of the document.\n * @param kind - The kind of the effect.\n * @param payload - The data of the effect.\n * @param place - The place of the document.\n * @returns The steps that give the result of the host, or an error value.\n */\n runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps;\n /**\n * This function drives several steps at the same time. When one waits, the others go on.\n *\n * @param list - One function for each item. Each function starts the steps of its item.\n * @param options - The most items that run at the same time, and the stop at the first failure.\n * @returns The steps that give each result, in the order of the list.\n */\n all(list: readonly (() => Steps)[], options?: AllOptions): Generator<Promise<unknown>, readonly Result[], unknown>;\n}\n\n/**\n * The options of a drive of parts at the same time.\n *\n * - `concurrency`: the most parts that run at the same time. The default is each part.\n * - `failFast`: `true` stops at the first part that fails. The parts that did not start do not start, the parts that\n * run stop at their wait, and the results come at once. Each part without a result gives `#ABORT`.\n */\nexport interface AllOptions {\n readonly concurrency?: number;\n readonly failFast?: boolean;\n}\n\n/** Compiled code: the evaluation of a document in a context. */\nexport type Code = (ctx: Context, rt: Runtime) => Result;\n\n/** Compiled code that can wait: the run of a document in a context. */\nexport type RunCode = (ctx: Context, rt: Runtime) => Steps;\n\n/** A compiled part: its place in its parent, its binding name, and its code. It has no field with its value. */\nexport interface CompiledPart {\n /** The path in the value of the parent as one text, for example `0` or `bind.x`. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /** The code that evaluates the part. */\n readonly code: Code;\n /** The code that runs the part. Its steps can wait. */\n readonly run: RunCode;\n}\n\n/** The input of a compiler: the document, its kind, and its parts, compiled. */\nexport interface CompileInput {\n /** The text of the type of the document, for example `add` or `math.sum` after its alias. */\n readonly kind: string;\n /** The keys of the kind after each alias. */\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a compiled part in the place of each part. */\n readonly value: unknown;\n /** The value of the document without its parts. */\n readonly data: Json;\n /** The compiled parts, in the order of the value. */\n readonly parts: readonly CompiledPart[];\n /** The keys from the root document to this document. */\n readonly place: readonly Key[];\n readonly machine: Machine;\n /**\n * This function gives the value of the document with an item in the place of each part. The containers on the way\n * to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`, for example the results of the parts.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n /** `true` when the position of the document declares an address. A reference there gives the thing, not its value. */\n readonly address?: boolean;\n}\n\n/**\n * A sealed part. An evaluator can read the binding name of a part and evaluate it. It cannot read the value of the\n * part, thus two parts that give the same results can replace each other.\n */\nexport interface Part {\n /** The path in the value of the parent as one text, for example `0` or `bind.x`. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /**\n * This function evaluates the part. Each call is a new evaluation.\n *\n * @param context - The context for the part. The default is the context of the parent.\n * @returns The result of the part.\n */\n evaluate(context?: Context): Result;\n}\n\n/** The input of an evaluator. */\nexport interface EvalInput {\n /** The text of the type of the document, for example `add` or `math.sum` after its alias. */\n readonly kind: string;\n /** The keys of the kind after each alias. */\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a sealed part in the place of each part. */\n readonly value: unknown;\n /** The value of the document without its parts. */\n readonly data: Json;\n /** The parts, in the order of the value. */\n readonly parts: readonly Part[];\n /** The context of the document. */\n readonly context: Context;\n /** The keys from the root document to this document. */\n readonly place: readonly Key[];\n /** `true` when the position of the document declares an address. */\n readonly address?: boolean;\n /**\n * This function resolves a path from the context of the document.\n *\n * @param path - The steps. The first step is a root.\n * @param options - `hops: true` records each hop.\n * @returns What the path reached, or an error.\n */\n resolve(path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect. The context must have the capability for the kind of the effect. In a run, an\n * evaluator cannot cause an effect: the host does each effect, thus only a runner can wait for it.\n *\n * @param kind - The kind of the effect, for example `log`.\n * @param payload - The data of the effect.\n * @returns The payload, or the error `#CAP!`.\n */\n effect(kind: Cap, payload: unknown): Result;\n /**\n * This function gives the value of the document with an item in the place of each part, for example the result of\n * each part. The containers on the way to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n}\n\n/** A part for a runner. Its evaluation can wait for the effects in it. */\nexport interface RunPart {\n /** The path in the value of the parent as one text. */\n readonly key: string;\n /** The keys from the value of the parent to the part. */\n readonly path: readonly Key[];\n /** The binding name from the header of the part. */\n readonly name?: string;\n /**\n * This function evaluates the part. Each call is a new evaluation. Take its result with `yield*`.\n *\n * @param context - The context for the part. The default is the context of the parent.\n * @returns The steps of the evaluation of the part.\n */\n evaluate(context?: Context): Steps;\n}\n\n/** The input of a runner: the input of an evaluator, with parts and effects that can wait. */\nexport interface RunInput {\n readonly kind: string;\n readonly typePath: readonly Key[];\n readonly doc: Envelope;\n /** The value of the document with a part for a runner in the place of each part. */\n readonly value: unknown;\n readonly data: Json;\n readonly parts: readonly RunPart[];\n readonly context: Context;\n readonly place: readonly Key[];\n resolve(path: readonly unknown[], options?: ResolveOptions): Resolution;\n /**\n * This function causes an effect. In a run, the host does the effect, and the steps wait when the host waits. In\n * an evaluation, the effect gives its payload. Take its result with `yield*`.\n *\n * @param kind - The kind of the effect, for example `log`.\n * @param payload - The data of the effect.\n * @returns The steps that give the result of the host, or an error value.\n */\n effect(kind: Cap, payload: unknown): Steps;\n /**\n * This function evaluates parts at the same time. Take the results with `yield*`. A runner can give its own parts,\n * for example a part with a different context: each part needs only the function `evaluate`.\n *\n * @param parts - The parts.\n * @param options - The most parts that run at the same time, and the stop at the first failure.\n * @returns The steps that give each result, in the order of the parts.\n */\n all(parts: readonly RunPart[], options?: AllOptions): Generator<Promise<unknown>, readonly Result[], unknown>;\n /**\n * This function gives the value of the document with an item in the place of each part, for example the result of\n * each part. The containers on the way to a part are new. The data around the parts stays the same objects.\n *\n * @param items - One item for each part, in the order of `parts`.\n * @returns The value with the items.\n */\n fill(items: readonly unknown[]): unknown;\n}\n\n/** An evaluator that is a function of its input. The kernel calls it for each evaluation. */\nexport type EvalFn = (input: EvalInput) => Result;\n\n/** An evaluator that compiles a document one time into code. The code then evaluates it many times. */\nexport interface CompiledEvaluator {\n /**\n * This function compiles a document.\n *\n * @param input - The document, its kind and its compiled parts.\n * @returns The code that evaluates the document.\n */\n readonly compile: (input: CompileInput) => Code;\n}\n\n/** An evaluator: a function of its input, or a compiler. */\nexport type Evaluator = EvalFn | CompiledEvaluator;\n\n/** A runner that is a generator function of its input. */\nexport type RunFn = (input: RunInput) => Steps;\n\n/** A runner that compiles a document one time into code that can wait. */\nexport interface CompiledRunner {\n /**\n * This function compiles a document.\n *\n * @param input - The document, its kind and its compiled parts.\n * @returns The code that runs the document.\n */\n readonly compileRun: (input: CompileInput) => RunCode;\n}\n\n/**\n * A runner: the code of a kind whose parts or effects can wait. The same runner serves an evaluation, which does\n * not wait at any time, and a run, in which the host does each effect.\n */\nexport type Runner = RunFn | CompiledRunner;\n\n/**\n * A machine: a world of kinds, and the code of each evaluator name, of each `deref` and of each walker.\n *\n * - `maxDepth`: the deepest nesting of documents. The default is 1000.\n * - `permits`: the rule of the host for an effect. The default is the function `permits` on the capabilities.\n */\nexport interface Machine extends Navigator {\n readonly evaluators: Readonly<Record<string, Evaluator>>;\n /** The runners, by evaluator name. A runner wins over an evaluator of the same name. */\n readonly runners?: Readonly<Record<string, Runner>>;\n readonly maxDepth?: number;\n readonly permits?: (caps: readonly Cap[], kind: readonly Key[], context: Context) => boolean;\n}\n\n/** One evaluation in a trace. The children are the evaluations of its parts, in the order that they started. */\nexport interface TraceNode {\n readonly id: number;\n /** The keys from the root document to this document, as texts. */\n readonly path: readonly string[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** `true` when the type came from the container and not from an envelope. */\n readonly declared: boolean;\n /** The answer of the ladder to the verb `eval`. */\n readonly answer: Answer;\n readonly side: Side;\n /** The names that the document could read when its evaluation started. */\n readonly names: readonly string[];\n /** The names and their values when the evaluation started. */\n readonly scope: Readonly<Record<string, unknown>>;\n /** The capabilities that the document had when its evaluation started. */\n readonly caps: readonly Cap[];\n /** A short text for the root `self` when the evaluation started. */\n readonly self: string;\n /** The time of the start. Each start and each end takes one tick. */\n readonly enter: number;\n /** The time of the end. */\n readonly exit: number;\n readonly result: Result;\n readonly children: readonly TraceNode[];\n /** The indices of the effects that this document caused itself. */\n readonly effects: readonly number[];\n}\n\n/** The record of one evaluation of a document. */\nexport interface Run {\n readonly result: Result;\n readonly trace: TraceNode;\n readonly effects: readonly Effect[];\n /** The number of ticks. */\n readonly time: number;\n}\n\ninterface Building {\n id: number;\n path: readonly string[];\n doc: Envelope;\n declared: boolean;\n answer: Answer;\n side: Side;\n names: readonly string[];\n scope: Readonly<Record<string, unknown>>;\n caps: readonly Cap[];\n self: string;\n enter: number;\n exit: number;\n result: Result;\n children: Building[];\n effects: number[];\n}\n\n/** What a trace node knows from the compilation. */\ninterface Meta {\n readonly path: readonly string[];\n readonly doc: Envelope;\n readonly declared: boolean;\n readonly answer: Answer;\n readonly side: Side;\n}\n\nfunction selfLabel(self: Thing): string {\n try {\n if (isHostThing(self)) return self.label;\n if (self === null || self === undefined) return \"none\";\n return (JSON.stringify(self) ?? describe(self)).slice(0, 40);\n } catch {\n return describe(self).slice(0, 40);\n }\n}\n\nconst NO_ANSWER: Answer = { verb: \"eval\", error: \"no-answer\", steps: [] };\n\n/** A signal of the host that stops a run: the shape of the standard `AbortSignal`. */\nexport interface StopSignal {\n readonly aborted: boolean;\n readonly reason?: unknown;\n addEventListener(type: \"abort\", listener: () => void, options?: { readonly once?: boolean }): void;\n}\n\n/** The options of a run. */\nexport interface RunOptions {\n /** The host code that does each effect. Without it, an effect gives its payload, as in an evaluation. */\n readonly perform?: Perform;\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** A signal of the host. When it aborts, the run stops with `#ABORT`. */\n readonly signal?: StopSignal;\n}\n\n/** The options of an evaluation of a plan. */\nexport interface EvalOptions {\n /** A list that gets each effect, in its order. */\n readonly effects?: Effect[];\n}\n\n/** The options of a resolution without a record of hops, and with one. One object of each serves each call. */\nconst WITHOUT_HOPS: ResolveOptions = Object.freeze({ hops: false });\nconst WITH_HOPS: ResolveOptions = Object.freeze({ hops: true });\n\n/** This class holds the state of one evaluation or run: the machine, the effects, the clock and the trace. */\nclass Session implements Runtime {\n /** The list of the effects. It is made at the first effect, thus an evaluation without effects makes no list. */\n private list: Effect[] | undefined;\n tick = 0;\n nextId = 0;\n current: Building | undefined;\n readonly holder: Building | undefined;\n\n constructor(\n readonly machine: Machine,\n readonly running: boolean,\n readonly traced: boolean,\n readonly perform: Perform | undefined,\n readonly signal: StopSignal | undefined,\n effects: Effect[] | undefined,\n ) {\n this.list = effects;\n this.holder = traced ? holderNode() : undefined;\n this.current = this.holder;\n }\n\n /** The effects of the evaluation, in their order. */\n get effects(): Effect[] {\n return (this.list ??= []);\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const hops = options?.hops ?? this.traced;\n return resolve(this.machine, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n }\n\n private permitted(ctx: Context, keys: readonly Key[]): boolean {\n return this.machine.permits === undefined ? permits(ctx.caps, keys) : this.machine.permits(ctx.caps, keys, ctx);\n }\n\n private record(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result | Effect {\n const keys = typeof kind === \"string\" ? kind.split(\".\") : kind;\n const text = keys.join(\".\");\n if (!this.permitted(ctx, keys)) return fail(\"#CAP!\", `The context has no capability for the effect ${text}.`, { place });\n const node = this.current;\n const list = this.effects;\n const effect: Effect = { index: list.length, kind: text, path: keys, payload, node: node?.id ?? -1, at: this.tick, place, context: ctx };\n list.push(effect);\n if (node !== undefined) node.effects.push(effect.index);\n return effect;\n }\n\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const text = typeof kind === \"string\" ? kind : kind.join(\".\");\n if (this.running) return fail(\"#CALC!\", `The effect ${text} needs a runner: in a run, the host does each effect.`, { place });\n const made = this.record(ctx, kind, payload, place);\n return \"ok\" in made ? made : ok(payload);\n }\n\n *runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps {\n const made = this.record(ctx, kind, payload, place);\n if (\"ok\" in made) return made;\n const perform = this.perform;\n if (!this.running || perform === undefined) return ok(payload);\n const failed = (error: unknown): Result => fail(\"#CALC!\", `The host failed the effect ${made.kind}: ${describe(error)}`, { place, cause: error });\n let done: unknown;\n try {\n done = perform(made);\n } catch (error) {\n return failed(error);\n }\n if (!(done instanceof Promise)) return ok(done);\n return (yield done.then((value: unknown) => ok(value), failed)) as Result;\n }\n\n *all(list: readonly (() => Steps)[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n const results: Result[] = new Array<Result>(list.length);\n const limit = Math.max(1, options.concurrency ?? list.length);\n const failFast = options.failFast === true;\n let failed = false;\n interface Active {\n readonly index: number;\n readonly steps: Steps;\n pending: Promise<unknown>;\n }\n const active: Active[] = [];\n let next = 0;\n const settle = (index: number, result: Result): void => {\n results[index] = result;\n if (failFast && !result.ok) failed = true;\n };\n const advance = (index: number, steps: Steps, input: { readonly value?: unknown; readonly error?: unknown; readonly threw: boolean }): void => {\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = input.threw ? steps.throw(input.error) : steps.next(input.value);\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n return;\n }\n if (step.done === true) {\n settle(index, step.value);\n return;\n }\n const item: Active = { index, steps, pending: Promise.resolve() };\n item.pending = step.value.then(\n (value) => ({ item, value, threw: false }),\n (error: unknown) => ({ item, error, threw: true }),\n );\n active.push(item);\n };\n const start = (): void => {\n while (!failed && active.length < limit && next < list.length) {\n const index = next;\n next += 1;\n const begin = list[index] as () => Steps;\n let steps: Steps;\n try {\n steps = begin();\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n continue;\n }\n advance(index, steps, { threw: false });\n }\n };\n start();\n while (active.length > 0 && !failed) {\n const settled = (yield Promise.race(active.map((item) => item.pending))) as {\n readonly item: Active;\n readonly value?: unknown;\n readonly error?: unknown;\n readonly threw: boolean;\n };\n active.splice(active.indexOf(settled.item), 1);\n advance(settled.item.index, settled.item.steps, settled);\n start();\n }\n if (!failed) return results;\n const stopped = fail(\"#ABORT\", \"The part stopped: a part before it failed, and the parts run with failFast.\");\n for (const item of active) {\n try {\n item.steps.return(stopped);\n } catch {\n // The finally code of a part threw. The part stops with the abort.\n }\n }\n for (let index = 0; index < list.length; index += 1) if (results[index] === undefined) results[index] = stopped;\n return results;\n }\n\n enter(meta: Meta, ctx: Context): Building {\n const node: Building = {\n id: this.nextId,\n path: meta.path,\n doc: meta.doc,\n declared: meta.declared,\n answer: meta.answer,\n side: meta.side,\n names: Object.keys(ctx.names),\n scope: ctx.names,\n caps: ctx.caps,\n self: selfLabel(ctx.self),\n enter: this.tick,\n exit: this.tick,\n result: fail(\"#NOEVAL\", \"The evaluation did not end.\"),\n children: [],\n effects: [],\n };\n this.nextId += 1;\n this.tick += 1;\n (this.current ?? (this.holder as Building)).children.push(node);\n return node;\n }\n\n exit(node: Building, result: Result): void {\n node.result = result;\n node.exit = this.tick;\n this.tick += 1;\n }\n}\n\nfunction holderNode(): Building {\n return {\n id: -1,\n path: [],\n doc: { type: \"?\", value: null },\n declared: false,\n answer: NO_ANSWER,\n side: \"derive\",\n names: [],\n scope: {},\n caps: [],\n self: \"none\",\n enter: 0,\n exit: 0,\n result: ok(null),\n children: [],\n effects: [],\n };\n}\n\n/** This function drives steps that cannot wait. */\nfunction drive(steps: Steps): Result {\n const step = steps.next();\n if (step.done === true) return step.value;\n void step.value.catch(() => undefined);\n void steps.return(fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\"));\n return fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\");\n}\n\nconst ABORTED = Symbol(\"aborted\");\n\n/** This function drives steps that can wait. The steps before the first wait happen at once, in the call. */\nasync function driveWaiting(steps: Steps, signal: StopSignal | undefined): Promise<Result> {\n const abort = (): Result => {\n const reason = fail(\"#ABORT\", `The host stopped the run: ${describe(signal?.reason ?? \"no reason\")}`, { cause: signal?.reason });\n try {\n steps.return(reason);\n } catch {\n // The finally code of a runner threw. The run stops with the abort.\n }\n return reason;\n };\n const aborted =\n signal === undefined\n ? undefined\n : new Promise<typeof ABORTED>((resolve) => {\n if (signal.aborted) resolve(ABORTED);\n else signal.addEventListener(\"abort\", () => resolve(ABORTED), { once: true });\n });\n if (signal?.aborted === true) return abort();\n let step = steps.next();\n while (step.done !== true) {\n let value: unknown;\n try {\n value = aborted === undefined ? await step.value : await Promise.race([step.value, aborted]);\n } catch (error) {\n step = steps.throw(error);\n continue;\n }\n if (value === ABORTED) return abort();\n step = steps.next(value);\n }\n return step.value;\n}\n\nfunction isCompiledEvaluator(evaluator: Evaluator): evaluator is CompiledEvaluator {\n return typeof evaluator === \"object\" && evaluator !== null && typeof (evaluator as CompiledEvaluator).compile === \"function\";\n}\n\nfunction isCompiledRunner(runner: Runner): runner is CompiledRunner {\n return typeof runner === \"object\" && runner !== null && typeof (runner as CompiledRunner).compileRun === \"function\";\n}\n\n/** The options of a compilation. */\nexport interface PrepareOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** `true`: each evaluation records a trace. The default is `false`. */\n readonly trace?: boolean;\n}\n\n/** A compiled document. It evaluates many times, and it does the work of the ladder one time. */\nexport interface Plan {\n readonly machine: Machine;\n /** `true` when each evaluation records a trace. */\n readonly traced: boolean;\n /** The compiled root document. */\n readonly root: CompiledPart;\n /**\n * This function evaluates the document. It does not wait, and the host does no effect.\n *\n * @param context - The names and the capabilities at the root.\n * @param options - A list that gets the effects.\n * @returns The result.\n */\n evaluate(context?: Context, options?: EvalOptions): Result;\n /**\n * This function runs the document: the host does each effect, and the run waits when the host waits.\n *\n * @param context - The names and the capabilities at the root.\n * @param options - The host code that does the effects, and a signal to stop the run.\n * @returns The result, when the run ends.\n */\n run(context?: Context, options?: RunOptions): Promise<Result>;\n}\n\ninterface Compiler {\n readonly machine: Machine;\n readonly traced: boolean;\n readonly maxDepth: number;\n}\n\nfunction failing(c: Compiler, meta: Meta, place: readonly Key[], code: ErrorCode, reason: string): { readonly code: Code; readonly run: RunCode } {\n const result = fail(code, reason, { place });\n const plain: Code = () => result;\n return finish(c, meta, plain, function* () {\n return result;\n });\n}\n\nfunction finish(c: Compiler, meta: Meta, code: Code, run: RunCode): { readonly code: Code; readonly run: RunCode } {\n if (!c.traced) return { code, run };\n const tracedCode: Code = (ctx, rt) => {\n const s = rt as Session;\n const node = s.enter(meta, ctx);\n const before = s.current;\n s.current = node;\n let result: Result;\n try {\n result = code(ctx, rt);\n } finally {\n s.current = before;\n }\n s.exit(node, result);\n return result;\n };\n const tracedRun: RunCode = function* (ctx, rt) {\n const s = rt as Session;\n const node = s.enter(meta, ctx);\n const steps = run(ctx, rt);\n let input: unknown;\n let threw = false;\n for (;;) {\n const before = s.current;\n s.current = node;\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = threw ? steps.throw(input) : steps.next(input);\n } finally {\n s.current = before;\n }\n if (step.done === true) {\n s.exit(node, step.value);\n return step.value;\n }\n try {\n input = yield step.value;\n threw = false;\n } catch (error) {\n input = error;\n threw = true;\n }\n }\n };\n return { code: tracedCode, run: tracedRun };\n}\n\n/**\n * This function finds the evaluator of the verb `eval` without the record of the rungs, for a compilation without a\n * trace. It gives the same evaluator as `ask`: the own entry, then the kind, then the default of the world.\n */\nfunction evaluatorOf(world: World, envelope: Envelope | undefined, found: Lookup): { readonly name?: string; readonly unknown: boolean } {\n const own = envelope?.own;\n const ownName = own !== undefined && Object.hasOwn(own, \"eval\") ? own[\"eval\"] : undefined;\n if (ownName !== undefined) return { name: ownName, unknown: false };\n if (!found.ok) return { unknown: true };\n const verbs = found.kind.verbs;\n const name = Object.hasOwn(verbs, \"eval\") ? verbs[\"eval\"] : Object.hasOwn(world.defaults, \"eval\") ? world.defaults[\"eval\"] : undefined;\n return name === undefined ? { unknown: false } : { name, unknown: false };\n}\n\n/** The meta of a node of a compilation without a trace. Only a trace reads the meta of a node. */\nconst NO_META: Meta = Object.freeze({ path: [], doc: { type: \"?\", value: null }, declared: false, answer: NO_ANSWER, side: \"derive\" });\n\nfunction compileNode(c: Compiler, value: unknown, place: readonly Key[], declared: string | undefined, depth: number, address = false): { readonly code: Code; readonly run: RunCode } {\n const envelope = isEnvelope(value) ? (value as Envelope) : undefined;\n const doc: Envelope = envelope ?? { type: declared ?? \"?\", value: value as Json };\n const meta0: Meta = c.traced ? { path: place.map(String), doc, declared: envelope === undefined, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n if (envelope === undefined && declared === undefined) {\n return failing(c, meta0, place, \"#PART?\", \"The value has no envelope, and its position declares no type.\");\n }\n if (depth > c.maxDepth) return failing(c, meta0, place, \"#DEPTH!\", `The nesting is deeper than ${c.maxDepth} documents.`);\n\n const world = c.machine.world;\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n let meta = meta0;\n let name: string | undefined;\n let unknown: boolean;\n if (c.traced) {\n const answer = ask(world, envelope ?? {}, \"eval\", declared === undefined ? {} : { declaredType: declared });\n meta = { ...meta0, answer, side: kind?.side ?? \"derive\" };\n name = answer.evaluator;\n unknown = answer.error === \"unknown-kind\";\n } else {\n const quick = evaluatorOf(world, envelope, found);\n name = quick.name;\n unknown = quick.unknown;\n }\n const kindText = typeName(doc.type);\n if (unknown) return failing(c, meta, place, \"#KIND?\", `The world has no kind ${kindText}.`);\n const runners = c.machine.runners ?? {};\n const runner = name !== undefined && Object.hasOwn(runners, name) ? runners[name] : undefined;\n const evaluator = name !== undefined && Object.hasOwn(c.machine.evaluators, name) ? c.machine.evaluators[name] : undefined;\n if (name === undefined || (runner === undefined && evaluator === undefined)) {\n return failing(c, meta, place, \"#NOEVAL\", `No rung gives an evaluator for ${kindText}.`);\n }\n\n const split = splitParts(kind?.parts, doc.value);\n if (!split.ok) {\n const at = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n return failing(c, meta, place, \"#VALUE!\", `${split.reason}${at} The kind is ${kindText}.`);\n }\n const parts: CompiledPart[] = split.parts.map((slot) => {\n const item = slot.item;\n // The capability rules of the contract narrow the context of the part, thus no evaluator can forget them.\n const own = compileNode(c, item, place.concat(slot.path), slot.of, depth + 1, slot.address === true);\n const rules = rulesFor(kind?.caps, slot.path);\n const compiled = rules.length === 0 ? own : gated(rules, own);\n // The binding name is in the header of an envelope. Most parts have no name, thus the cheap test comes first.\n const header = typeof (item as { readonly name?: unknown } | null)?.name === \"string\" && isEnvelope(item) ? (item as { readonly name: string }).name : undefined;\n return header === undefined\n ? { key: slot.key, path: slot.path, code: compiled.code, run: compiled.run }\n : { key: slot.key, path: slot.path, name: header, code: compiled.code, run: compiled.run };\n });\n const typePath = found.ok ? found.path : [];\n const input: CompileInput = {\n kind: kindText,\n typePath,\n doc,\n value: split.parts.length === 0 ? doc.value : split.fill(parts),\n data: split.data,\n parts,\n place,\n machine: c.machine,\n fill: fillOf(split, doc),\n ...(address ? { address: true } : {}),\n };\n if (runner !== undefined) {\n const inner: RunCode = isCompiledRunner(runner) ? runner.compileRun(input) : interpretRun(runner, input, split.fill);\n const run = placedRun(inner, place, name);\n return finish(c, meta, runnerCode(run, place, kindText), run);\n }\n\n const inner: Code = isCompiledEvaluator(evaluator as Evaluator)\n ? (evaluator as CompiledEvaluator).compile(input)\n : interpret(evaluator as EvalFn, input, split.fill);\n const code = placedCode(inner, place, name);\n return finish(c, meta, code, runOf(code));\n}\n\n/*\n * The helpers below make the closures that a plan keeps. Each one has its own small scope. A closure that a\n * compilation made in its own scope keeps each variable of that scope that any closure there reads, for example\n * the split of the value. Thus a plan with these helpers keeps only its code.\n */\n\n/** This function gives the code of a document: the code of its evaluator, with the place of each error and of each exception. */\nfunction placedCode(inner: Code, place: readonly Key[], name: string): Code {\n return (ctx, rt) => {\n try {\n return placed(inner(ctx, rt), place);\n } catch (error) {\n return placed(thrown(error, `the evaluator ${name}`), place);\n }\n };\n}\n\n/**\n * This function gives the code of a part that capability rules cover. The code narrows the context of the part by\n * the rules before the part starts.\n */\nfunction gated(rules: readonly CapsRule[], part: { readonly code: Code; readonly run: RunCode }): { readonly code: Code; readonly run: RunCode } {\n const inner = part.code;\n const steps = part.run;\n const under = (ctx: Context): Context => {\n const caps = capsUnder(rules, ctx.caps);\n return caps === ctx.caps || (caps.length === 0 && ctx.caps.length === 0) ? ctx : { ...ctx, caps };\n };\n return { code: (ctx, rt) => inner(under(ctx), rt), run: (ctx, rt) => steps(under(ctx), rt) };\n}\n\n/** This function gives the steps of a runner, with the place of each error and of each exception. */\nfunction placedRun(inner: RunCode, place: readonly Key[], name: string): RunCode {\n return function* (ctx, rt) {\n try {\n return placed(yield* inner(ctx, rt), place);\n } catch (error) {\n return placed(thrown(error, `the runner ${name}`), place);\n }\n };\n}\n\n/** This function gives the code of a runner in an evaluation: its steps, which cannot wait. */\nfunction runnerCode(run: RunCode, place: readonly Key[], kindText: string): Code {\n return (ctx, rt) =>\n rt.running\n ? fail(\"#CALC!\", `${kindText} waits for effects, and its parent cannot wait. Give the parent a runner.`, { place })\n : drive(run(ctx, rt));\n}\n\n/** This function gives the steps of a run of an evaluator. The code runs at the first step, and it does not wait. */\nfunction runOf(code: Code): RunCode {\n return function* (ctx, rt) {\n return code(ctx, rt);\n };\n}\n\n/** This function gives the fill of a compile input: the value with an item in the place of each part. */\nfunction fillOf(split: Extract<Split, { readonly ok: true }>, doc: Envelope): <P>(items: readonly P[]) => unknown {\n return (items) => (split.parts.length === 0 ? doc.value : split.fill(items));\n}\n\n\nfunction interpret(fn: EvalFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): Code {\n const { kind, typePath, doc, data, place } = input;\n const address = input.address === true ? { address: true } : {};\n const compiled = input.parts;\n const hasParts = compiled.length > 0;\n return (ctx, rt) => {\n const parts: Part[] = compiled.map((part) => ({\n key: part.key,\n path: part.path,\n ...(part.name === undefined ? {} : { name: part.name }),\n evaluate: (override?: Context) => part.code(override === undefined ? ctx : narrow(ctx, override), rt),\n }));\n return fn({\n kind,\n typePath,\n doc,\n value: hasParts ? fill(parts) : doc.value,\n data,\n parts,\n context: ctx,\n place,\n ...address,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.effect(ctx, effectKind, payload, place),\n fill: input.fill,\n });\n };\n}\n\nfunction interpretRun(fn: RunFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): RunCode {\n const { kind, typePath, doc, data, place } = input;\n const compiled = input.parts;\n const hasParts = compiled.length > 0;\n return (ctx, rt) => {\n const parts: RunPart[] = compiled.map((part) => ({\n key: part.key,\n path: part.path,\n ...(part.name === undefined ? {} : { name: part.name }),\n evaluate: (override?: Context) => part.run(override === undefined ? ctx : narrow(ctx, override), rt),\n }));\n return fn({\n kind,\n typePath,\n doc,\n value: hasParts ? fill(parts) : doc.value,\n data,\n parts,\n context: ctx,\n place,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.runEffect(ctx, effectKind, payload, place),\n all: (list, options) => rt.all(list.map((part) => () => part.evaluate()), options),\n fill: input.fill,\n });\n };\n}\n\nfunction rootContext(machine: Machine, ctx: Context): Context {\n return ctx.world === null ? { ...ctx, world: worldThing(machine.world) } : ctx;\n}\n\n/**\n * This function compiles a document into a plan. The ladder, the kinds and the parts are known after it. A plan\n * evaluates many times. A document that does not compile gives a plan that fails with the reason, when it evaluates.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, and a trace.\n * @returns The plan.\n */\nexport function prepare(machine: Machine, doc: unknown, options: PrepareOptions = {}): Plan {\n const c: Compiler = { machine, traced: options.trace === true, maxDepth: machine.maxDepth ?? 1000 };\n let root: { readonly code: Code; readonly run: RunCode };\n try {\n root = compileNode(c, doc, [], options.declaredType, 0);\n } catch (error) {\n const result = thrown(error, \"the compilation\");\n root = {\n code: () => result,\n run: function* () {\n return result;\n },\n };\n }\n const compiled: CompiledPart = { key: \"\", path: [], code: root.code, run: root.run };\n return planOf(machine, c.traced, compiled);\n}\n\n/** This function makes the object of a plan. Its closures keep only the machine and the compiled root. */\nfunction planOf(machine: Machine, traced: boolean, root: CompiledPart): Plan {\n return {\n machine,\n traced,\n root,\n evaluate(context: Context = makeContext(), evalOptions?: EvalOptions): Result {\n const s = new Session(machine, false, traced, undefined, undefined, evalOptions?.effects);\n return root.code(rootContext(machine, context), s);\n },\n run(context: Context = makeContext(), runOptions: RunOptions = {}): Promise<Result> {\n const s = new Session(machine, true, traced, runOptions.perform, runOptions.signal, undefined);\n return driveWaiting(root.run(rootContext(machine, context), s), runOptions.signal);\n },\n };\n}\n\n/**\n * This function makes a cache of plans for one machine. A document object compiles one time. Use it only for\n * documents that do not change after they are made.\n *\n * @param machine - The machine.\n * @param options - The options of each compilation.\n * @returns A function that gives the plan of a document.\n */\nexport function planner(machine: Machine, options: PrepareOptions = {}): (doc: unknown) => Plan {\n const objects = new WeakMap<object, Plan>();\n const values = new Map<unknown, Plan>();\n return (doc) => {\n if (typeof doc === \"object\" && doc !== null) {\n let plan = objects.get(doc);\n if (plan === undefined) {\n plan = prepare(machine, doc, options);\n objects.set(doc, plan);\n }\n return plan;\n }\n let plan = values.get(doc);\n if (plan === undefined) {\n plan = prepare(machine, doc, options);\n if (values.size > 1000) values.clear();\n values.set(doc, plan);\n }\n return plan;\n };\n}\n\nfunction record(s: Session, result: Result): Run {\n const root = s.holder?.children[0];\n if (root === undefined) throw new Error(\"The evaluation made no trace.\");\n return { result, trace: root as TraceNode, effects: s.effects, time: s.tick };\n}\n\n/**\n * This function evaluates a document, and records each evaluation in a trace.\n *\n * The verb `eval` goes up the ladder for each document. The kind of the document tells where its parts are. The\n * evaluator gets each part sealed: it can evaluate the part, and it cannot read its value. A failure gives an error\n * value, and the function does not throw. An effect is recorded in its order, and nothing does it.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param context - The names and the capabilities at the root.\n * @param declaredType - The type of a bare root value.\n * @returns The result, the trace and the effects in their order.\n */\nexport function evaluate(machine: Machine, doc: unknown, context: Context = makeContext(), declaredType?: string): Run {\n const plan = prepare(machine, doc, { trace: true, ...(declaredType === undefined ? {} : { declaredType }) });\n const s = new Session(machine, false, true, undefined, undefined, undefined);\n const result = plan.root.code(rootContext(machine, context), s);\n return record(s, result);\n}\n\n/**\n * This function runs a document: an evaluation in which the host does each effect. A runner waits for its\n * parts and for its effects, thus a step can read the result of the step before. The part of the run before the\n * first wait happens at once, in the call. The run records a trace.\n *\n * @param machine - The world, the evaluators and the runners.\n * @param doc - The document, as JSON.\n * @param context - The names and the capabilities at the root.\n * @param options - The host code that does the effects, the type of a bare root value, and a signal.\n * @returns The result, the trace and the effects in their order, when the run ends.\n */\nexport async function run(machine: Machine, doc: unknown, context: Context = makeContext(), options: RunOptions = {}): Promise<Run> {\n const plan = prepare(machine, doc, { trace: true, ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }) });\n const s = new Session(machine, true, true, options.perform, options.signal, undefined);\n const result = await driveWaiting(plan.root.run(rootContext(machine, context), s), options.signal);\n return record(s, result);\n}\n\n/**\n * This function finds a node of a trace by its path.\n *\n * @param trace - The root of the trace.\n * @param path - The keys from the root.\n * @returns The first evaluation at that path, or `undefined` when the document did not evaluate.\n */\nexport function nodeAt(trace: TraceNode, path: readonly Key[]): TraceNode | undefined {\n const want = path.map(String);\n let node: TraceNode | undefined = trace;\n let at = 0;\n while (node !== undefined && at < want.length) {\n const here: TraceNode = node;\n node = here.children.find((child) => {\n const tail = child.path.slice(here.path.length);\n return tail.length > 0 && tail.every((key, index) => key === want[at + index]);\n });\n if (node !== undefined) at += node.path.length - here.path.length;\n }\n return node;\n}\n\n/**\n * This function lists the nodes of a trace in the order of their start.\n *\n * @param trace - The root of the trace.\n * @returns Each node, the root first.\n */\nexport function flatten(trace: TraceNode): readonly TraceNode[] {\n const out: TraceNode[] = [];\n const stack: TraceNode[] = [trace];\n while (stack.length > 0) {\n const node = stack.pop() as TraceNode;\n out.push(node);\n for (let index = node.children.length - 1; index >= 0; index -= 1) stack.push(node.children[index] as TraceNode);\n }\n return out.sort((a, b) => a.enter - b.enter);\n}\n\n/**\n * This function lists the errors of a trace: each node whose result is an error and whose parts did not fail\n * the same way. These nodes are where each error started.\n *\n * @param trace - The root of the trace.\n * @returns The errors, in the order of their start.\n */\nexport function failures(trace: TraceNode): readonly EvalError[] {\n return flatten(trace)\n .filter((node) => !node.result.ok && !node.children.some((child) => !child.result.ok && child.result.error === (node.result as { error: EvalError }).error))\n .map((node) => (node.result as { readonly error: EvalError }).error);\n}\n\n/** The type of a document as a reference: re-exported for the compilers. */\nexport type { TypeRef };\n","import { type Json, type Key, field, isRecord } from \"./doc.ts\";\nimport { type Context, type Evaluator, type Machine, type Part, type Result, type RunPart, type Runner, type Steps, fail, ok } from \"./evaluate.ts\";\nimport { type HostThing, type Thing, type Walker, THING, isHostThing, valueOfThing } from \"./deref.ts\";\nimport type { World } from \"./ladder.ts\";\n\n/**\n * The world of the examples: small kinds for numbers, lists, conditions, names, sequences and effects.\n * Each kind names an evaluator for `eval` and a view for `view`. The site draws each document with its view.\n */\nexport const STD_WORLD: World = {\n kinds: {\n number: { verbs: { eval: \"data.number\", view: \"view.value\" }, summary: \"A number. Its value is the result.\" },\n text: { verbs: { eval: \"data.text\", view: \"view.value\" }, summary: \"A text. Its value is the result.\" },\n bool: { verbs: { eval: \"data.bool\", view: \"view.value\" }, summary: \"A truth value. Its value is the result.\" },\n add: {\n verbs: { eval: \"math.add\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"The sum of its parts. A bare number in its list gets the type number.\",\n },\n multiply: {\n verbs: { eval: \"math.multiply\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"The product of its parts.\",\n },\n greater: {\n verbs: { eval: \"math.greater\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"number\" },\n summary: \"True when the first part is greater than the second part.\",\n },\n list: { verbs: { eval: \"list.all\", view: \"view.op\" }, parts: { shape: \"list\" }, summary: \"The results of its parts, as a list.\" },\n if: {\n verbs: { eval: \"control.if\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"test\", \"then\", \"else\"] },\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n ref: {\n verbs: { eval: \"ref.resolve\", view: \"view.ref\" },\n summary: \"A path from a root of the context. Each step goes up the ladder of the verb deref.\",\n },\n nearest: {\n verbs: { step: \"walk.nearest\", view: \"view.card\" },\n summary: \"A step of a path: it follows a key again and again, until it reaches a node of a type.\",\n },\n panel: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n summary: \"A node of a tree. Its parts see it as self, and each node links to its parent.\",\n },\n box: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n summary: \"A node of a tree, as panel. A formula in a box can read the parent of the box.\",\n },\n math: {\n kinds: {\n sum: { type: \"ref\", value: [\"world\", \"add\"] },\n product: { type: \"ref\", value: [\"world\", \"multiply\"] },\n },\n },\n seq: {\n verbs: { eval: \"control.seq\", view: \"view.seq\" },\n parts: { shape: \"list\" },\n scope: [\n { names: { headers: true }, in: [[\"*\"]], sequential: true },\n { names: { fixed: [\"last\"] }, in: [[\"*\"]], sequential: true },\n ],\n summary: \"Its steps, in order. The result of a named step is a name for the later steps.\",\n },\n pure: {\n verbs: { eval: \"control.pure\", view: \"view.op\" },\n parts: { shape: \"list\" },\n caps: [{ rule: \"mask\" }],\n summary: \"It evaluates its part without capabilities, thus an effect in it fails.\",\n },\n log: {\n verbs: { eval: \"effect.log\", view: \"view.op\" },\n parts: { shape: \"list\", of: \"text\" },\n side: \"run\",\n effects: [\"log\"],\n summary: \"It writes the result of its part to the log. This is an effect.\",\n },\n write: {\n verbs: { eval: \"effect.write\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"value\"] },\n side: \"run\",\n effects: [\"write\"],\n summary: \"It writes the result of its part to the store, at its key. This is an effect.\",\n },\n },\n defaults: { view: \"view.card\" },\n};\n\nfunction isNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/** This function evaluates each part, collects the errors, and gives the values when no part failed. */\nfunction allValues(results: readonly Result[]): { readonly values: readonly unknown[] } | { readonly error: Result } {\n const errors = results.filter((result) => !result.ok);\n const first = errors[0];\n if (first !== undefined && errors.length === 1) return { error: first };\n if (errors.length > 1) return { error: fail(\"#ARGS\", `${errors.length} parts failed.`) };\n return { values: results.map((result) => (result.ok ? result.value : null)) };\n}\n\nfunction numbers(values: readonly unknown[], kind: string): readonly number[] | Result {\n const bad = values.findIndex((value) => !isNumber(value));\n if (bad !== -1) return fail(\"#VALUE!\", `Part ${bad} of ${kind} is not a number.`);\n return values.filter(isNumber);\n}\n\nfunction dataOf(type: \"number\" | \"string\" | \"boolean\"): Evaluator {\n return ({ data }) =>\n typeof data === type && (type !== \"number\" || isNumber(data))\n ? ok(data)\n : fail(\"#VALUE!\", `The value must be a ${type === \"string\" ? \"text\" : type}.`);\n}\n\n/** The code of the evaluators of the standard world, by name. */\nexport const STD_EVALUATORS: Readonly<Record<string, Evaluator>> = {\n \"data.number\": dataOf(\"number\"),\n \"data.text\": dataOf(\"string\"),\n \"data.bool\": dataOf(\"boolean\"),\n \"math.add\": ({ parts }) => {\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"add\");\n return Array.isArray(values) ? ok(values.reduce((sum, value) => sum + value, 0)) : (values as Result);\n },\n \"math.multiply\": ({ parts }) => {\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"multiply\");\n return Array.isArray(values) ? ok(values.reduce((product, value) => product * value, 1)) : (values as Result);\n },\n \"math.greater\": ({ parts }) => {\n if (parts.length !== 2) return fail(\"#VALUE!\", \"greater needs exactly two parts.\");\n const all = allValues(parts.map((part) => part.evaluate()));\n if (\"error\" in all) return all.error;\n const values = numbers(all.values, \"greater\");\n if (!Array.isArray(values)) return values as Result;\n const [a, b] = values as readonly number[];\n return ok((a ?? 0) > (b ?? 0));\n },\n \"ref.resolve\": ({ data, resolve }) => {\n if (!Array.isArray(data) || data.length === 0) {\n return fail(\"#VALUE!\", \"The value of ref is a path: a list that starts with a root, for example [\\\"names\\\", \\\"a\\\"].\");\n }\n const found = resolve(data as readonly Json[]);\n return found.ok ? ok(valueOfThing(found.thing)) : fail(found.code, found.reason);\n },\n \"tree.node\": (input) => treeNode(input.parts, input.context, input.kind),\n};\n\n/**\n * This function evaluates a node of a tree. The node is a host thing. A step `parent` reaches the node that holds\n * it. A step with the name of a part evaluates that part on demand, one time. Each part sees the node as self.\n */\nfunction treeNode(parts: readonly Part[], context: Context, type: string): Result {\n const memo = new Map<string, Result>();\n const read = (key: string): Result | undefined => {\n const known = memo.get(key);\n if (known !== undefined) return known;\n const part = parts.find((item) => item.key === key);\n if (part === undefined) return undefined;\n const result = part.evaluate({ ...context, self: me });\n memo.set(key, result);\n return result;\n };\n const me: HostThing & { readonly type: string } = {\n [THING]: true,\n type,\n label: `node ${type}`,\n deref(key: Key): Thing | undefined {\n if (key === \"parent\") return context.self;\n if (key === \"type\") return type;\n const result = read(String(key));\n return result?.ok === true ? result.value : undefined;\n },\n toJson(): unknown {\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key);\n out[part.key] = result?.ok === true ? result.value : null;\n }\n return out;\n },\n };\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key);\n if (result === undefined) continue;\n if (!result.ok) return result;\n out[part.key] = result.value;\n }\n return ok(out);\n}\n\n/** The options of a walker `nearest`. */\nexport interface NearestOptions {\n /**\n * This function tells if a node has the wanted type. The default compares the field `type` of a host thing.\n *\n * @param node - The node that the walk reached.\n * @param wanted - The type that the step document asks for.\n * @returns `true` when the node has the type.\n */\n readonly matches?: (node: Thing, wanted: Json | undefined) => boolean;\n /** The most hops of one walk. The default is 256. */\n readonly maxHops?: number;\n}\n\nfunction hostType(node: Thing, wanted: Json | undefined): boolean {\n return isHostThing(node) && (node as { readonly type?: unknown }).type === wanted;\n}\n\n/**\n * This function makes a walker `nearest`. The walker follows a key (the default is `parent`) until the node that it\n * reaches has the wanted type. With `self: true`, the node where the walk starts is the first candidate. A node\n * without that key ends the walk with an error.\n *\n * @param options - The test of a type and the most hops.\n * @returns The walker.\n */\nexport function nearestWalker(options: NearestOptions = {}): Walker {\n const matches = options.matches ?? hostType;\n const maxHops = options.maxHops ?? 256;\n return ({ data, here, deref }) => {\n const follow = isRecord(data) && typeof field(data, \"follow\") === \"string\" ? String(field(data, \"follow\")) : \"parent\";\n const wanted = isRecord(data) ? field(data, \"type\") : undefined;\n const fromSelf = isRecord(data) && field(data, \"self\") === true;\n let at: Thing | undefined = here;\n for (let hops = 0; hops < maxHops; hops += 1) {\n if (hops > 0 || !fromSelf) at = at === undefined || at === null ? undefined : deref(at, follow);\n if (at === undefined || at === null) return { ok: false, reason: `No node of the type ${String(wanted)} is on the way.` };\n if (matches(at, wanted)) return { ok: true, thing: at };\n }\n return { ok: false, reason: \"The walk is too long.\" };\n };\n}\n\nconst nearest: Walker = nearestWalker();\n\n/** The walkers of the standard world, by name. */\nexport const STD_WALKERS: Readonly<Record<string, Walker>> = { \"walk.nearest\": nearest };\n\n/** This function evaluates parts one after the other, and stops at the first error. */\nfunction* inOrder(parts: readonly RunPart[]): Generator<Promise<unknown>, { readonly values: readonly unknown[] } | { readonly error: Result }, unknown> {\n const values: unknown[] = [];\n for (const part of parts) {\n const result = yield* part.evaluate();\n if (!result.ok) return { error: result };\n values.push(result.value);\n }\n return { values };\n}\n\n/**\n * The runners of the standard world, by name: the kinds that can hold effects. Each one evaluates its parts in\n * order. In a run, an effect ends before the next step starts.\n */\nexport const STD_RUNNERS: Readonly<Record<string, Runner>> = {\n \"control.seq\": function* ({ parts, context }): Steps {\n let names: Record<string, unknown> = { ...context.names };\n let last: unknown = null;\n for (const part of parts) {\n const result = yield* part.evaluate({ ...context, names });\n if (!result.ok) return result;\n names = { ...names, last: result.value };\n if (part.name !== undefined) names = { ...names, [part.name]: result.value };\n last = result.value;\n }\n return ok(last);\n },\n // The contract of pure masks the capabilities of its part, and the kernel applies it. Thus the runner does not.\n \"control.pure\": function* ({ parts }) {\n const only = parts[0];\n if (only === undefined) return fail(\"#VALUE!\", \"pure needs one part.\");\n return yield* only.evaluate();\n },\n \"control.if\": function* ({ parts }) {\n const test = parts.find((part) => part.key === \"test\");\n if (test === undefined) return fail(\"#VALUE!\", \"if needs a test.\");\n const chosen = yield* test.evaluate();\n if (!chosen.ok) return chosen;\n if (typeof chosen.value !== \"boolean\") return fail(\"#VALUE!\", \"The test of if must give a truth value.\");\n const branch = parts.find((part) => part.key === (chosen.value === true ? \"then\" : \"else\"));\n return branch === undefined ? ok(null) : yield* branch.evaluate();\n },\n \"list.all\": function* ({ parts }) {\n const all = yield* inOrder(parts);\n return \"error\" in all ? all.error : ok(all.values);\n },\n \"effect.log\": function* ({ parts, effect }) {\n const all = yield* inOrder(parts);\n if (\"error\" in all) return all.error;\n return yield* effect(\"log\", all.values.length === 1 ? (all.values[0] ?? null) : all.values);\n },\n \"effect.write\": function* ({ parts, data, effect }) {\n const key = isRecord(data) ? field(data, \"key\") : undefined;\n if (typeof key !== \"string\") return fail(\"#VALUE!\", \"write needs a text key.\");\n const value = parts.find((part) => part.key === \"value\");\n if (value === undefined) return fail(\"#VALUE!\", \"write needs a value.\");\n const result = yield* value.evaluate();\n if (!result.ok) return result;\n return yield* effect(\"write\", { key, value: result.value });\n },\n};\n\n/** The machine of the examples: the standard world, its evaluators, its runners and its walkers. */\nexport const STD_MACHINE: Machine = { world: STD_WORLD, evaluators: STD_EVALUATORS, runners: STD_RUNNERS, walkers: STD_WALKERS };\n\n/** The capabilities of the examples at the root: the two effects of the standard world. */\nexport const STD_CAPS: readonly string[] = [\"log\", \"write\"];\n","/** One step of a sequence: its name, the names of the earlier steps that it reads, and if it has an effect. */\nexport interface StepSpec {\n readonly id: string;\n readonly reads: readonly string[];\n readonly effect: boolean;\n}\n\n/** An edge from a step that must come first to a step that must come after it. */\nexport type Edge = readonly [before: string, after: string];\n\n/** A reference that a sequence cannot resolve. */\nexport interface OrderProblem {\n readonly step: string;\n readonly reads: string;\n /** `unknown-name`: no step has this name. `read-before-defined`: the step with this name comes later. */\n readonly problem: \"unknown-name\" | \"read-before-defined\";\n}\n\n/**\n * This function finds the references that a sequence cannot resolve. A step can read only the steps before it.\n *\n * @param steps - The steps, in the written order.\n * @returns One problem for each bad reference, in the written order.\n */\nexport function checkSteps(steps: readonly StepSpec[]): readonly OrderProblem[] {\n const problems: OrderProblem[] = [];\n steps.forEach((step, index) => {\n for (const name of step.reads) {\n const at = steps.findIndex((other) => other.id === name);\n if (at === -1) problems.push({ step: step.id, reads: name, problem: \"unknown-name\" });\n else if (at >= index) problems.push({ step: step.id, reads: name, problem: \"read-before-defined\" });\n }\n });\n return problems;\n}\n\n/**\n * This function gives the data edges: a step comes after each earlier step that it reads.\n *\n * @param steps - The steps, in the written order.\n * @returns The edges. A bad reference gives no edge.\n */\nexport function dataEdges(steps: readonly StepSpec[]): readonly Edge[] {\n const edges: Edge[] = [];\n steps.forEach((step, index) => {\n for (const name of step.reads) {\n const at = steps.findIndex((other) => other.id === name);\n if (at !== -1 && at < index) edges.push([name, step.id]);\n }\n });\n return edges;\n}\n\n/**\n * This function gives the effect edges: each step with an effect comes after the previous step with an effect.\n * Effects keep their written order. Steps without an effect get no effect edge.\n *\n * @param steps - The steps, in the written order.\n * @returns The edges, one for each pair of consecutive effect steps.\n */\nexport function effectEdges(steps: readonly StepSpec[]): readonly Edge[] {\n const edges: Edge[] = [];\n let previous: string | undefined;\n for (const step of steps) {\n if (!step.effect) continue;\n if (previous !== undefined) edges.push([previous, step.id]);\n previous = step.id;\n }\n return edges;\n}\n\n/**\n * This function tells if an order of the steps gives the same meaning as the written order.\n * The order must contain each step one time, and it must obey the data edges and the effect edges.\n *\n * @param steps - The steps, in the written order.\n * @param order - The names of the steps in the order to examine.\n * @returns `true` when the order is permitted.\n */\nexport function isAllowedOrder(steps: readonly StepSpec[], order: readonly string[]): boolean {\n if (order.length !== steps.length) return false;\n if (new Set(order).size !== order.length) return false;\n if (!steps.every((step) => order.includes(step.id))) return false;\n const position = new Map(order.map((id, index) => [id, index] as const));\n return [...dataEdges(steps), ...effectEdges(steps)].every(\n ([before, after]) => (position.get(before) ?? 0) < (position.get(after) ?? 0),\n );\n}\n\n/**\n * This function puts the steps in layers. Each step goes one layer after the last step that it must follow.\n * The steps of one layer do not depend on each other, thus they can run at the same time.\n *\n * @param steps - The steps, in the written order.\n * @returns The layers, first to last. Each layer keeps the written order.\n */\nexport function layers(steps: readonly StepSpec[]): readonly (readonly string[])[] {\n const edges = [...dataEdges(steps), ...effectEdges(steps)];\n const depth = new Map<string, number>();\n for (const step of steps) {\n const before = edges.filter(([, after]) => after === step.id).map(([first]) => depth.get(first) ?? 0);\n depth.set(step.id, before.length === 0 ? 0 : Math.max(...before) + 1);\n }\n const result: string[][] = [];\n for (const step of steps) {\n const at = depth.get(step.id) ?? 0;\n while (result.length <= at) result.push([]);\n result[at]?.push(step.id);\n }\n return result;\n}\n","import type { Envelope } from \"./doc.ts\";\nimport type { Side } from \"./ladder.ts\";\n\n/** The parts of a context. A term can reach outside itself only through these parts. */\nexport const PARTS = [\"self\", \"names\", \"world\", \"event\", \"caps\"] as const;\n\n/** One part of a context. */\nexport type Part = (typeof PARTS)[number];\n\n/** The description of one part of a context. */\nexport interface PartInfo {\n readonly part: Part;\n readonly title: string;\n /** What a reference through this part reaches. */\n readonly reaches: string;\n /** The direction in which a reference through this part goes. */\n readonly direction: string;\n}\n\n/** The descriptions of the parts, in the order of `PARTS`. */\nexport const PART_INFO: readonly PartInfo[] = [\n {\n part: \"self\",\n title: \"Self\",\n reaches: \"A position in a structure: the node itself, its parent, its children or its siblings.\",\n direction: \"Any direction that a move permits: up, down or to the side.\",\n },\n {\n part: \"names\",\n title: \"Names\",\n reaches: \"The values that a binding gives: a let, a parameter, or the result of an earlier step.\",\n direction: \"Back, to the place where the program binds the name.\",\n },\n\n {\n part: \"world\",\n title: \"World\",\n reaches: \"The stored documents and collections, by an absolute ID or by a query.\",\n direction: \"Out, to the store.\",\n },\n {\n part: \"event\",\n title: \"Event\",\n reaches: \"The trigger of a run: the event and its values.\",\n direction: \"From the past, to the run that the event starts.\",\n },\n {\n part: \"caps\",\n title: \"Capabilities\",\n reaches: \"The effects that a term can cause. A part of the term gets the same set or a smaller set.\",\n direction: \"Down, and only smaller.\",\n },\n];\n\n/**\n * What a construct gives the parts of its body, for one part of the context.\n *\n * - `same`: the parts get the same value.\n * - `extends`: the parts get the value with more names.\n * - `moves`: the parts get a new position.\n * - `narrows`: the parts get a smaller set.\n * - `sets`: the parts get a new value.\n * - `none`: the parts get nothing.\n */\nexport type Give = \"same\" | \"extends\" | \"moves\" | \"narrows\" | \"sets\" | \"none\";\n\n/** How a construct uses one part of the context. */\nexport interface Use {\n readonly reads: boolean;\n readonly gives: Give;\n readonly note: string;\n}\n\n/** A construct of a language, and how it uses each part of the context. */\nexport interface Construct {\n readonly id: string;\n readonly title: string;\n readonly side: Side;\n readonly summary: string;\n readonly example: Envelope;\n readonly uses: Readonly<Record<Part, Use>>;\n}\n\nconst NONE: Use = { reads: false, gives: \"none\", note: \"It does not use this part.\" };\n\n/** Six constructs that show the range of the context. */\nexport const CONSTRUCTS: readonly Construct[] = [\n {\n id: \"formula\",\n title: \"Formula\",\n side: \"derive\",\n summary: \"A pure formula that gives a value at one position of a structure.\",\n example: {\n type: \"let\",\n value: {\n bind: { gap: 8 },\n body: { type: [\"ops\", \"add\"], value: [{ type: \"ref\", value: [\"self\", \"parent\", \"width\"] }, { type: \"ref\", value: [\"names\", \"gap\"] }] },\n },\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"A let binds names for its body.\" },\n self: { reads: true, gives: \"moves\", note: \"A move reads the parent. An axis moves self to each target.\" },\n world: NONE,\n event: NONE,\n caps: { reads: false, gives: \"none\", note: \"A formula causes no effect, thus its parts get no capability.\" },\n },\n },\n {\n id: \"sequence\",\n title: \"Sequence\",\n side: \"run\",\n summary: \"A list of steps. A step can read the result of each earlier step by its name.\",\n example: {\n type: \"seq\",\n value: [\n { type: [\"store\", \"find\"], value: { match: { board: \"b1\" } }, name: \"cards\" },\n { type: [\"store\", \"patch\"], value: { ids: { type: \"ref\", value: [\"names\", \"cards\", \"ids\"] }, set: { done: true } } },\n ],\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"The result of each step is a name for the later steps.\" },\n self: NONE,\n world: { reads: true, gives: \"same\", note: \"A step reads and writes the store through a procedure.\" },\n event: { reads: false, gives: \"same\", note: \"The steps get the event of the run without a change.\" },\n caps: { reads: true, gives: \"narrows\", note: \"A nested call gets the same capabilities or fewer.\" },\n },\n },\n {\n id: \"node\",\n title: \"Tree node\",\n side: \"derive\",\n summary: \"A node of a document tree. Its data and its box go down to its children.\",\n example: {\n type: \"node\",\n value: { data: { title: \"Notes\" }, children: [{ type: \"text\", value: { type: \"ref\", value: [\"names\", \"title\"] } }] },\n },\n uses: {\n names: { reads: true, gives: \"extends\", note: \"The data of the node becomes a name for its children.\" },\n self: { reads: true, gives: \"moves\", note: \"Each child becomes self for its own part.\" },\n world: { reads: true, gives: \"same\", note: \"A node can show stored documents.\" },\n event: NONE,\n caps: NONE,\n },\n },\n {\n id: \"rule\",\n title: \"Layout rule\",\n side: \"derive\",\n summary: \"A rule that gives the box of a child from the box of its parent.\",\n example: { type: [\"layouts\", \"stack\"], value: { gap: 8 } },\n uses: {\n names: { reads: true, gives: \"none\", note: \"The rule reads its parameters.\" },\n self: { reads: true, gives: \"none\", note: \"The rule reads the box of the parent and the key of the child.\" },\n world: NONE,\n event: NONE,\n caps: NONE,\n },\n },\n {\n id: \"handler\",\n title: \"Event handler\",\n side: \"run\",\n summary: \"A run that an event starts. It holds a sequence as data until the event comes.\",\n example: {\n type: \"on\",\n value: {\n event: \"click\",\n run: { type: \"seq\", value: [{ type: [\"card\", \"toggle\"], value: { id: { type: \"ref\", value: [\"event\", \"target\"] } } }] },\n },\n },\n uses: {\n names: { reads: true, gives: \"same\", note: \"The handler reads the names of its place.\" },\n self: { reads: true, gives: \"same\", note: \"The handler knows the node that got the event.\" },\n world: { reads: true, gives: \"same\", note: \"The run reads and writes the store.\" },\n event: { reads: true, gives: \"sets\", note: \"The handler gives the event to its run.\" },\n caps: { reads: true, gives: \"narrows\", note: \"The run gets only the capabilities of the handler.\" },\n },\n },\n {\n id: \"query\",\n title: \"Query\",\n side: \"derive\",\n summary: \"A selection of stored documents. A storage adapter decides where it runs.\",\n example: { type: \"query\", value: { collection: \"cards\", match: { board: { type: \"ref\", value: [\"names\", \"board\"] } } } },\n uses: {\n names: { reads: true, gives: \"none\", note: \"The query reads its parameters.\" },\n self: NONE,\n world: { reads: true, gives: \"none\", note: \"The query reads one collection.\" },\n event: NONE,\n caps: NONE,\n },\n },\n];\n","import { type Envelope, type Json, type Key, isEnvelope, isKey, isRecord, typeName } from \"./doc.ts\";\nimport { type Kind, type NamesSource, type ScopeRule, type World, lookupKind } from \"./world.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type PartSlot, pathMatches, splitParts } from \"./parts.ts\";\nimport { type Cap, type Root, ROOTS, isRef } from \"./deref.ts\";\nimport type { ErrorCode } from \"./errors.ts\";\nimport { type Machine, partCaps, permits } from \"./evaluate.ts\";\n\n/** One document that a walk visits. */\nexport interface DocVisit {\n /** The keys from the root document to this document, through the parts. It is the place of an error. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to this document. A change at this path changes this document. */\n readonly at: readonly Key[];\n /** The visit of the document that holds this document as a part. The root has none. */\n readonly parent?: DocVisit | undefined;\n /** The keys from the value of the parent to this document: the path of the part. The root has none. */\n readonly slot: readonly Key[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** `true` when the type came from the position and not from an envelope. */\n readonly declared: boolean;\n /** The kind of the document, when the world has it. */\n readonly kind?: Kind | undefined;\n /** The keys of the kind after each alias. */\n readonly typePath?: readonly Key[] | undefined;\n /** The number of documents around this document. The root has 0. */\n readonly depth: number;\n /** The names that the kinds around this document bind for it. */\n readonly names: ReadonlySet<string>;\n /** The names that a sequence around this document binds only for the parts after it. */\n readonly later: ReadonlySet<string>;\n /** `true` when the position of the document declares an address: a reference there is not a read of a value. */\n readonly address?: true | undefined;\n /**\n * The capabilities of the document: the capabilities of the walk, narrowed by the capability rules of the kinds\n * around it (`Kind.caps`). A walk without capabilities gives none here.\n */\n readonly caps?: readonly Cap[] | undefined;\n}\n\n/** A position that a walk cannot read as a document. */\nexport interface WalkProblem {\n /** The keys from the root document to the document with the problem. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to the value with the problem. */\n readonly at: readonly Key[];\n readonly code: \"#PART?\" | \"#VALUE!\";\n readonly reason: string;\n}\n\n/** The options of a walk. */\nexport interface WalkOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The names that the host binds at the root. */\n readonly names?: readonly string[];\n /** The capabilities at the root. With them, each visit gets the capabilities of its document. */\n readonly caps?: readonly Cap[];\n /**\n * This function gets each position that is not a document.\n *\n * @param problem - The position and the reason.\n */\n readonly problem?: (problem: WalkProblem) => void;\n}\n\nfunction valueAt(value: unknown, path: readonly Key[]): unknown {\n let here: unknown = value;\n for (const key of path) {\n if (Array.isArray(here)) here = here[Number(key)];\n else if (isRecord(here) && Object.hasOwn(here, String(key))) here = here[String(key)];\n else return undefined;\n }\n return here;\n}\n\nfunction headerName(item: Json): string | undefined {\n return isEnvelope(item) && typeof (item as { readonly name?: unknown }).name === \"string\" ? (item as { readonly name: string }).name : undefined;\n}\n\nfunction namesOf(source: NamesSource, value: unknown, covered: readonly PartSlot[]): readonly string[] {\n if (\"fixed\" in source) return source.fixed;\n if (\"keysAt\" in source) {\n const at = valueAt(value, source.keysAt);\n return isRecord(at) ? Object.keys(at) : [];\n }\n if (\"listAt\" in source) {\n const at = valueAt(value, source.listAt);\n return Array.isArray(at) ? (at as readonly unknown[]).filter((item): item is string => typeof item === \"string\") : [];\n }\n if (\"textAt\" in source) {\n const at = valueAt(value, source.textAt);\n if (typeof at === \"string\") return [at];\n return source.otherwise === undefined ? [] : [source.otherwise];\n }\n return covered.map((slot) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n}\n\n/** The names that the scope rules of a kind give each part, and the names that only later parts see. */\nfunction scopesOf(rules: readonly ScopeRule[] | undefined, value: unknown, slots: readonly PartSlot[]): { readonly sees: readonly (readonly string[])[]; readonly later: readonly (readonly string[])[] } {\n const sees: string[][] = slots.map(() => []);\n const later: string[][] = slots.map(() => []);\n for (const rule of rules ?? []) {\n const covered = slots.map((slot, index) => ({ slot, index })).filter(({ slot }) => rule.in.some((pattern) => pathMatches(slot.path, pattern)));\n if (rule.sequential !== true) {\n const names = namesOf(rule.names, value, covered.map(({ slot }) => slot));\n for (const { index } of covered) sees[index]?.push(...names);\n continue;\n }\n if (\"headers\" in rule.names) {\n covered.forEach(({ index }, position) => {\n const before = covered.slice(0, position).map(({ slot }) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n const after = covered.slice(position).map(({ slot }) => headerName(slot.item)).filter((name): name is string => name !== undefined);\n sees[index]?.push(...before);\n later[index]?.push(...after);\n });\n continue;\n }\n const names = namesOf(rule.names, value, covered.map(({ slot }) => slot));\n covered.forEach(({ index }, position) => {\n if (position > 0) sees[index]?.push(...names);\n else later[index]?.push(...names);\n });\n }\n return { sees, later };\n}\n\n/** The names of a walk without names. A walk does not change a set at any time: it makes a new set to add names. */\nconst NO_NAMES: ReadonlySet<string> = new Set();\n\n/** This function gives the options of a walk without the names of the host. */\nfunction withoutNames(options: WalkOptions): WalkOptions {\n const { names: _host, ...rest } = options;\n return rest;\n}\n\n/** A path that shares its start with other paths: the keys of one step, and the path before them. */\ninterface Trail {\n readonly up: Trail | undefined;\n readonly keys: readonly Key[];\n full?: readonly Key[];\n}\n\n/** This function gives the keys of a trail, from its start. It keeps the result in the trail. */\nfunction keysOf(trail: Trail | undefined): readonly Key[] {\n if (trail === undefined) return [];\n if (trail.full !== undefined) return trail.full;\n const steps: Trail[] = [];\n let here: Trail | undefined = trail;\n while (here !== undefined && here.full === undefined) {\n steps.push(here);\n here = here.up;\n }\n const keys: Key[] = here?.full === undefined ? [] : [...here.full];\n for (let index = steps.length - 1; index >= 0; index -= 1) for (const key of (steps[index] as Trail).keys) keys.push(key);\n trail.full = keys;\n return keys;\n}\n\n/** A visit with its paths as trails. It makes the keys of a path only when a reader asks for them. */\nclass Visit implements DocVisit {\n readonly #place: Trail | undefined;\n readonly #at: Trail | undefined;\n\n constructor(\n place: Trail | undefined,\n at: Trail | undefined,\n readonly doc: Envelope,\n readonly declared: boolean,\n readonly depth: number,\n readonly names: ReadonlySet<string>,\n readonly later: ReadonlySet<string>,\n readonly slot: readonly Key[],\n readonly parent: DocVisit | undefined,\n readonly kind: Kind | undefined,\n readonly typePath: readonly Key[] | undefined,\n readonly address: true | undefined,\n readonly caps: readonly Cap[] | undefined,\n ) {\n this.#place = place;\n this.#at = at;\n }\n\n get place(): readonly Key[] {\n return keysOf(this.#place);\n }\n\n get at(): readonly Key[] {\n return keysOf(this.#at);\n }\n}\n\n/**\n * This function visits each document of a document: the root and each part at each depth, by the contracts of the\n * kinds. A part of a kind that the world does not have is not visited. With capabilities in the options, the walk\n * narrows them for each part by the rules of its kind, as a run does. The walk uses no stack of the host for the\n * depth, thus a deep document cannot overflow it. The time and the memory of a walk are linear in the size of the\n * document. A visit makes the keys of its place and of its path only when a reader asks for them.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param visit - The function that gets each document. It gives `\"skip\"` to not visit the parts of a document.\n * @param options - The type of a bare root value, the names, the capabilities and a function for the problems.\n */\nexport function walk(world: World, doc: unknown, visit: (visit: DocVisit) => void | \"skip\", options: WalkOptions = {}): void {\n interface Item {\n readonly value: unknown;\n readonly place: Trail | undefined;\n readonly at: Trail | undefined;\n readonly declared: string | undefined;\n readonly depth: number;\n readonly names: ReadonlySet<string>;\n readonly later: ReadonlySet<string>;\n readonly address: boolean;\n readonly slot: readonly Key[];\n readonly parent: DocVisit | undefined;\n readonly caps: readonly Cap[] | undefined;\n }\n const stack: Item[] = [\n {\n value: doc,\n place: undefined,\n at: undefined,\n declared: options.declaredType,\n depth: 0,\n names: options.names === undefined || options.names.length === 0 ? NO_NAMES : new Set(options.names),\n later: NO_NAMES,\n address: false,\n slot: [],\n parent: undefined,\n caps: options.caps,\n },\n ];\n while (stack.length > 0) {\n const item = stack.pop() as Item;\n const envelope = isEnvelope(item.value) ? (item.value as Envelope) : undefined;\n if (envelope === undefined && item.declared === undefined) {\n options.problem?.({ place: keysOf(item.place), at: keysOf(item.at), code: \"#PART?\", reason: \"The value has no envelope, and its position declares no type.\" });\n continue;\n }\n const doc: Envelope = envelope ?? { type: item.declared ?? \"?\", value: item.value as Json };\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n const here = new Visit(\n item.place,\n item.at,\n doc,\n envelope === undefined,\n item.depth,\n item.names,\n item.later,\n item.slot,\n item.parent,\n kind,\n found.ok ? found.path : undefined,\n item.address ? true : undefined,\n item.caps,\n );\n const answer = visit(here);\n if (answer === \"skip\" || kind === undefined) continue;\n const split = splitParts(kind.parts, doc.value);\n const base: Trail | undefined = envelope === undefined ? item.at : { up: item.at, keys: [\"value\"] };\n if (!split.ok) {\n const at = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n const where = keysOf({ up: base, keys: split.at });\n options.problem?.({ place: keysOf(item.place), at: where, code: \"#VALUE!\", reason: `${split.reason}${at} The kind is ${typeName(doc.type)}.` });\n continue;\n }\n const { sees, later } = scopesOf(kind.scope, doc.value, split.parts);\n for (let index = split.parts.length - 1; index >= 0; index -= 1) {\n const slot = split.parts[index] as PartSlot;\n const extra = sees[index] ?? [];\n const hidden = later[index] ?? [];\n stack.push({\n value: slot.item,\n place: slot.path.length === 0 ? item.place : { up: item.place, keys: slot.path },\n at: slot.path.length === 0 ? base : { up: base, keys: slot.path },\n declared: slot.of,\n depth: item.depth + 1,\n names: extra.length === 0 ? item.names : new Set([...item.names, ...extra]),\n later: hidden.length === 0 ? item.later : new Set([...item.later, ...hidden]),\n address: slot.address === true,\n slot: slot.path,\n parent: here,\n caps: item.caps === undefined || kind.caps === undefined ? item.caps : partCaps(kind.caps, slot.path, item.caps),\n });\n }\n }\n}\n\n/** One reference of a document. */\nexport interface RefUse {\n /** The visit of the reference document: its parent, its depth and the names that it sees. */\n readonly visit: DocVisit;\n /** The place of the reference document, through the parts. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to the reference document. */\n readonly at: readonly Key[];\n /** The path of the reference: its root and its steps. */\n readonly path: readonly Json[];\n readonly root: string;\n /** `false` when a kind around the reference binds its first name. A reference to another root is free. */\n readonly free: boolean;\n /** `true` when the reference is an address: its position declares it. An address does not read a value. */\n readonly address: boolean;\n}\n\n/**\n * This function finds each reference of a document: each document of the type `ref` that a walk reaches. A\n * reference to a name that a kind around it binds is not free. The others are what the document reads from\n * outside: its dependencies. When the kind `ref` has parts, the walk also finds the references in its step documents.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value. The names of the host do not change the result.\n * @returns The references, in the order of the document.\n */\nexport function refsOf(world: World, doc: unknown, options: WalkOptions = {}): readonly RefUse[] {\n const out: RefUse[] = [];\n // The walk gets no names of the host: a name that the host binds is a dependency, thus its reference is free.\n const rest: WalkOptions = options.names === undefined ? options : withoutNames(options);\n walk(\n world,\n doc,\n (v) => {\n if (!isRef(v.doc)) return undefined;\n const path = v.doc.value as readonly Json[];\n const root = typeof path[0] === \"string\" ? path[0] : \"\";\n const first = path[1];\n const bound = root === \"names\" && isKey(first) && v.names.has(String(first));\n // The place and the path of a reference are made only when a reader asks for them.\n const use = { path, root, free: !bound, address: v.address === true } as RefUse;\n Object.defineProperty(use, \"place\", { enumerable: true, get: () => v.place });\n Object.defineProperty(use, \"at\", { enumerable: true, get: () => v.at });\n Object.defineProperty(use, \"visit\", { enumerable: false, value: v });\n out.push(use);\n return undefined;\n },\n rest,\n );\n return out;\n}\n\nfunction setAt(value: unknown, path: readonly Key[], next: unknown): unknown {\n if (path.length === 0) return next;\n const [key, ...rest] = path as [Key, ...Key[]];\n if (Array.isArray(value)) {\n const copy = [...value];\n copy[Number(key)] = setAt(value[Number(key)], rest, next);\n return copy;\n }\n const record = (isRecord(value) ? value : {}) as Readonly<Record<string, unknown>>;\n const copy: Record<string, unknown> = {};\n for (const name of Object.keys(record)) Object.defineProperty(copy, name, { value: record[name], enumerable: true, writable: true, configurable: true });\n Object.defineProperty(copy, String(key), { value: setAt(record[String(key)], rest, next), enumerable: true, writable: true, configurable: true });\n return copy;\n}\n\n/**\n * This function changes the free references of a document. The document is not changed: the function gives a new\n * document that shares each part without a change.\n *\n * @param world - The world of the kinds.\n * @param doc - The document, as JSON.\n * @param change - The function that gives the new document of a reference, or `undefined` to keep it.\n * @param options - The type of a bare root value, and the names that the host binds at the root.\n * @returns The new document.\n */\nexport function mapRefs(world: World, doc: unknown, change: (use: RefUse) => unknown, options: WalkOptions = {}): unknown {\n let out = doc;\n for (const use of refsOf(world, doc, options)) {\n if (!use.free) continue;\n const next = change(use);\n if (next !== undefined) out = setAt(out, use.at, next);\n }\n return out;\n}\n\n/** A problem that a check finds before a document runs. */\nexport interface Issue {\n readonly code: ErrorCode;\n /** The keys from the root document to the document with the problem. */\n readonly place: readonly Key[];\n readonly reason: string;\n /** The keys from the root JSON value to the value with the problem. */\n readonly at?: readonly Key[];\n}\n\n/** The options of a check. */\nexport interface CheckOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The names that the host binds at the root. `\"any\"` does not check the names. The default is no names. */\n readonly names?: readonly string[] | \"any\";\n /**\n * The capabilities at the root. Without them, the check does not check the effects. The check narrows them for\n * each part by the capability rules of the kinds, as a run does.\n */\n readonly caps?: readonly Cap[];\n}\n\n/**\n * This function gives the reason of a `#CAP!`. When a kind around the document narrowed the capabilities, the\n * reason names the nearest such kind.\n */\nfunction capReason(v: DocVisit, kind: readonly Key[]): string {\n const text = kind.join(\".\");\n for (let up = v.parent; up !== undefined; up = up.parent) {\n if (up.caps !== undefined && permits(up.caps, kind)) {\n return `The capabilities do not permit the effect ${text} here. The kind ${typeName(up.doc.type)} around it narrows them for its parts.`;\n }\n }\n return `The capabilities do not permit the effect ${text}.`;\n}\n\n/**\n * This function checks a document before an evaluation, by the contracts of its kinds. It finds the problems\n * that an evaluation finds when it reaches them:\n *\n * - `#KIND?`: a kind that the world does not have.\n * - `#NOEVAL`: no evaluator.\n * - `#VALUE!`: a value without the shape of its kind.\n * - `#PART?`: a value without a type.\n * - `#DEPTH!`: too much nesting.\n * - `#REF!` and `#STEP?`: a bad path.\n * - `#NAME?`: a name that nothing binds.\n * - `#CAP!`: an effect that the capabilities of its document do not permit. A kind around the document can narrow them.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, the names of the host and the capabilities.\n * @returns The problems, in the order of the document.\n */\nexport function check(machine: Machine, doc: unknown, options: CheckOptions = {}): readonly Issue[] {\n const issues: Issue[] = [];\n const maxDepth = machine.maxDepth ?? 1000;\n const anyName = options.names === \"any\";\n const roots: readonly string[] = machine.roots ?? ROOTS;\n const has = (table: Readonly<Record<string, unknown>> | undefined, name: string): boolean => table !== undefined && Object.hasOwn(table, name);\n walk(\n machine.world,\n doc,\n (v) => {\n if (v.depth > maxDepth) {\n issues.push({ code: \"#DEPTH!\", place: v.place, reason: `The nesting is deeper than ${maxDepth} documents.`, at: v.at });\n return \"skip\";\n }\n const header = v.declared ? {} : v.doc;\n const answer = ask(machine.world, header, \"eval\", v.declared ? { declaredType: typeName(v.doc.type) } : {});\n if (answer.error === \"unknown-kind\") {\n issues.push({ code: \"#KIND?\", place: v.place, reason: `The world has no kind ${typeName(v.doc.type)}.`, at: v.at });\n return \"skip\";\n }\n const name = answer.evaluator;\n if (name === undefined || (!has(machine.evaluators, name) && !has(machine.runners, name))) {\n issues.push({ code: \"#NOEVAL\", place: v.place, reason: `No rung gives an evaluator for ${typeName(v.doc.type)}.`, at: v.at });\n }\n const caps = v.caps;\n if (caps !== undefined && v.kind?.effects !== undefined) {\n const kinds: readonly (readonly Key[])[] = v.kind.effects === \"type\" ? [v.typePath ?? []] : v.kind.effects.map((kind) => kind.split(\".\"));\n for (const kind of kinds) {\n if (!permits(caps, kind)) issues.push({ code: \"#CAP!\", place: v.place, reason: capReason(v, kind), at: v.at });\n }\n }\n const isPath = isRef(v.doc);\n if (!isPath && v.typePath?.length === 1 && v.typePath[0] === \"ref\") {\n issues.push({ code: \"#VALUE!\", place: v.place, reason: \"The value of ref is a path: a list that starts with a root.\", at: [...v.at, ...(v.declared ? [] : [\"value\"])] });\n }\n if (!isPath) return undefined;\n const path = v.doc.value as readonly Json[];\n const root = path[0];\n // The JSON path of a problem of a path goes to its step.\n const stepAt = (index: number): readonly Key[] => [...v.at, \"value\", ...(index < path.length ? [index] : [])];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) {\n issues.push({ code: \"#REF!\", place: v.place, reason: `A path starts with a root: ${ROOTS.join(\", \")}.`, at: stepAt(0) });\n return \"skip\";\n }\n if (!roots.includes(root)) {\n issues.push({ code: \"#REF!\", place: v.place, reason: `The root ${root} is not open here. The open roots are ${roots.join(\", \")}.`, at: stepAt(0) });\n }\n const first = path[1];\n if (root === (\"names\" as Root) && !anyName && isKey(first) && !v.names.has(String(first))) {\n const later = v.later.has(String(first));\n issues.push({\n code: \"#NAME?\",\n place: v.place,\n reason: later ? `The name ${String(first)} is bound by a later step.` : `Nothing binds the name ${String(first)}.`,\n at: stepAt(1),\n });\n }\n path.forEach((step, index) => {\n if (index === 0 || isKey(step)) return;\n const found = isEnvelope(step) ? lookupKind(machine.world, step.type) : undefined;\n const walker = found?.ok === true && Object.hasOwn(found.kind.verbs, \"step\") ? found.kind.verbs[\"step\"] : undefined;\n if (walker === undefined || !has(machine.walkers, walker)) {\n issues.push({ code: \"#STEP?\", place: v.place, reason: \"A step is a key, or a document of a kind with the verb step.\", at: stepAt(index) });\n }\n });\n // The step documents of the path are parts when the kind ref has a deep shape. The walk checks them too.\n return undefined;\n },\n {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(Array.isArray(options.names) ? { names: options.names } : {}),\n ...(options.caps === undefined ? {} : { caps: options.caps }),\n problem: (problem) => issues.push({ code: problem.code, place: problem.place, reason: problem.reason, at: problem.at }),\n },\n );\n return issues;\n}\n","import { type Json, isRecord } from \"./doc.ts\";\nimport type { Kind, WorldEntry } from \"./world.ts\";\nimport { type Context, type Resolution, valueOfThing } from \"./deref.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, thrown } from \"./errors.ts\";\nimport type { Code, CompileInput, CompiledEvaluator, CompiledPart, Evaluator, Machine } from \"./evaluate.ts\";\n\n/** An operation of a formula language: a function of the values of its arguments. */\nexport type OpFn = (...args: never[]) => unknown;\n\n/**\n * A lazy operation: it gets one function for each argument. It evaluates only the arguments that it needs, for\n * example a default for an error.\n */\nexport type LazyOp = (args: readonly (() => Result)[]) => Result;\n\n/** The code of an extension: it gives the value of the data of an extension document, in the context of the document. */\nexport type ExtFn = (data: Json, context: Context) => Result;\n\n/**\n * The rules of one formula language: its operations, and the rules that differ between languages.\n *\n * - `ops`: the operations of the namespace `ops`, by their name (the keys after `ops`, with dots between them).\n * - `lazy`: the operations that evaluate their arguments themselves.\n * - `ext`: the extensions of the namespace `ext`, by their name. The kit has `ext.undefined` and `ext.number`.\n * - `truthy`: the truth of a value for `if`, `and` and `or`. `undefined` is an error `#VALUE!`. The default\n * accepts only `true` and `false`.\n * - `otherwise`: the value of an `if` without `else`. The default is `null`. A profile with this key gives its value,\n * also `undefined`.\n * - `logic`: what `and` and `or` give: a truth value (the default), or the value that decided.\n * - `omit`: the errors that leave a field out of a `record`, as an absent value.\n * - `missing`: the values that a reference cannot give. Such a value gives `#N/A`.\n * - `check`: a check of the value of an operation, for example \"a number must be finite\".\n * - `combine`: the error of two or more failed parts of an operation, a `record` or a `list`. With it, each part\n * evaluates, and one failed part gives its own error. Without it, the first error stops the evaluation.\n */\nexport interface FormulaProfile {\n readonly ops?: Readonly<Record<string, OpFn>> | ((name: string) => OpFn | undefined);\n readonly lazy?: Readonly<Record<string, LazyOp>>;\n readonly ext?: Readonly<Record<string, ExtFn>>;\n readonly truthy?: (value: unknown) => boolean | undefined;\n readonly otherwise?: unknown;\n readonly logic?: \"boolean\" | \"value\";\n readonly omit?: (error: EvalError) => boolean;\n readonly missing?: (value: unknown) => boolean;\n readonly check?: (value: unknown, op: string) => Result | undefined;\n readonly combine?: (errors: readonly EvalError[]) => EvalError;\n}\n\n/** The mark of a field that the profile leaves out of a record. */\nconst SKIPPED: unique symbol = Symbol(\"skipped\");\n\n/** The value of a name whose binding failed. A reference to the name gives the error. */\nexport class Held {\n constructor(readonly error: EvalError) {}\n}\n\nconst CLOSURE: unique symbol = Symbol.for(\"coeval.closure\") as never;\n\n/** A function that the construct `fn` made. It throws a `Failure` when its body fails. */\nexport type Closure = ((...args: readonly unknown[]) => unknown) & { readonly [CLOSURE]: { readonly params: readonly string[] } };\n\n/**\n * This function tells if a value is a function that the construct `fn` made.\n *\n * @param value - The value.\n * @returns `true` for a closure.\n */\nexport function isClosure(value: unknown): value is Closure {\n return typeof value === \"function\" && (value as Partial<Closure>)[CLOSURE] !== undefined;\n}\n\n/** The standard extensions: the values that JSON cannot write. */\nexport const STD_EXT: Readonly<Record<string, ExtFn>> = {\n undefined: () => ok(undefined),\n number: (data) => {\n if (data === \"NaN\") return ok(Number.NaN);\n if (data === \"Infinity\") return ok(Number.POSITIVE_INFINITY);\n if (data === \"-Infinity\") return ok(Number.NEGATIVE_INFINITY);\n if (data === \"-0\") return ok(-0);\n return fail(\"#VALUE!\", \"The value of ext.number is NaN, Infinity, -Infinity or -0.\");\n },\n};\n\n/** The truth of a value in the rules of JavaScript: `0`, `\"\"`, `null`, `undefined` and `NaN` are false. */\nexport function jsTruthy(value: unknown): boolean {\n return Boolean(value);\n}\n\nfunction strictTruthy(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\n/**\n * This function sets an own data property. Only the key `__proto__` needs `defineProperty`: an assignment to it\n * changes the prototype. An assignment is faster for each other key of a new plain object.\n */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nfunction compiled(compile: (input: CompileInput) => Code): CompiledEvaluator {\n return { compile };\n}\n\n/** This function evaluates parts in order. It gives the value of each part, or the first error. */\nfunction valuesOf(parts: readonly CompiledPart[], ctx: Context, rt: Parameters<Code>[1]): unknown[] | Failed {\n const values = new Array<unknown>(parts.length);\n for (let index = 0; index < parts.length; index += 1) {\n const result = (parts[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n values[index] = result.value;\n }\n return values;\n}\n\nfunction partsOf(value: unknown): Readonly<Record<string, CompiledPart>> {\n return isRecord(value) ? (value as unknown as Readonly<Record<string, CompiledPart>>) : {};\n}\n\nconst LIT_SUMMARY = \"A literal: its value is the result.\";\n\n/**\n * This function makes the kinds of the formula kit, for a world. The kinds are the shared constructs of D13 and\n * the namespaces `ops` and `ext`. A bare value in a position of a term is a literal.\n *\n * @returns The entries of the world, by their key.\n */\nexport function formulaKinds(): Readonly<Record<string, WorldEntry>> {\n const term = { shape: \"term\", of: \"lit\" } as const;\n const terms = { shape: \"list\", of: \"lit\" } as const;\n const kinds: Record<string, Kind | WorldEntry> = {\n lit: { verbs: { eval: \"formula.lit\" }, summary: LIT_SUMMARY },\n ref: { verbs: { eval: \"formula.ref\" }, summary: \"A path from a root of the context. Its result is what the path reaches.\" },\n record: { verbs: { eval: \"formula.record\" }, parts: { shape: \"map\", of: \"lit\" }, summary: \"A record: each field is a term.\" },\n list: { verbs: { eval: \"formula.list\" }, parts: terms, summary: \"A list: each item is a term.\" },\n let: {\n verbs: { eval: \"formula.let\" },\n parts: { shape: \"record\", fields: { bind: { shape: \"map\", of: \"lit\" }, body: term }, required: [\"bind\", \"body\"] },\n scope: [{ names: { keysAt: [\"bind\"] }, in: [[\"body\"]] }],\n summary: \"Names for the body. Each binding sees the names around the let, not the other bindings.\",\n },\n fn: {\n verbs: { eval: \"formula.fn\" },\n parts: { shape: \"record\", fields: { body: term }, required: [\"params\", \"body\"] },\n scope: [{ names: { listAt: [\"params\"] }, in: [[\"body\"]] }],\n summary: \"A function: its parameters are names for its body.\",\n },\n call: {\n verbs: { eval: \"formula.call\" },\n parts: { shape: \"record\", fields: { fn: term, args: terms }, required: [\"fn\"] },\n summary: \"It calls a function with the values of its arguments.\",\n },\n if: {\n verbs: { eval: \"formula.if\" },\n parts: { shape: \"record\", fields: { test: term, then: term, else: term }, required: [\"test\", \"then\"] },\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n and: { verbs: { eval: \"formula.and\" }, parts: terms, summary: \"True when each term is true. It stops at the first false term.\" },\n or: { verbs: { eval: \"formula.or\" }, parts: terms, summary: \"True when one term is true. It stops at the first true term.\" },\n ops: { kinds: {}, fallback: { verbs: { eval: \"formula.op\" }, parts: terms, summary: \"An operation of the language, applied to the values of its terms.\" } },\n ext: { kinds: {}, fallback: { verbs: { eval: \"formula.ext\" }, summary: \"An extension of the language. Its value is data.\" } },\n };\n return kinds as Readonly<Record<string, WorldEntry>>;\n}\n\n/**\n * This function makes the evaluators of the formula kit for one language. Each evaluator compiles its document\n * one time into code.\n *\n * @param profile - The operations and the rules of the language.\n * @returns The evaluators, by their name.\n */\nexport function formulaEvaluators(profile: FormulaProfile = {}): Readonly<Record<string, Evaluator>> {\n const truthy = profile.truthy ?? strictTruthy;\n const otherwise = ok(Object.hasOwn(profile, \"otherwise\") ? profile.otherwise : null);\n const logicValue = profile.logic === \"value\";\n const omit = profile.omit;\n const missing = profile.missing;\n const check = profile.check;\n const lookup = (name: string): OpFn | undefined => {\n const ops = profile.ops;\n if (ops === undefined) return undefined;\n if (typeof ops === \"function\") return ops(name);\n return Object.hasOwn(ops, name) ? ops[name] : undefined;\n };\n const notTruth = (what: string): Failed => fail(\"#VALUE!\", `The ${what} must give a truth value.`);\n const combine = profile.combine;\n /** This function evaluates each part. Without `combine`, the first error stops it. A field that `omit` skips is absent. */\n const collect = (parts: readonly CompiledPart[], ctx: Context, rt: Parameters<Code>[1], skip?: (error: EvalError) => boolean): (readonly unknown[]) | Failed => {\n const values = new Array<unknown>(parts.length);\n let errors: EvalError[] | undefined;\n for (let index = 0; index < parts.length; index += 1) {\n const result = (parts[index] as CompiledPart).code(ctx, rt);\n if (result.ok) values[index] = result.value;\n else if (skip !== undefined && skip(result.error)) values[index] = SKIPPED;\n else if (combine === undefined) return result;\n else (errors ??= []).push(result.error);\n }\n // The errors exist only with combine, so the second test only narrows the type.\n if (errors === undefined || combine === undefined) return values;\n return { ok: false, error: errors.length === 1 ? (errors[0] as EvalError) : combine(errors) };\n };\n\n return {\n \"formula.lit\": compiled(({ doc }) => {\n const result = ok(doc.value);\n return () => result;\n }),\n\n \"formula.ref\": compiled(({ doc, parts, fill, address }) => {\n const path = doc.value;\n if (!Array.isArray(path) || path.length === 0) {\n const bad = fail(\"#VALUE!\", 'The value of ref is a path: a list that starts with a root, for example [\"names\", \"a\"].');\n return () => bad;\n }\n // A path through a name whose binding failed gives the error of the binding.\n const head = path[0] === \"names\" && typeof path[1] === \"string\" ? path[1] : undefined;\n const give = (found: Resolution): Result => {\n if (!found.ok) return fail(found.code, found.reason);\n // An address gives what the path reaches: a host thing stays a thing.\n if (address === true) return ok(found.thing);\n const reached = valueOfThing(found.thing);\n if (reached instanceof Held) return { ok: false, error: reached.error };\n if (missing !== undefined && missing(reached)) return fail(\"#N/A\", \"The path reaches no value.\");\n return ok(reached);\n };\n // The step documents of a path are its parts when the kind ref has a deep shape. They evaluate first, in order.\n const computed = parts.length > 0;\n return (ctx, rt) => {\n if (head !== undefined && Object.hasOwn(ctx.names, head)) {\n const bound = ctx.names[head];\n if (bound instanceof Held) return { ok: false, error: bound.error };\n }\n if (!computed) return give(rt.resolve(ctx, path));\n const steps = valuesOf(parts, ctx, rt);\n return Array.isArray(steps) ? give(rt.resolve(ctx, fill(steps) as readonly unknown[])) : steps;\n };\n }),\n\n \"formula.step\": compiled(({ doc, parts, fill }) => {\n // A step document without parts is its own value. A step document with parts gets the result of each part.\n if (parts.length === 0) {\n const same = ok(doc);\n return () => same;\n }\n return (ctx, rt) => {\n const values = valuesOf(parts, ctx, rt);\n return Array.isArray(values) ? ok({ ...doc, value: fill(values) as Json }) : values;\n };\n }),\n\n \"formula.record\": compiled(({ value }) => {\n const fields = partsOf(value);\n const keys = Object.keys(fields);\n const codes = keys.map((key) => (fields[key] as CompiledPart).code);\n if (combine !== undefined) {\n // With combine, each field evaluates, and two failed fields give one error.\n const parts = keys.map((key) => fields[key] as CompiledPart);\n return (ctx, rt) => {\n const values = collect(parts, ctx, rt, omit);\n if (!Array.isArray(values)) return values as Failed;\n const out: Record<string, unknown> = {};\n keys.forEach((key, index) => {\n if (values[index] !== SKIPPED) setOwn(out, key, values[index]);\n });\n return ok(out);\n };\n }\n return (ctx, rt) => {\n const out: Record<string, unknown> = {};\n for (let index = 0; index < keys.length; index += 1) {\n const result = (codes[index] as Code)(ctx, rt);\n if (!result.ok) {\n if (omit !== undefined && omit(result.error)) continue;\n return result;\n }\n setOwn(out, keys[index] as string, result.value);\n }\n return ok(out);\n };\n }),\n\n \"formula.list\": compiled(({ parts }) => (ctx, rt) => {\n const values = collect(parts, ctx, rt);\n return Array.isArray(values) ? ok(values) : (values as Failed);\n }),\n\n \"formula.let\": compiled(({ value }) => {\n const record = partsOf(value);\n const bindings = Object.entries(partsOf(record[\"bind\"]));\n const body = record[\"body\"] as CompiledPart;\n return (ctx, rt) => {\n const names: Record<string, unknown> = { ...ctx.names };\n for (const [name, part] of bindings) {\n const result = part.code(ctx, rt);\n setOwn(names, name, result.ok ? result.value : new Held(result.error));\n }\n return body.code({ ...ctx, names }, rt);\n };\n }),\n\n \"formula.fn\": compiled(({ value, data }) => {\n const params = isRecord(data) ? data[\"params\"] : undefined;\n if (!Array.isArray(params) || !params.every((param) => typeof param === \"string\") || new Set(params).size !== params.length) {\n const bad = fail(\"#VALUE!\", \"The params of fn are a list of different texts.\");\n return () => bad;\n }\n const names = params as readonly string[];\n const body = partsOf(value)[\"body\"] as CompiledPart;\n return (ctx, rt) => {\n const closure = (...args: readonly unknown[]): unknown => {\n const scope: Record<string, unknown> = { ...ctx.names };\n names.forEach((name, index) => setOwn(scope, name, args[index]));\n const result = body.code({ ...ctx, names: scope }, rt);\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n };\n Object.defineProperty(closure, CLOSURE, { value: { params: names } });\n return ok(closure);\n };\n }),\n\n \"formula.call\": compiled(({ value }) => {\n const record = partsOf(value);\n const fnPart = record[\"fn\"] as CompiledPart;\n const args = Array.isArray(record[\"args\"]) ? (record[\"args\"] as unknown as readonly CompiledPart[]) : [];\n return (ctx, rt) => {\n const fn = fnPart.code(ctx, rt);\n if (!fn.ok) return fn;\n if (typeof fn.value !== \"function\") return fail(\"#VALUE!\", \"The fn of call must give a function.\");\n const values = new Array<unknown>(args.length);\n for (let index = 0; index < args.length; index += 1) {\n const result = (args[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n values[index] = result.value;\n }\n try {\n return ok((fn.value as (...items: unknown[]) => unknown)(...values));\n } catch (error) {\n return thrown(error, \"the function of call\");\n }\n };\n }),\n\n \"formula.if\": compiled(({ value }) => {\n const record = partsOf(value);\n const test = record[\"test\"] as CompiledPart;\n const then = record[\"then\"] as CompiledPart;\n const other = record[\"else\"];\n return (ctx, rt) => {\n const chosen = test.code(ctx, rt);\n if (!chosen.ok) return chosen;\n const truth = truthy(chosen.value);\n if (truth === undefined) return notTruth(\"test of if\");\n if (truth) return then.code(ctx, rt);\n return other === undefined ? otherwise : other.code(ctx, rt);\n };\n }),\n\n \"formula.and\": compiled(({ parts }) => (ctx, rt) => {\n let last: Result = ok(true);\n for (const part of parts) {\n last = part.code(ctx, rt);\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return notTruth(\"term of and\");\n if (!truth) return logicValue ? last : ok(false);\n }\n return logicValue ? last : ok(true);\n }),\n\n \"formula.or\": compiled(({ parts }) => (ctx, rt) => {\n let last: Result = ok(false);\n for (const part of parts) {\n last = part.code(ctx, rt);\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return notTruth(\"term of or\");\n if (truth) return logicValue ? last : ok(true);\n }\n return logicValue ? last : ok(false);\n }),\n\n \"formula.op\": compiled(({ typePath, parts }) => {\n const name = typePath.slice(1).join(\".\");\n const lazy = profile.lazy !== undefined && Object.hasOwn(profile.lazy, name) ? profile.lazy[name] : undefined;\n if (lazy !== undefined) {\n return (ctx, rt) => {\n try {\n return lazy(parts.map((part) => () => part.code(ctx, rt)));\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n };\n }\n const fn = lookup(name) as ((...args: unknown[]) => unknown) | undefined;\n if (fn === undefined) {\n const unknown = fail(\"#NAME?\", `The language has no operation ${name}.`);\n return () => unknown;\n }\n const done = (out: unknown): Result => (check === undefined ? ok(out) : (check(out, name) ?? ok(out)));\n const failed = (error: unknown): Result => thrown(error, `the operation ${name}`);\n if (combine !== undefined) {\n return (ctx, rt) => {\n const values = collect(parts, ctx, rt);\n if (!Array.isArray(values)) return values as Failed;\n try {\n return done(fn(...values));\n } catch (error) {\n return failed(error);\n }\n };\n }\n if (parts.length === 1) {\n const [a] = parts as readonly [CompiledPart];\n return (ctx, rt) => {\n const x = a.code(ctx, rt);\n if (!x.ok) return x;\n try {\n return done(fn(x.value));\n } catch (error) {\n return failed(error);\n }\n };\n }\n if (parts.length === 2) {\n const [a, b] = parts as readonly [CompiledPart, CompiledPart];\n return (ctx, rt) => {\n const x = a.code(ctx, rt);\n if (!x.ok) return x;\n const y = b.code(ctx, rt);\n if (!y.ok) return y;\n try {\n return done(fn(x.value, y.value));\n } catch (error) {\n return failed(error);\n }\n };\n }\n return (ctx, rt) => {\n const values = new Array<unknown>(parts.length);\n for (let index = 0; index < parts.length; index += 1) {\n const result = (parts[index] as CompiledPart).code(ctx, rt);\n if (!result.ok) return result;\n values[index] = result.value;\n }\n try {\n return done(fn(...values));\n } catch (error) {\n return failed(error);\n }\n };\n }),\n\n \"formula.ext\": compiled(({ typePath, doc }) => {\n const name = typePath.slice(1).join(\".\");\n const own = profile.ext !== undefined && Object.hasOwn(profile.ext, name) ? profile.ext[name] : undefined;\n const handler = own ?? (Object.hasOwn(STD_EXT, name) ? STD_EXT[name] : undefined);\n if (handler === undefined) {\n const unknown = fail(\"#NAME?\", `The language has no extension ${name}.`);\n return () => unknown;\n }\n return (ctx) => {\n try {\n return handler(doc.value, ctx);\n } catch (error) {\n return thrown(error, `the extension ${name}`);\n }\n };\n }),\n };\n}\n\n/**\n * This function makes a machine for a formula language. The machine has the kinds and the evaluators of the\n * formula kit. It also has the kinds, the evaluators and the walkers that the language adds.\n *\n * @param profile - The operations and the rules of the language.\n * @param more - The parts of a machine that the language adds. Its kinds win over the kinds of the kit.\n * @returns The machine.\n */\nexport function formulaMachine(profile: FormulaProfile = {}, more: Partial<Machine> = {}): Machine {\n return {\n ...more,\n world: { kinds: { ...formulaKinds(), ...more.world?.kinds }, defaults: { ...more.world?.defaults } },\n evaluators: { ...formulaEvaluators(profile), ...more.evaluators },\n };\n}\n"],"mappings":";;AAqCA,MAAa,gBAAgB;CAAC;CAAQ;CAAS;CAAQ;AAAK;;;;;;;;AAS5D,SAAgB,SAAS,OAAqC;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