@mark1russell7/coeval 0.6.0 → 0.6.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":["NONE","setOwn","own","entryOf","setOwn","makeRootContext","drive","record","CLOSURE","partsOf","CLOSURE"],"sources":["../src/doc.ts","../src/errors.ts","../src/world.ts","../src/merge.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","../src/reference.ts","../src/agree.ts","../src/generate.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 values are equal. Plain JSON compares by its structure. Equal values have the same\n * texts, numbers and truth values, the same items in the same order, and the same fields. The order of the fields\n * does not matter. Each leaf compares with `Object.is`, thus `-0` is not `0`, and `NaN` is `NaN`.\n *\n * Only lists and plain records (`isRecord`) compare by their items and fields. Each other object compares by\n * identity: a date, a map, a function and an instance of a class are equal only to themselves. Thus an early cutoff\n * with this function does not keep a stale host value.\n *\n * The function does not use the stack for the depth, thus a deep document cannot overflow it. A cycle of lists or\n * records does not make it loop. `sameValue` of `agree` uses the same rules, and it adds rules for closures and for\n * a rule of the caller.\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 // The pairs of containers that the comparison already visits. It is made at the first pair of containers.\n let seen: Map<object, Set<object>> | undefined;\n while (stack.length > 0) {\n const [x, y] = stack.pop() as [unknown, unknown];\n if (Object.is(x, y)) continue;\n const list = Array.isArray(x);\n if (list !== Array.isArray(y)) return false;\n // An object that is not a list and not a plain record is a host value: Object.is above compared it.\n if (!list && (!isRecord(x) || !isRecord(y))) return false;\n seen ??= new Map();\n const pairs = seen.get(x as object);\n if (pairs?.has(y as object) === true) continue;\n if (pairs === undefined) seen.set(x as object, new Set([y as object]));\n else pairs.add(y as object);\n if (list) {\n const xs = x as readonly unknown[];\n const ys = y as readonly unknown[];\n if (xs.length !== ys.length) return false;\n for (let index = 0; index < xs.length; index += 1) stack.push([xs[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 try {\n // A regular expression that compiles near the limit of the stack throws a SyntaxError with the same message.\n // Thus the test reads the message with includes, and it accepts a SyntaxError.\n return (error instanceof RangeError || error instanceof SyntaxError) && error.message.includes(\"call stack\");\n } catch {\n // Near the limit of the stack, the test itself can overflow.\n return true;\n }\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 Key, docEquals, isRecord } from \"./doc.ts\";\nimport type { DerefCode, Walker } from \"./deref.ts\";\nimport type { Evaluator, Machine, Runner } from \"./evaluate.ts\";\nimport { type Kind, type World, type WorldEntry, isAlias, isKind, isNamespace } from \"./world.ts\";\n\n/** The keys from a part of a merge to one of its entries, for example `[\"kinds\", \"ref\"]`. */\nexport type MergePath = readonly Key[];\n\n/**\n * A world as a part of a merge. Each field is optional. `replaces` names the paths of the entries that this part\n * replaces, for example `[\"kinds\", \"ref\"]` or `[\"defaults\", \"view\"]`. The result of a merge has no `replaces`.\n */\nexport interface WorldPart {\n readonly kinds?: Readonly<Record<string, WorldEntry>>;\n readonly defaults?: Readonly<Record<string, string>>;\n readonly fallback?: Kind;\n readonly replaces?: readonly MergePath[];\n}\n\n/**\n * A machine as a part of a merge. Each field is optional. `replaces` names paths in the machine, for example\n * `[\"evaluators\", \"formula.op\"]` or `[\"world\", \"kinds\", \"ref\"]`. The paths in `world.replaces` start at the world.\n */\nexport interface MachinePart extends Omit<Partial<Machine>, \"world\"> {\n readonly world?: WorldPart;\n readonly replaces?: readonly MergePath[];\n}\n\n/**\n * One conflict of a merge. `path` is the path of the entry, as `replaces` names it. Thus the same path in the\n * `replaces` of the later part resolves the conflict. `parts` gives the indices of the two parts, the earlier first.\n */\nexport interface MergeConflict {\n readonly path: MergePath;\n readonly parts: readonly [number, number];\n readonly reason: string;\n}\n\n/** The exception of a merge with conflicts. It lists each conflict of the merge, not only the first. */\nexport class MergeError extends Error {\n readonly conflicts: readonly MergeConflict[];\n\n /**\n * This constructor makes the exception.\n *\n * @param conflicts - The conflicts, in the order that the merge found them.\n */\n constructor(conflicts: readonly MergeConflict[]) {\n const lines = conflicts.map((item) => `At ${JSON.stringify(item.path)}, the parts ${item.parts[0]} and ${item.parts[1]}: ${item.reason}`);\n super(`The merge has ${conflicts.length === 1 ? \"1 conflict\" : `${conflicts.length} conflicts`}. ${lines.join(\" \")}`);\n this.name = \"MergeError\";\n this.conflicts = conflicts;\n }\n}\n\ntype Known = NonNullable<Machine[\"known\"]>;\n\nconst NONE: ReadonlySet<string> = new Set();\n\nfunction keyOf(path: MergePath): string {\n return JSON.stringify(path.map(String));\n}\n\n/** This function sets an own data property. An assignment to the key `__proto__` changes the prototype. */\nfunction setOwn<T>(target: Record<string, T>, key: string, value: T): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nfunction own<T>(table: Readonly<Record<string, T>> | undefined, key: string): T | undefined {\n return table !== undefined && Object.hasOwn(table, key) ? table[key] : undefined;\n}\n\n/** This function gives a copy of a JSON value without the fields whose value is `undefined`, as JSON writes it. */\nfunction defined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(defined);\n if (!isRecord(value)) return value;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) if (value[key] !== undefined) setOwn(out, key, defined(value[key]));\n return out;\n}\n\n/** Two values are the same when they are equal by `docEquals`. A function and a host value are equal only to themselves. */\nfunction same(a: unknown, b: unknown): boolean {\n return Object.is(a, b) || docEquals(defined(a), defined(b));\n}\n\n/** Two lists of roots are the same when they hold the same roots, in any order. */\nfunction sameRoots(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) return same(a, b);\n return same([...new Set(a.map(String))].sort(), [...new Set(b.map(String))].sort());\n}\n\n/** The record of a merge: the conflicts, and the part that gave each entry. */\nclass Merger {\n readonly conflicts: MergeConflict[] = [];\n private readonly sources = new Map<string, number>();\n\n /** This method gives the part that gave the entry at a path, or the entry nearest above it. */\n sourceOf(path: MergePath): number {\n for (let length = path.length; length >= 0; length -= 1) {\n const found = this.sources.get(keyOf(path.slice(0, length)));\n if (found !== undefined) return found;\n }\n return 0;\n }\n\n /** This method records the part that gives a new entry. */\n give(path: MergePath, part: number): void {\n this.sources.set(keyOf(path), part);\n }\n\n /** This method records the part that replaces an entry, and forgets the parts of each entry below it. */\n replace(path: MergePath, part: number): void {\n const below = `${keyOf(path).slice(0, -1)},`;\n for (const key of [...this.sources.keys()]) if (key.startsWith(below)) this.sources.delete(key);\n this.give(path, part);\n }\n\n clash(path: MergePath, part: number, reason: string): void {\n this.conflicts.push({ path, parts: [this.sourceOf(path), part], reason });\n }\n}\n\n/**\n * This function merges one entry of a table into the table. A new entry joins the table. A path in `replaces` gives\n * the later entry. Two entries that are the same give one entry. Each other pair is a conflict.\n */\nfunction mergeLeaf<T>(\n m: Merger,\n table: Record<string, T>,\n key: string,\n later: T | undefined,\n path: MergePath,\n part: number,\n replaces: ReadonlySet<string>,\n equal: (a: T, b: T) => boolean,\n reason: string,\n): void {\n if (later === undefined) return;\n const earlier = own(table, key);\n if (earlier === undefined) {\n setOwn(table, key, later);\n m.give(path, part);\n } else if (replaces.has(keyOf(path))) {\n setOwn(table, key, later);\n m.replace(path, part);\n } else if (!equal(earlier, later)) {\n m.clash(path, part, reason);\n }\n}\n\nfunction what(entry: WorldEntry): string {\n if (isKind(entry)) return \"a kind\";\n if (isAlias(entry)) return \"an alias\";\n return isNamespace(entry) ? \"a namespace\" : \"an entry\";\n}\n\nfunction mergeFallback(m: Merger, earlier: Kind | undefined, later: Kind | undefined, path: MergePath, part: number, replaces: ReadonlySet<string>): Kind | undefined {\n const table: Record<string, Kind> = earlier === undefined ? {} : { fallback: earlier };\n mergeLeaf(m, table, \"fallback\", later, path, part, replaces, same, \"Two parts give two different fallback kinds.\");\n return table[\"fallback\"];\n}\n\nfunction mergeEntries(m: Merger, into: Record<string, WorldEntry>, from: Readonly<Record<string, WorldEntry>>, path: MergePath, part: number, replaces: ReadonlySet<string>): void {\n for (const key of Object.keys(from)) {\n const later = from[key];\n if (later === undefined) continue;\n const at = [...path, key];\n const earlier = own(into, key);\n if (earlier === undefined) {\n setOwn(into, key, later);\n m.give(at, part);\n } else {\n setOwn(into, key, mergeEntry(m, earlier, later, at, part, replaces));\n }\n }\n}\n\n/** This function merges two entries at one path. Two namespaces merge key by key, and their fallbacks merge too. */\nfunction mergeEntry(m: Merger, earlier: WorldEntry, later: WorldEntry, path: MergePath, part: number, replaces: ReadonlySet<string>): WorldEntry {\n if (replaces.has(keyOf(path))) {\n m.replace(path, part);\n return later;\n }\n if (same(earlier, later)) return earlier;\n if (isNamespace(earlier) && isNamespace(later)) {\n const kinds: Record<string, WorldEntry> = { ...earlier.kinds };\n mergeEntries(m, kinds, later.kinds, [...path, \"kinds\"], part, replaces);\n const fallback = mergeFallback(m, earlier.fallback, later.fallback, [...path, \"fallback\"], part, replaces);\n return fallback === undefined ? { kinds } : { kinds, fallback };\n }\n const a = what(earlier);\n const b = what(later);\n m.clash(path, part, a === b ? `Two parts give two different ${a === \"an alias\" ? \"aliases\" : \"kinds\"}.` : `One part gives ${a}, and the other part gives ${b}.`);\n return earlier;\n}\n\ninterface WorldDraft {\n readonly kinds: Record<string, WorldEntry>;\n readonly defaults: Record<string, string>;\n fallback?: Kind;\n}\n\nfunction worldOf(draft: WorldDraft): World {\n const world = { kinds: { ...draft.kinds }, defaults: { ...draft.defaults } };\n return draft.fallback === undefined ? world : { ...world, fallback: draft.fallback };\n}\n\nfunction mergeWorldInto(m: Merger, draft: WorldDraft, part: WorldPart | undefined, index: number, replaces: ReadonlySet<string>, base: MergePath): void {\n if (part === undefined) return;\n if (part.kinds !== undefined) mergeEntries(m, draft.kinds, part.kinds, [...base, \"kinds\"], index, replaces);\n const defaults = part.defaults ?? {};\n for (const verb of Object.keys(defaults)) {\n mergeLeaf(m, draft.defaults, verb, defaults[verb], [...base, \"defaults\", verb], index, replaces, Object.is, \"Two parts give two different defaults for this verb.\");\n }\n const fallback = mergeFallback(m, draft.fallback, part.fallback, [...base, \"fallback\"], index, replaces);\n if (fallback !== undefined) draft.fallback = fallback;\n}\n\n/**\n * This function merges worlds into one world, in the order of the parts. It does not change a part.\n *\n * - Two entries that are equal by `docEquals` give one entry.\n * - Two namespaces merge key by key, at each depth. Their fallbacks merge as each other entry.\n * - The defaults merge verb by verb, and the world keeps one fallback.\n * - Each other pair of entries at one path is a conflict, unless the later part names the path in `replaces`.\n * Then the later entry wins, with no merge below it.\n *\n * A part can be a function of the merge of the parts before it (`prev`, as an overlay of Nix). Thus a part can read\n * the entry that it replaces.\n *\n * @param parts - The worlds, or functions that give a world from the merge before them.\n * @returns The world. It has no `replaces`.\n * @throws {MergeError} The merge has a conflict. The error lists each conflict.\n */\nexport function mergeWorlds(...parts: readonly (WorldPart | ((prev: World) => WorldPart))[]): World {\n const m = new Merger();\n const draft: WorldDraft = { kinds: {}, defaults: {} };\n parts.forEach((input, index) => {\n const part = typeof input === \"function\" ? input(worldOf(draft)) : input;\n mergeWorldInto(m, draft, part, index, new Set((part.replaces ?? []).map(keyOf)), []);\n });\n if (m.conflicts.length > 0) throw new MergeError(m.conflicts);\n return worldOf(draft);\n}\n\n/** The fields of a machine that merge by their own rules. Each other field is one value, or a conflict. */\nconst TABLES = new Set([\"world\", \"evaluators\", \"runners\", \"derefs\", \"walkers\", \"known\", \"replaces\"]);\n\ninterface MachineDraft {\n readonly world: WorldDraft;\n readonly evaluators: Record<string, Evaluator>;\n runners?: Record<string, Runner>;\n derefs?: Record<string, DerefCode>;\n walkers?: Record<string, Walker>;\n readonly hooks: { readonly part: number; readonly known: Known }[];\n /** The last part that replaced the code of each evaluator name. */\n readonly replaced: Map<string, number>;\n readonly rest: Record<string, unknown>;\n readonly parts: MachinePart[];\n}\n\n/**\n * This function composes the hooks `known` in the order of their parts. The first answer that is not `true` wins. A\n * hook does not answer for an evaluator name whose code a later part replaces.\n */\nfunction composeKnown(hooks: readonly { readonly part: number; readonly known: Known }[], replaced: ReadonlyMap<string, number>): Known | undefined {\n const first = hooks[0];\n if (first === undefined) return undefined;\n if (hooks.length === 1 && replaced.size === 0) return first.known;\n const list = [...hooks];\n const last = new Map(replaced);\n return (path, evaluator) => {\n const after = last.get(evaluator);\n for (const hook of list) {\n if (after !== undefined && hook.part < after) continue;\n const answer = hook.known(path, evaluator);\n if (answer !== true) return answer;\n }\n return true;\n };\n}\n\nfunction machineOf(draft: MachineDraft): Machine {\n const known = composeKnown(draft.hooks, draft.replaced);\n return {\n ...draft.rest,\n world: worldOf(draft.world),\n evaluators: { ...draft.evaluators },\n ...(draft.runners === undefined ? {} : { runners: { ...draft.runners } }),\n ...(draft.derefs === undefined ? {} : { derefs: { ...draft.derefs } }),\n ...(draft.walkers === undefined ? {} : { walkers: { ...draft.walkers } }),\n ...(known === undefined ? {} : { known }),\n };\n}\n\n/** This function merges the evaluators and the runners of a part. The evaluator and the runner of a name are its code. */\nfunction mergeCode(m: Merger, draft: MachineDraft, part: MachinePart, index: number, replaces: ReadonlySet<string>): void {\n if (part.runners !== undefined) draft.runners ??= {};\n const names = new Set([...Object.keys(part.evaluators ?? {}), ...Object.keys(part.runners ?? {})]);\n for (const name of names) {\n const evaluator = own(part.evaluators, name);\n const runner = own(part.runners, name);\n if (evaluator === undefined && runner === undefined) continue;\n const evaluatorPath = [\"evaluators\", name];\n const runnerPath = [\"runners\", name];\n if (replaces.has(keyOf(evaluatorPath)) || replaces.has(keyOf(runnerPath))) {\n // The part replaces the code of the name: the evaluator and the runner of the earlier parts go.\n if (evaluator === undefined) delete draft.evaluators[name];\n else setOwn(draft.evaluators, name, evaluator);\n if (runner !== undefined) setOwn((draft.runners ??= {}), name, runner);\n else if (draft.runners !== undefined) delete draft.runners[name];\n m.replace(evaluatorPath, index);\n m.replace(runnerPath, index);\n draft.replaced.set(name, index);\n continue;\n }\n mergeLeaf(m, draft.evaluators, name, evaluator, evaluatorPath, index, NONE, Object.is, \"Two parts give two different evaluators for this name.\");\n if (runner !== undefined) mergeLeaf(m, (draft.runners ??= {}), name, runner, runnerPath, index, NONE, Object.is, \"Two parts give two different runners for this name.\");\n }\n}\n\n/** A runner hides the evaluator of its name. Thus a name with a runner and an evaluator needs one part that gives both. */\nfunction checkHidden(m: Merger, draft: MachineDraft): void {\n const runners = draft.runners ?? {};\n for (const name of Object.keys(runners)) {\n const runner = runners[name];\n const evaluator = own(draft.evaluators, name);\n if (runner === undefined || evaluator === undefined) continue;\n if (draft.parts.some((part) => own(part.evaluators, name) === evaluator && own(part.runners, name) === runner)) continue;\n const a = m.sourceOf([\"evaluators\", name]);\n const b = m.sourceOf([\"runners\", name]);\n m.conflicts.push({\n path: [\"runners\", name],\n parts: [Math.min(a, b), Math.max(a, b)],\n reason: \"The runner of one part hides the evaluator of the other part, because a runner wins over an evaluator of its name.\",\n });\n }\n}\n\n/**\n * This function merges machines into one machine, in the order of the parts. It does not change a part.\n *\n * - The worlds merge with the rules of `mergeWorlds`. The paths of their conflicts start with `\"world\"`.\n * - The tables `evaluators`, `runners`, `derefs` and `walkers` merge name by name. A function is equal only to itself.\n * - The evaluator and the runner of a name are its code. A replacement of the name replaces both.\n * - A runner hides the evaluator of its name. Thus one part must give both, or the merge gives a conflict.\n * - The hooks `known` compose in the order of the parts. A hook does not answer for a name that a later part replaces.\n * - Each other field, for example `permits`, `adopt`, `roots`, `plain` or `maxDepth`, is one value. Two different\n * values are a conflict. An absent field has no value.\n *\n * A conflict stops the merge, unless the later part names its path in `replaces`. A part can be a function of the\n * merge of the parts before it (`prev`, as an overlay of Nix). Thus a part can wrap the code that it replaces.\n *\n * @param parts - The machines, or functions that give a machine from the merge before them.\n * @returns The machine.\n * @throws {MergeError} The merge has a conflict. The error lists each conflict.\n */\nexport function mergeMachines(...parts: readonly (MachinePart | ((prev: Machine) => MachinePart))[]): Machine {\n const m = new Merger();\n const draft: MachineDraft = { world: { kinds: {}, defaults: {} }, evaluators: {}, hooks: [], replaced: new Map(), rest: {}, parts: [] };\n parts.forEach((input, index) => {\n const part = typeof input === \"function\" ? input(machineOf(draft)) : input;\n draft.parts.push(part);\n const replaces = new Set([...(part.replaces ?? []), ...(part.world?.replaces ?? []).map((path) => [\"world\", ...path])].map(keyOf));\n mergeWorldInto(m, draft.world, part.world, index, replaces, [\"world\"]);\n mergeCode(m, draft, part, index, replaces);\n if (part.derefs !== undefined) {\n const derefs = (draft.derefs ??= {});\n for (const name of Object.keys(part.derefs)) mergeLeaf(m, derefs, name, part.derefs[name], [\"derefs\", name], index, replaces, Object.is, \"Two parts give two different deref codes for this name.\");\n }\n if (part.walkers !== undefined) {\n const walkers = (draft.walkers ??= {});\n for (const name of Object.keys(part.walkers)) mergeLeaf(m, walkers, name, part.walkers[name], [\"walkers\", name], index, replaces, Object.is, \"Two parts give two different walkers for this name.\");\n }\n if (part.known !== undefined && !draft.hooks.some((hook) => hook.known === part.known)) draft.hooks.push({ part: index, known: part.known });\n const fields = part as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(fields)) {\n if (TABLES.has(key)) continue;\n mergeLeaf(m, draft.rest, key, fields[key], [key], index, replaces, key === \"roots\" ? sameRoots : same, `Two parts give two different values for ${key}.`);\n }\n });\n checkHidden(m, draft);\n if (m.conflicts.length > 0) throw new MergeError(m.conflicts);\n return machineOf(draft);\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 Envelope, type Json, type Key, docEquals, isEnvelope, isRecord, typeName, typePath } from \"./doc.ts\";\nimport { type Kind, type Shape, type World, lookupKind } 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 tells if a shape holds only data: no value of the shape can hold a part. */\nfunction isData(shape: Shape): boolean {\n return shape.shape === \"none\" || shape.shape === \"text\" || shape.shape === \"number\" || shape.shape === \"one\";\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 const items = list.map((child, index) => walk(each, child, [...path, index]));\n // A list of data is data, also when it is empty. Only a list that can hold parts gives null in the data.\n return isData(each) ? { t: \"data\", value: item } : { t: \"list\", items };\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 * The kind and the parts of one document: what `partsOf` gives. `ok` is `false` only when the value is not a\n * document: it has no envelope, and its position declares no type. A value without the shape of its kind gives a\n * failed `split`.\n */\nexport type DocParts =\n | {\n readonly ok: true;\n /** The document. A bare value gets 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, or `undefined` when the world has no kind for the type. Then the value is data. */\n readonly kind: Kind | undefined;\n /** The keys of the kind after each alias, or `undefined` without a kind. */\n readonly typePath: readonly Key[] | undefined;\n /**\n * The split of the value by the shape of the kind. The reason of a failed split is the reason of the `#VALUE!`\n * of an evaluation: it names the kind. Its `at` gives the keys from the value to the problem.\n */\n readonly split: Split;\n }\n | { readonly ok: false; readonly code: \"#PART?\"; readonly reason: string };\n\n/**\n * This function reads one document by the contracts of the world. It finds the kind of the type. A bare value gets\n * the type that its position declares. Then the function splits the value by the shape of the kind. The plan, the\n * reference interpreter and the static kit read each document with this function. Thus they see the same parts.\n *\n * @param world - The world of the kinds.\n * @param value - The document, or a bare value.\n * @param declaredType - The type that the position of a bare value declares.\n * @returns The document, its kind and its parts, or the reason why the value is not a document.\n */\nexport function partsOf(world: World, value: unknown, declaredType?: string): DocParts {\n const envelope = isEnvelope(value) ? (value as Envelope) : undefined;\n if (envelope === undefined && declaredType === undefined) return { ok: false, code: \"#PART?\", reason: \"The value has no envelope, and its position declares no type.\" };\n const doc: Envelope = envelope ?? { type: declaredType as string, value: value as Json };\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n const split = splitParts(kind?.parts, doc.value);\n const typePath = found.ok ? found.path : undefined;\n if (split.ok) return { ok: true, doc, declared: envelope === undefined, kind, typePath, split };\n // The reason names the place in the value and the kind, as each reader of the document gives it.\n const where = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n const reason = `${split.reason}${where} The kind is ${typeName(doc.type)}.`;\n return { ok: true, doc, declared: envelope === undefined, kind, typePath, split: { ok: false, reason, at: split.at } };\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, partsOf, pathMatches } from \"./parts.ts\";\nimport { ask, type Answer } from \"./ladder.ts\";\nimport type { CapsRule, Kind, Side, World } 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 * - `known`: the names that the evaluators know, for `check`. Without it, `check` does not check such names.\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 * This function tells if an evaluator knows the name in the path of a kind. An example is the operation\n * `[\"ops\", \"add\"]` of a formula language: a fallback kind names it, and the evaluator finds it in a table.\n * `check` asks it for each document with an evaluator. The function must be pure.\n *\n * @param path - The keys of the kind of the document, after each alias.\n * @param evaluator - The name of the evaluator that the ladder gives the document.\n * @returns `true` when the evaluator knows the name, or else the reason of the `#NAME?` that a run gives.\n */\n readonly known?: (path: readonly Key[], evaluator: string) => true | string;\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 return failingWith(c, meta, fail(code, reason, { place }));\n}\n\n/** This function gives the code of a document that fails with one result at each evaluation. */\nfunction failingWith(c: Compiler, meta: Meta, result: Result): { readonly code: Code; readonly run: RunCode } {\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, kind: Kind | undefined): { 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 (kind === undefined) return { unknown: true };\n const verbs = 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 world = c.machine.world;\n const read = partsOf(world, value, declared);\n if (!read.ok) {\n const meta: Meta = c.traced ? { path: place.map(String), doc: { type: \"?\", value: value as Json }, declared: true, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n return failing(c, meta, place, read.code, read.reason);\n }\n const { doc, kind, split } = read;\n const envelope = read.declared ? undefined : doc;\n const meta0: Meta = c.traced ? { path: place.map(String), doc, declared: read.declared, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n if (depth > c.maxDepth) return failing(c, meta0, place, \"#DEPTH!\", `The nesting is deeper than ${c.maxDepth} documents.`);\n\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, kind);\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 if (!split.ok) return failing(c, meta, place, \"#VALUE!\", split.reason);\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 = read.typePath ?? [];\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 // A compiler that throws fails its own document when that document evaluates, with its place (PLAN.FAIL-LATE).\n if (runner !== undefined) {\n let inner: RunCode;\n try {\n inner = isCompiledRunner(runner) ? runner.compileRun(input) : interpretRun(runner, input, split.fill);\n } catch (error) {\n return failingWith(c, meta, placed(thrown(error, `the runner ${name}`), place));\n }\n const run = placedRun(inner, place, name);\n return finish(c, meta, runnerCode(run, place, kindText), run);\n }\n\n let inner: Code;\n try {\n inner = isCompiledEvaluator(evaluator as Evaluator) ? (evaluator as CompiledEvaluator).compile(input) : interpret(evaluator as EvalFn, input, split.fill);\n } catch (error) {\n return failingWith(c, meta, placed(thrown(error, `the evaluator ${name}`), place));\n }\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/**\n * This function gives the code of a runner in an evaluation: its steps, which cannot wait. A step that waits gives\n * `#CALC!` at the place of the runner, where the error started (RUN.WAIT).\n */\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 : placed(drive(run(ctx, rt)), place);\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 = placed(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 EvalInput, type Evaluator, type Machine, type Part, type Result, type RunPart, type Runner, type Steps, fail, ok } from \"./evaluate.ts\";\nimport { Failure } from \"./errors.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 // An attribute evaluates on demand, thus in an order that is not the order of the document. It causes no effect.\n caps: [{ rule: \"mask\" }],\n summary: \"A node of a tree. Each part is an attribute that evaluates on demand, one time, with the node as self.\",\n },\n box: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n caps: [{ rule: \"mask\" }],\n summary: \"A node of a tree, as panel. A formula in a box can read its parent and its siblings.\",\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),\n};\n\n/*\n * The decorated tree (TREE.*, R3 P1). Each node is a host thing, and each part of a node is an attribute. An attribute\n * evaluates on demand, with the node as self. One memo cell for each node and attribute keeps its result for one\n * evaluation. The structure comes first: a node inside an attribute of an open tree gives its thing and evaluates\n * nothing. The root gives the JSON of the tree. Thus a reference to a sibling reads the finished list of children.\n */\n\n/** The brand of a node of the decorated tree. Its value is the state that the kit reads. */\nconst TREE_NODE: unique symbol = Symbol.for(\"coeval.tree.node\") as never;\n\n/** One tree in one evaluation. It is open until its root gives the JSON of the tree. */\ninterface TreeBuild {\n open: boolean;\n}\n\n/** The state of a node behind its brand. */\ninterface NodeState {\n readonly build: TreeBuild;\n readonly type: string;\n readonly place: readonly Key[];\n /**\n * This function gives the JSON of the node: each attribute in the order of the parts, with the JSON of each node in\n * its value.\n *\n * @param path - The nodes and the containers whose JSON is in progress. A node on it gives `#CYCLE!`.\n * @returns The JSON, or the first error.\n */\n json(path: Set<object>): Result;\n}\n\n/** The memo cell of one attribute: in evaluation, or done with its result. */\ntype Cell = { readonly busy: true } | { readonly busy: false; readonly result: Result };\n\nconst BUSY: Cell = Object.freeze({ busy: true });\n\n/** One attribute in evaluation. The text names it in the reason of a cycle. */\ninterface Demand {\n readonly cells: Map<string, Cell>;\n readonly key: string;\n readonly text: string;\n}\n\n/** The attributes in evaluation, in the order of their demands. An evaluation does not wait, thus one list serves. */\nconst demands: Demand[] = [];\n\nfunction attributeText(key: string, type: string, place: readonly Key[]): string {\n return `${key} of ${type} at [${place.join(\", \")}]`;\n}\n\n/** This function gives the `#CYCLE!` of a demand that reached an attribute in evaluation, with the chain of demands. */\nfunction cycleAt(cells: Map<string, Cell>, key: string, text: string): Result {\n const first = demands.findIndex((demand) => demand.cells === cells && demand.key === key);\n const chain = first === -1 ? [text] : demands.slice(first).map((demand) => demand.text);\n chain.push(text);\n return fail(\"#CYCLE!\", `The attributes form a cycle: ${chain.join(\" -> \")}.`);\n}\n\nfunction stateOf(thing: unknown): NodeState | undefined {\n return typeof thing === \"object\" && thing !== null ? (thing as { readonly [TREE_NODE]?: NodeState })[TREE_NODE] : undefined;\n}\n\n/** This function sets an own field, also the field `__proto__` (SHAPE.PROTO). */\nfunction putField(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * This function gives a value with the JSON of each node of a tree in it. A list or a plain record is new only when\n * it holds a node. A container that holds itself stays as it is.\n */\nfunction plainOf(value: unknown, path: Set<object>): Result {\n const state = stateOf(value);\n if (state !== undefined) {\n if (path.has(value as object)) return fail(\"#CYCLE!\", `The JSON of the node ${state.type} at [${state.place.join(\", \")}] holds the node itself.`);\n return state.json(path);\n }\n if (typeof value !== \"object\" || value === null || path.has(value) || isHostThing(value)) return ok(value);\n if (!Array.isArray(value) && !isRecord(value)) return ok(value);\n path.add(value);\n try {\n if (Array.isArray(value)) {\n let list: unknown[] | undefined;\n for (let index = 0; index < value.length; index += 1) {\n const item = plainOf(value[index], path);\n if (!item.ok) return item;\n if (item.value !== value[index]) (list ??= [...(value as readonly unknown[])])[index] = item.value;\n }\n return ok(list ?? value);\n }\n const record = value as Readonly<Record<string, unknown>>;\n let out: Record<string, unknown> | undefined;\n for (const key of Object.keys(record)) {\n const item = plainOf(record[key], path);\n if (!item.ok) return item;\n if (item.value === record[key]) continue;\n if (out === undefined) {\n out = {};\n for (const other of Object.keys(record)) putField(out, other, record[other]);\n }\n putField(out, key, item.value);\n }\n return ok(out ?? value);\n } finally {\n path.delete(value);\n }\n}\n\n/**\n * This function makes a node of the decorated tree. A step `parent` gives the self of the context of the node, and a\n * step `type` gives its type. A step with the key of a part reads that attribute. A failed attribute throws `Failure`\n * with its own error, thus a reference to it gives that error.\n */\nfunction treeThing(parts: readonly Part[], context: Context, type: string, place: readonly Key[], build: TreeBuild): HostThing {\n const cells = new Map<string, Cell>();\n const read = (key: string): Result | undefined => {\n const cell = cells.get(key);\n if (cell !== undefined) return cell.busy ? cycleAt(cells, key, attributeText(key, type, place)) : cell.result;\n const part = parts.find((item) => item.key === key);\n if (part === undefined) return undefined;\n cells.set(key, BUSY);\n demands.push({ cells, key, text: attributeText(key, type, place) });\n let result: Result;\n try {\n result = part.evaluate({ ...context, self: node });\n } catch (error) {\n // An exception of the host, for example an overflow of the stack, leaves the attribute without a result.\n cells.delete(key);\n throw error;\n } finally {\n demands.pop();\n }\n cells.set(key, { busy: false, result });\n return result;\n };\n const state: NodeState = {\n build,\n type,\n place,\n json(path) {\n path.add(node);\n try {\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key) as Result;\n if (!result.ok) return result;\n const value = plainOf(result.value, path);\n if (!value.ok) return value;\n putField(out, part.key, value.value);\n }\n return ok(out);\n } finally {\n path.delete(node);\n }\n },\n };\n const node: HostThing & { readonly type: string; readonly [TREE_NODE]: NodeState } = {\n [THING]: true,\n [TREE_NODE]: state,\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 if (result === undefined) return undefined;\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n toJson(): unknown {\n const result = state.json(new Set());\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n };\n return node;\n}\n\n/**\n * This function evaluates a node of the decorated tree. Inside an attribute of an open tree, the node gives its host\n * thing, and no attribute evaluates. Else the node is the root of a new tree, and it gives the JSON of the tree.\n */\nfunction treeNode({ parts, context, kind, place }: EvalInput): Result {\n const above = stateOf(context.self);\n if (above !== undefined && above.build.open) return ok(treeThing(parts, context, kind, place, above.build));\n const build: TreeBuild = { open: true };\n const root = treeThing(parts, context, kind, place, build);\n try {\n return (stateOf(root) as NodeState).json(new Set());\n } finally {\n build.open = false;\n }\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, partsOf, pathMatches } 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 read = partsOf(world, item.value, item.declared);\n if (!read.ok) {\n options.problem?.({ place: keysOf(item.place), at: keysOf(item.at), code: read.code, reason: read.reason });\n continue;\n }\n const { doc, kind, split } = read;\n const here = new Visit(\n item.place,\n item.at,\n doc,\n read.declared,\n item.depth,\n item.names,\n item.later,\n item.slot,\n item.parent,\n kind,\n read.typePath,\n item.address ? true : undefined,\n item.caps,\n );\n const answer = visit(here);\n if (answer === \"skip\" || kind === undefined) continue;\n const base: Trail | undefined = read.declared ? item.at : { up: item.at, keys: [\"value\"] };\n if (!split.ok) {\n options.problem?.({ place: keysOf(item.place), at: keysOf({ up: base, keys: split.at }), code: \"#VALUE!\", reason: split.reason });\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. With the hook `known` of the machine, also a name that the language does not\n * have, for example an operation.\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 } else if (machine.known !== undefined) {\n // The evaluator gives #NAME? in a run for a name that the language does not have, for example an operation.\n const known = machine.known(v.typePath ?? [], name);\n if (known !== true) issues.push({ code: \"#NAME?\", place: v.place, reason: known, 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 // The step documents of the path are parts, and they evaluate before the path, thus the walk visits them.\n return undefined;\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, type Key, 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\";\nimport { type MachinePart, mergeMachines } from \"./merge.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: { params: { shape: \"list\", item: { shape: \"text\" }, distinct: true }, 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 const held = (ctx: Context): Failed | undefined => {\n if (head === undefined || !Object.hasOwn(ctx.names, head)) return undefined;\n const bound = ctx.names[head];\n return bound instanceof Held ? { ok: false, error: bound.error } : undefined;\n };\n if (parts.length === 0) return (ctx, rt) => held(ctx) ?? give(rt.resolve(ctx, path));\n // The step documents of a path are its parts when the kind ref has a deep shape. They evaluate first, in order,\n // thus the error of a step comes before the error of a binding that the path reads (FORMULA.STEPS).\n return (ctx, rt) => {\n const steps = valuesOf(parts, ctx, rt);\n if (!Array.isArray(steps)) return steps;\n return held(ctx) ?? give(rt.resolve(ctx, fill(steps) as readonly unknown[]));\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 the hook `known` of the formula kit for one profile (STATIC.KNOWN). The evaluator\n * `formula.op` knows an operation of `lazy` or of `ops`. A profile whose `ops` is a function answers through a call\n * of that function. A function that throws counts as an answer, because the run then gives `#CALC!`. The evaluator\n * `formula.ext` knows an extension of `ext` and each standard extension. The hook knows each name of the other\n * evaluators.\n *\n * @param profile - The operations and the extensions of the language.\n * @returns The hook: `true`, or the reason of the `#NAME?` that the evaluator gives in a run.\n */\nexport function formulaKnown(profile: FormulaProfile = {}): (path: readonly Key[], evaluator: string) => true | string {\n const hasOp = (name: string): boolean => {\n if (profile.lazy !== undefined && Object.hasOwn(profile.lazy, name)) return true;\n const ops = profile.ops;\n if (ops === undefined) return false;\n if (typeof ops !== \"function\") return Object.hasOwn(ops, name);\n try {\n return ops(name) !== undefined;\n } catch {\n return true;\n }\n };\n const hasExt = (name: string): boolean => (profile.ext !== undefined && Object.hasOwn(profile.ext, name)) || Object.hasOwn(STD_EXT, name);\n return (path, evaluator) => {\n if (evaluator !== \"formula.op\" && evaluator !== \"formula.ext\") return true;\n // The evaluators give the same reasons when they do not find the name.\n const name = path.slice(1).join(\".\");\n if (evaluator === \"formula.op\") return hasOp(name) ? true : `The language has no operation ${name}.`;\n return hasExt(name) ? true : `The language has no extension ${name}.`;\n };\n}\n\n/**\n * This function makes a machine for a formula language. It merges the kit and the parts that the language adds with\n * `mergeMachines`. Thus a kind `ops.*` or a namespace `ops` of the language extends the namespace of the kit, and\n * the fallback of the kit stays. The hook `known` of the kit comes from the profile (`formulaKnown`). A hook `known`\n * of the language answers after it.\n *\n * A kind or an evaluator of the language that differs from the entry of the kit with its name is a conflict. The\n * language names the path in `replaces` to replace the entry, for example `[\"world\", \"kinds\", \"ref\"]` or\n * `[\"evaluators\", \"formula.op\"]`. Then the hook of the kit does not answer for a replaced evaluator.\n *\n * @param profile - The operations and the rules of the language.\n * @param more - The parts of a machine that the language adds, with the paths of the entries that it replaces.\n * @returns The machine.\n * @throws {MergeError} The language and the kit have a conflict.\n */\nexport function formulaMachine(profile: FormulaProfile = {}, more: MachinePart = {}): Machine {\n return mergeMachines({ world: { kinds: formulaKinds() }, evaluators: formulaEvaluators(profile), known: formulaKnown(profile) }, more);\n}\n","import { type Envelope, type Json, type Key, isEnvelope, isRecord, typeName } from \"./doc.ts\";\nimport { ask } from \"./ladder.ts\";\nimport type { CapsRule, Kind } from \"./world.ts\";\nimport { type PartSlot, type Split, partsOf, pathMatches } from \"./parts.ts\";\nimport { type Cap, type Context, type HostThing, type Resolution, type ResolveOptions, type Thing, THING, isHostThing, resolve, valueOfThing, worldThing } from \"./deref.ts\";\nimport { STD_EVALUATORS } from \"./stdlib.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, placed, thrown } from \"./errors.ts\";\nimport {\n type AllOptions,\n type Effect,\n type EvalFn,\n type EvalInput,\n type Machine,\n type Part,\n type RunFn,\n type RunInput,\n type RunPart,\n type Steps,\n intersectCaps,\n makeContext,\n permits,\n} from \"./evaluate.ts\";\nimport { type FormulaProfile, type OpFn, Held, STD_EXT } from \"./formula.ts\";\n\n/*\n * The reference interpreter: a direct reading of the rules of docs/SPEC.md. It compiles nothing and caches nothing.\n * At each evaluation of a document, it asks the ladder, finds the kind, splits the value and calls the evaluator. A\n * part evaluates only when its evaluator asks. Thus it shares no compiler with a plan, and a test can compare them.\n */\n\n/**\n * The definitional code of the reference, by evaluator name. The reference cannot read compiled code, thus each\n * compiled evaluator or runner of a machine needs a definition here. A function evaluator needs none.\n */\nexport interface Definitions {\n readonly evaluators?: Readonly<Record<string, EvalFn>>;\n readonly runners?: Readonly<Record<string, RunFn>>;\n}\n\n/** The options of the reference interpreter. */\nexport interface ReferenceOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The definitional code of the compiled evaluators and runners of the machine. */\n readonly definitions?: Definitions;\n /** A list that gets each effect, in its order. */\n readonly effects?: Effect[];\n}\n\n/** The state of one evaluation of the reference. */\ninterface Env {\n readonly machine: Machine;\n readonly definitions: Definitions;\n readonly effects: Effect[];\n readonly maxDepth: number;\n}\n\n/** The code that answers a document: a function evaluator, a runner, or a gap of the reference. */\ntype Chosen = { readonly evaluator: EvalFn } | { readonly runner: RunFn } | { readonly gap: string };\n\n/** The answers of the ladder and of the contract of the kind for one document. */\ninterface Seen {\n readonly doc: Envelope;\n readonly kindText: string;\n readonly typePath: readonly Key[];\n readonly kind: Kind | undefined;\n readonly name: string;\n readonly chosen: Chosen;\n readonly split: Extract<Split, { readonly ok: true }>;\n}\n\n/** One position of a document: its value, its place, the type that it declares, its depth and its context. */\ninterface At {\n readonly value: unknown;\n readonly place: readonly Key[];\n readonly declared: string | undefined;\n readonly depth: number;\n readonly address: boolean;\n readonly ctx: Context;\n}\n\nfunction own<T>(table: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return table !== undefined && Object.hasOwn(table, name) ? table[name] : undefined;\n}\n\n/**\n * This function finds the code of an evaluator name. A runner wins over an evaluator of the same name. A standard\n * evaluator gets the definition of the reference, unless the options give another definition (REF.TREE).\n */\nfunction choose(env: Env, name: string): Chosen | undefined {\n const runner = own(env.machine.runners, name);\n if (runner !== undefined) {\n const defined = own(env.definitions.runners, name);\n if (defined !== undefined) return { runner: defined };\n return typeof runner === \"function\" ? { runner } : { gap: `The reference has no definition of the compiled runner ${name}.` };\n }\n const evaluator = own(env.machine.evaluators, name);\n if (evaluator === undefined) return undefined;\n const standard = evaluator === own(STD_EVALUATORS, name) ? own(STD_DEFINITIONS.evaluators, name) : undefined;\n const defined = own(env.definitions.evaluators, name) ?? standard;\n if (defined !== undefined) return { evaluator: defined };\n return typeof evaluator === \"function\" ? { evaluator } : { gap: `The reference has no definition of the compiled evaluator ${name}.` };\n}\n\n/**\n * This function reads one document by the rules, in their order. First come an envelope or a declared type\n * (EVAL.ERRORS) and the limit of the depth (PLAN.DEPTH). Then come the ladder (LADDER.*), an evaluator and the shape\n * of the parts (SHAPE.*).\n */\nfunction examine(env: Env, at: At): Seen | Failed {\n const { place, declared } = at;\n const world = env.machine.world;\n // The lookup of the kind and the split of the value are definitions of the model (D15): partsOf gives both.\n const read = partsOf(world, at.value, declared);\n if (!read.ok) return fail(read.code, read.reason, { place });\n if (at.depth > env.maxDepth) return fail(\"#DEPTH!\", `The nesting is deeper than ${env.maxDepth} documents.`, { place });\n const { doc, kind, split } = read;\n const kindText = typeName(doc.type);\n const answer = ask(world, read.declared ? {} : doc, \"eval\", declared === undefined ? {} : { declaredType: declared });\n if (answer.error === \"unknown-kind\") return fail(\"#KIND?\", `The world has no kind ${kindText}.`, { place });\n const name = answer.evaluator;\n const chosen = name === undefined ? undefined : choose(env, name);\n if (name === undefined || chosen === undefined) return fail(\"#NOEVAL\", `No rung gives an evaluator for ${kindText}.`, { place });\n if (!split.ok) return fail(\"#VALUE!\", split.reason, { place });\n return { doc, kindText, typePath: read.typePath ?? [], kind, name, chosen, split };\n}\n\n/** This function gives the capabilities that the rules of a kind give one part (D14, CAP.CONTRACT, CAP.ONLY). */\nfunction capsOfPart(rules: readonly CapsRule[] | undefined, path: readonly Key[], caps: readonly Cap[]): readonly Cap[] {\n let out = caps;\n for (const rule of rules ?? []) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(path, pattern))) continue;\n if (rule.rule === \"mask\") return [];\n if (rule.rule === \"only\") out = intersectCaps(out, rule.caps);\n }\n return out;\n}\n\n/**\n * This function gives the context of a part. A context that the evaluator gives keeps only the capabilities of the\n * parent (CAP.NARROW). Then the rules of the kind narrow it (CAP.CONTRACT).\n */\nfunction contextOfPart(seen: Seen, slot: PartSlot, parent: Context, given: Context | undefined): Context {\n const base = given === undefined || given === parent ? parent : { ...given, caps: given.caps.filter((cap) => permits(parent.caps, cap)) };\n const caps = capsOfPart(seen.kind?.caps, slot.path, base.caps);\n return caps === base.caps ? base : { ...base, caps };\n}\n\nfunction headerOf(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 partAt(seen: Seen, at: At, slot: PartSlot, given: Context | undefined): At {\n return {\n value: slot.item,\n place: at.place.concat(slot.path),\n declared: slot.of,\n depth: at.depth + 1,\n address: slot.address === true,\n ctx: contextOfPart(seen, slot, at.ctx, given),\n };\n}\n\n/** This function resolves a path with the full algorithm of `resolve`, not with its short path (DEREF.QUICK). */\nfunction resolveFully(machine: Machine, ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const found = resolve(machine, ctx, path, { hops: true });\n return options?.hops === true ? found : { ...found, hops: [] };\n}\n\n/** This function records an effect when the capabilities permit it (RUN.CAP, CAP.HOOK). */\nfunction record(env: Env, ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Failed | undefined {\n const keys = typeof kind === \"string\" ? kind.split(\".\") : kind;\n const text = keys.join(\".\");\n const machine = env.machine;\n const allowed = machine.permits === undefined ? permits(ctx.caps, keys) : machine.permits(ctx.caps, keys, ctx);\n if (!allowed) return fail(\"#CAP!\", `The context has no capability for the effect ${text}.`, { place });\n env.effects.push({ index: env.effects.length, kind: text, path: keys, payload, node: -1, at: 0, place, context: ctx });\n return undefined;\n}\n\n/** This function evaluates a document. Each error gets the place of the document where it started (K5). */\nfunction evaluateAt(env: Env, at: At): Result {\n const seen = examine(env, at);\n if (!(\"doc\" in seen)) return seen;\n return evaluateSeen(env, seen, at);\n}\n\nfunction evaluateSeen(env: Env, seen: Seen, at: At): Result {\n const { chosen } = seen;\n const { place } = at;\n if (\"gap\" in chosen) return fail(\"#NOEVAL\", chosen.gap, { place });\n if (\"runner\" in chosen) return drive(runSeen(env, seen, at, chosen.runner), place);\n const input = evalInput(env, seen, at);\n try {\n return placed(chosen.evaluator(input), place);\n } catch (error) {\n return placed(thrown(error, `the evaluator ${seen.name}`), place);\n }\n}\n\n/** This function gives the steps of a document for a runner. Nothing happens before the first step. */\nfunction* stepsAt(env: Env, at: At): Steps {\n const seen = examine(env, at);\n if (!(\"doc\" in seen)) return seen;\n if (\"runner\" in seen.chosen) return yield* runSeen(env, seen, at, seen.chosen.runner);\n return evaluateSeen(env, seen, at);\n}\n\nfunction* runSeen(env: Env, seen: Seen, at: At, runner: RunFn): Steps {\n try {\n return placed(yield* runner(runInput(env, seen, at)), at.place);\n } catch (error) {\n return placed(thrown(error, `the runner ${seen.name}`), at.place);\n }\n}\n\n/** This function drives steps that cannot wait. A step that waits gives `#CALC!` at the document (RUN.WAIT). */\nfunction drive(steps: Steps, place: readonly Key[]): Result {\n const step = steps.next();\n if (step.done === true) return step.value;\n void step.value.catch(() => undefined);\n const waited = fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\", { place });\n steps.return(waited);\n return waited;\n}\n\nfunction evalInput(env: Env, seen: Seen, at: At): EvalInput {\n const { split, doc } = seen;\n const parts: Part[] = split.parts.map((slot) => {\n const name = headerOf(slot.item);\n return {\n key: slot.key,\n path: slot.path,\n ...(name === undefined ? {} : { name }),\n evaluate: (given?: Context) => evaluateAt(env, partAt(seen, at, slot, given)),\n };\n });\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n return {\n kind: seen.kindText,\n typePath: seen.typePath,\n doc,\n value: fill(parts),\n data: split.data,\n parts,\n context: at.ctx,\n place: at.place,\n ...(at.address ? { address: true } : {}),\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: (kind, payload) => record(env, at.ctx, kind, payload, at.place) ?? ok(payload),\n fill,\n };\n}\n\nfunction runInput(env: Env, seen: Seen, at: At): RunInput {\n const { split, doc } = seen;\n const parts: RunPart[] = split.parts.map((slot) => {\n const name = headerOf(slot.item);\n return {\n key: slot.key,\n path: slot.path,\n ...(name === undefined ? {} : { name }),\n evaluate: (given?: Context) => stepsAt(env, partAt(seen, at, slot, given)),\n };\n });\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n return {\n kind: seen.kindText,\n typePath: seen.typePath,\n doc,\n value: fill(parts),\n data: split.data,\n parts,\n context: at.ctx,\n place: at.place,\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: function* (kind, payload) {\n return record(env, at.ctx, kind, payload, at.place) ?? ok(payload);\n },\n all: (list, options) => together(list, options),\n fill,\n };\n}\n\n/**\n * This function evaluates parts for `all` (RUN.ALL). The parts start in their order, up to the limit, and each part\n * goes on until it ends or waits. In an evaluation, a part that waits does not end, thus it keeps its place in the\n * limit. With `failFast`, the first failure stops the parts that wait, and the later parts do not start\n * (RUN.FAIL-FAST). When no part failed and a part waits, the steps wait, and the drive gives `#CALC!`.\n */\nfunction* together(list: readonly RunPart[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n const limit = Math.max(1, options.concurrency ?? list.length);\n const results: (Result | undefined)[] = list.map(() => undefined);\n const waiting: { readonly steps: Steps; readonly promise: Promise<unknown> }[] = [];\n let failed = false;\n for (let index = 0; index < list.length && !failed && waiting.length < limit; index += 1) {\n let result: Result | undefined;\n try {\n const steps = (list[index] as RunPart).evaluate();\n const step = steps.next();\n if (step.done === true) result = step.value;\n else waiting.push({ steps, promise: step.value });\n } catch (error) {\n result = thrown(error, \"a part\");\n }\n results[index] = result;\n if (result !== undefined && options.failFast === true && !result.ok) failed = true;\n }\n if (failed) {\n const stopped = fail(\"#ABORT\", \"The part stopped: a part before it failed, and the parts run with failFast.\");\n for (const item of waiting) {\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 return results.map((result) => result ?? stopped);\n }\n if (waiting.length > 0) yield Promise.race(waiting.map((item) => item.promise));\n // An evaluation stops at the first wait, thus only parts that ended reach this line.\n return results as readonly Result[];\n}\n\n/**\n * This function evaluates a document by the rules, without a compilation. It is the reference of the plans: a plan,\n * a traced plan and the second tier of a language must give its results. It covers evaluations, not runs: an effect\n * gives its payload, and a part that waits gives `#CALC!`.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document.\n * @param context - The names and the capabilities at the root.\n * @param options - The type of a bare root value, the definitions of compiled code, and a list for the effects.\n * @returns The result.\n */\nexport function reference(machine: Machine, doc: unknown, context: Context = makeContext(), options: ReferenceOptions = {}): Result {\n const env: Env = { machine, definitions: options.definitions ?? {}, effects: options.effects ?? [], maxDepth: machine.maxDepth ?? 1000 };\n const ctx = context.world === null ? { ...context, world: worldThing(machine.world) } : context;\n try {\n return evaluateAt(env, { value: doc, place: [], declared: options.declaredType, depth: 0, address: false, ctx });\n } catch (error) {\n return placed(thrown(error, \"the reference\"), []);\n }\n}\n\n/*\n * The definition of the decorated tree (TREE.*), written from docs/SPEC.md. It shares no code with `tree.node` of\n * stdlib.ts: its nodes, its memo, its marks for attributes in evaluation and its JSON are its own.\n */\n\n/** One tree of the reference in one evaluation. */\ninterface RefTree {\n open: boolean;\n}\n\n/** A node of the reference. Its host thing is the key of the table `refNodes`. */\ninterface RefNode {\n readonly tree: RefTree;\n readonly kind: string;\n readonly place: readonly Key[];\n readonly parts: readonly Part[];\n readonly ctx: Context;\n /** The results of the attributes that ended. */\n readonly values: Map<string, Result>;\n /** The attributes in evaluation. */\n readonly pending: Set<string>;\n}\n\nconst refNodes = new WeakMap<object, RefNode>();\n\n/** The attributes in evaluation in the reference, in the order of their demands (TREE.CYCLE). */\nconst inEvaluation: { readonly node: RefNode; readonly name: string }[] = [];\n\nfunction nameOfAttribute(node: RefNode, name: string): string {\n return `${name} of ${node.kind} at [${node.place.join(\", \")}]`;\n}\n\nfunction refNodeOf(thing: unknown): RefNode | undefined {\n return typeof thing === \"object\" && thing !== null ? refNodes.get(thing) : undefined;\n}\n\n/** TREE.ONCE, TREE.MEMO and TREE.CYCLE: the result of one attribute, or `undefined` when the node has no such part. */\nfunction attributeOf(node: RefNode, self: HostThing, name: string): Result | undefined {\n const done = node.values.get(name);\n if (done !== undefined) return done;\n if (node.pending.has(name)) {\n const from = inEvaluation.findIndex((entry) => entry.node === node && entry.name === name);\n const steps = from < 0 ? [nameOfAttribute(node, name)] : inEvaluation.slice(from).map((entry) => nameOfAttribute(entry.node, entry.name));\n return fail(\"#CYCLE!\", `The attributes form a cycle: ${[...steps, nameOfAttribute(node, name)].join(\" -> \")}.`);\n }\n const part = node.parts.find((item) => item.key === name);\n if (part === undefined) return undefined;\n node.pending.add(name);\n inEvaluation.push({ node, name });\n try {\n const result = part.evaluate({ ...node.ctx, self });\n node.values.set(name, result);\n return result;\n } finally {\n node.pending.delete(name);\n inEvaluation.pop();\n }\n}\n\n/** TREE.RESULT: the JSON of a node. `open` holds the nodes and the containers whose JSON is in progress. */\nfunction jsonOfNode(node: RefNode, self: HostThing, open: readonly object[]): Result {\n const record: Record<string, unknown> = {};\n for (const part of node.parts) {\n const result = attributeOf(node, self, part.key) as Result;\n if (!result.ok) return result;\n const value = plainValue(result.value, [...open, self]);\n if (!value.ok) return value;\n setField(record, part.key, value.value);\n }\n return ok(record);\n}\n\n/** This function gives a copy of a value with the JSON of each node in it. */\nfunction plainValue(value: unknown, open: readonly object[]): Result {\n const node = refNodeOf(value);\n if (node !== undefined) {\n if (open.includes(value as object)) return fail(\"#CYCLE!\", `The JSON of the node ${node.kind} at [${node.place.join(\", \")}] holds the node itself.`);\n return jsonOfNode(node, value as HostThing, open);\n }\n if (typeof value !== \"object\" || value === null || isHostThing(value) || open.includes(value)) return ok(value);\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n for (const item of value) {\n const plain = plainValue(item, [...open, value]);\n if (!plain.ok) return plain;\n items.push(plain.value);\n }\n return ok(items);\n }\n if (!isRecord(value)) return ok(value);\n const copy: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const plain = plainValue(value[key], [...open, value]);\n if (!plain.ok) return plain;\n setField(copy, key, plain.value);\n }\n return ok(copy);\n}\n\n/**\n * TREE.LAZY, TREE.PARENT, TREE.SIBLING and TREE.ERROR: a node of an open tree gives its thing, and the root of a new\n * tree gives its JSON. A step on the thing reads an attribute, and a failed attribute throws its own error.\n */\nconst treeDefinition: EvalFn = ({ parts, context, kind, place }) => {\n const outer = refNodeOf(context.self);\n const nested = outer !== undefined && outer.tree.open;\n const node: RefNode = { tree: nested ? outer.tree : { open: true }, kind, place, parts, ctx: context, values: new Map(), pending: new Set() };\n const self: HostThing & { readonly type: string } = {\n [THING]: true,\n type: kind,\n label: `node ${kind}`,\n deref: (key): Thing | undefined => {\n if (key === \"parent\") return context.self;\n if (key === \"type\") return kind;\n const result = attributeOf(node, self, String(key));\n if (result === undefined || result.ok) return result?.ok === true ? result.value : undefined;\n throw new Failure(result.error);\n },\n toJson: () => {\n const result = jsonOfNode(node, self, []);\n if (result.ok) return result.value;\n throw new Failure(result.error);\n },\n };\n refNodes.set(self, node);\n if (nested) return ok(self);\n try {\n return jsonOfNode(node, self, []);\n } finally {\n node.tree.open = false;\n }\n};\n\n/**\n * The definitions of the reference for the evaluators of the standard machine that need their own reading. The\n * reference uses them for the standard evaluators, also without the option `definitions`. It holds `tree.node`.\n */\nexport const STD_DEFINITIONS: Definitions = { evaluators: { \"tree.node\": treeDefinition } };\n\n/* The definitions of the formula kit: one function evaluator for each construct, written from docs/SPEC.md. */\n\nconst CLOSURE: unique symbol = Symbol.for(\"coeval.closure\") as never;\n\n/** This function sets an own field, also the field `__proto__` (SHAPE.PROTO). */\nfunction setField(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\nfunction partNamed(parts: readonly Part[], key: string): Part | undefined {\n return parts.find((part) => part.path.length === 1 && part.path[0] === key);\n}\n\nfunction partsUnder(parts: readonly Part[], key: string): readonly Part[] {\n return parts.filter((part) => part.path.length === 2 && part.path[0] === key);\n}\n\n/**\n * This function gives the definitions of the formula kit for one profile. Each construct is a function evaluator in\n * the most direct style. It shares no code with the compilers of `formulaEvaluators`, thus the two readings of the\n * rules can disagree, and a test finds it.\n *\n * @param profile - The operations and the rules of the language.\n * @returns The definitions, by evaluator name.\n */\nexport function formulaDefinitions(profile: FormulaProfile = {}): Definitions {\n const truthy = profile.truthy ?? ((value: unknown): boolean | undefined => (typeof value === \"boolean\" ? value : undefined));\n const opOf = (name: string): OpFn | undefined => (typeof profile.ops === \"function\" ? profile.ops(name) : own(profile.ops, name));\n const noTruth = (what: string): Failed => fail(\"#VALUE!\", `The ${what} must give a truth value.`);\n\n /** FORMULA.LIST, FORMULA.OPS and FORMULA.COMBINE: the values of parts in order, or the error. */\n const valuesOf = (parts: readonly Part[], skip?: (error: EvalError) => boolean): { readonly values: readonly (unknown | typeof SKIP)[] } | Failed => {\n const values: unknown[] = [];\n const errors: EvalError[] = [];\n for (const part of parts) {\n const result = part.evaluate();\n if (result.ok) values.push(result.value);\n else if (skip?.(result.error) === true) values.push(SKIP);\n else if (profile.combine === undefined) return result;\n else errors.push(result.error);\n }\n if (errors.length === 0 || profile.combine === undefined) return { values };\n return { ok: false, error: errors.length === 1 ? (errors[0] as EvalError) : profile.combine(errors) };\n };\n\n const lit: EvalFn = ({ doc }) => ok(doc.value);\n\n const ref: EvalFn = ({ doc, parts, fill, address, context, resolve: walk }) => {\n const path = doc.value;\n if (!Array.isArray(path) || path.length === 0) return fail(\"#VALUE!\", 'The value of ref is a path: a list that starts with a root, for example [\"names\", \"a\"].');\n // FORMULA.STEPS: the step documents of the path are parts. They evaluate first, in order.\n let steps: readonly unknown[] = path;\n if (parts.length > 0) {\n const all = valuesOfStrict(parts);\n if (!(\"values\" in all)) return all;\n steps = fill(all.values) as readonly unknown[];\n }\n // FORMULA.LET: 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 bound = head === undefined ? undefined : own(context.names, head);\n if (bound instanceof Held) return { ok: false, error: bound.error };\n const found = walk(steps);\n if (!found.ok) return fail(found.code, found.reason);\n // FORMULA.ADDRESS: an address gives what the path reaches.\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 (profile.missing?.(reached) === true) return fail(\"#N/A\", \"The path reaches no value.\");\n return ok(reached);\n };\n\n const step: EvalFn = ({ doc, parts, fill }) => {\n if (parts.length === 0) return ok(doc);\n const all = valuesOfStrict(parts);\n return \"values\" in all ? ok({ ...doc, value: fill(all.values) as Json }) : all;\n };\n\n const record: EvalFn = ({ parts }) => {\n const all = valuesOf(parts, profile.omit);\n if (!(\"values\" in all)) return all;\n const out: Record<string, unknown> = {};\n parts.forEach((part, index) => {\n const value = all.values[index];\n if (value !== SKIP) setField(out, String(part.path[0]), value);\n });\n return ok(out);\n };\n\n const list: EvalFn = ({ parts }) => {\n const all = valuesOf(parts);\n return \"values\" in all ? ok([...all.values]) : all;\n };\n\n const letIn: EvalFn = ({ parts, context }) => {\n const names: Record<string, unknown> = {};\n for (const key of Object.keys(context.names)) setField(names, key, context.names[key]);\n for (const binding of partsUnder(parts, \"bind\")) {\n const result = binding.evaluate();\n setField(names, String(binding.path[1]), result.ok ? result.value : new Held(result.error));\n }\n return (partNamed(parts, \"body\") as Part).evaluate({ ...context, names });\n };\n\n const fn: EvalFn = ({ data, parts, context }) => {\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 return fail(\"#VALUE!\", \"The params of fn are a list of different texts.\");\n }\n const names = params as readonly string[];\n const body = partNamed(parts, \"body\") as Part;\n const closure = (...args: readonly unknown[]): unknown => {\n const scope: Record<string, unknown> = {};\n for (const key of Object.keys(context.names)) setField(scope, key, context.names[key]);\n names.forEach((name, index) => setField(scope, name, args[index]));\n const result = body.evaluate({ ...context, names: scope });\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 const call: EvalFn = ({ parts }) => {\n const target = (partNamed(parts, \"fn\") as Part).evaluate();\n if (!target.ok) return target;\n if (typeof target.value !== \"function\") return fail(\"#VALUE!\", \"The fn of call must give a function.\");\n const all = valuesOfStrict(partsUnder(parts, \"args\"));\n if (!(\"values\" in all)) return all;\n try {\n return ok((target.value as (...items: unknown[]) => unknown)(...all.values));\n } catch (error) {\n return thrown(error, \"the function of call\");\n }\n };\n\n const choice: EvalFn = ({ parts }) => {\n const test = (partNamed(parts, \"test\") as Part).evaluate();\n if (!test.ok) return test;\n const truth = truthy(test.value);\n if (truth === undefined) return noTruth(\"test of if\");\n if (truth) return (partNamed(parts, \"then\") as Part).evaluate();\n const other = partNamed(parts, \"else\");\n if (other !== undefined) return other.evaluate();\n return ok(Object.hasOwn(profile, \"otherwise\") ? profile.otherwise : null);\n };\n\n /** FORMULA.LOGIC: `and` stops at the first false term, and `or` at the first true term. */\n const logic =\n (stopAt: boolean, what: string): EvalFn =>\n ({ parts }) => {\n let last: Result = ok(!stopAt);\n for (const part of parts) {\n last = part.evaluate();\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return noTruth(what);\n if (truth === stopAt) return profile.logic === \"value\" ? last : ok(stopAt);\n }\n return profile.logic === \"value\" ? last : ok(!stopAt);\n };\n\n const op: EvalFn = ({ typePath, parts }) => {\n const name = typePath.slice(1).join(\".\");\n const lazy = own(profile.lazy, name);\n if (lazy !== undefined) {\n try {\n return lazy(parts.map((part) => () => part.evaluate()));\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n }\n const apply = opOf(name) as ((...args: unknown[]) => unknown) | undefined;\n if (apply === undefined) return fail(\"#NAME?\", `The language has no operation ${name}.`);\n const all = valuesOf(parts);\n if (!(\"values\" in all)) return all;\n try {\n const out = apply(...all.values);\n return profile.check?.(out, name) ?? ok(out);\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n };\n\n const ext: EvalFn = ({ typePath, doc, context }) => {\n const name = typePath.slice(1).join(\".\");\n const handler = own(profile.ext, name) ?? own(STD_EXT, name);\n if (handler === undefined) return fail(\"#NAME?\", `The language has no extension ${name}.`);\n try {\n return handler(doc.value, context);\n } catch (error) {\n return thrown(error, `the extension ${name}`);\n }\n };\n\n return {\n evaluators: {\n \"formula.lit\": lit,\n \"formula.ref\": ref,\n \"formula.step\": step,\n \"formula.record\": record,\n \"formula.list\": list,\n \"formula.let\": letIn,\n \"formula.fn\": fn,\n \"formula.call\": call,\n \"formula.if\": choice,\n \"formula.and\": logic(false, \"term of and\"),\n \"formula.or\": logic(true, \"term of or\"),\n \"formula.op\": op,\n \"formula.ext\": ext,\n },\n };\n}\n\n/** The mark of a field that the profile leaves out of a record (FORMULA.RECORD). */\nconst SKIP: unique symbol = Symbol(\"skip\");\n\n/** The values of parts in order. The first error stops them, also with `combine` (FORMULA.STEPS, FORMULA.FN). */\nfunction valuesOfStrict(parts: readonly Part[]): { readonly values: readonly unknown[] } | Failed {\n const values: unknown[] = [];\n for (const part of parts) {\n const result = part.evaluate();\n if (!result.ok) return result;\n values.push(result.value);\n }\n return { values };\n}\n","import { type Key, docEquals, isRecord } from \"./doc.ts\";\nimport type { Context } from \"./deref.ts\";\nimport { type EvalError, type Result, isStackOverflow, thrown } from \"./errors.ts\";\nimport { type Effect, type Machine, evaluate, makeContext, prepare } from \"./evaluate.ts\";\nimport { Held, isClosure } from \"./formula.ts\";\nimport { type Definitions, reference } from \"./reference.ts\";\n\n/**\n * A tier that `agree` compares with the plan.\n *\n * - `reference`: the reference interpreter, which compiles nothing.\n * - `traced`: the traced evaluation, `evaluate`.\n * - `again`: a second evaluation of the same plan.\n * - `other`: the second tier of a language, from the option `other`.\n */\nexport type Tier = \"reference\" | \"traced\" | \"again\" | \"other\";\n\n/** What a second tier gives: its result, and its effects when it records them. */\nexport interface TierResult {\n readonly result: Result;\n readonly effects?: readonly Effect[];\n}\n\n/** The options of `agree`. */\nexport interface AgreeOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The definitional code of the compiled evaluators of the machine, for the reference. */\n readonly definitions?: Definitions;\n /** The tiers to compare with the plan. The default is the reference, the traced evaluation and a second evaluation. */\n readonly tiers?: readonly Exclude<Tier, \"other\">[];\n /**\n * This function gives the result of the second tier of a language, for example a compiler to loops.\n *\n * @param doc - The document.\n * @param context - The context.\n * @returns The result, or the result with the effects.\n */\n readonly other?: (doc: unknown, context: Context) => Result | TierResult;\n /**\n * This function compares two values that the rules of `sameValue` do not know, for example two dates.\n *\n * @param a - The value of the plan.\n * @param b - The value of the other tier.\n * @returns `true` or `false`, or `undefined` to use the rules of `sameValue`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n /** `true`: two errors must also have the same reason, and each error must have a place. */\n readonly strict?: boolean;\n /**\n * This function gives what the host saw since its last call, for example the calls of an operation. `agree` uses\n * it before the plan and after each tier, and compares the results. Thus a tier that evaluates a part that the plan\n * does not evaluate fails.\n *\n * @returns What the host saw.\n */\n readonly observe?: () => unknown;\n}\n\n/** The outcome of `agree`: the result of the plan, or the first tier that disagrees with it. */\nexport type Agreement =\n | { readonly ok: true; readonly result: Result; readonly effects: readonly Effect[] }\n | {\n readonly ok: false;\n readonly tier: Tier;\n /** The result of the plan. */\n readonly plan: Result;\n /** The result of the tier that disagrees. */\n readonly other: Result;\n /** One sentence that tells the difference. */\n readonly reason: string;\n };\n\n/**\n * This function tells if two values are the same for `agree`. Lists and plain records compare item by item and field\n * by field, and the order of the fields does not matter. Each other leaf compares with `Object.is`, thus `-0` is not\n * `0`, and `NaN` is `NaN`. The identity of a list or of a plain record is not compared.\n *\n * Two closures of `fn` are the same when they have the same parameters. Two `Held` values are the same when their\n * errors have the same code and place. Each other object is the same only as itself, unless the rule of the caller\n * tells otherwise.\n *\n * `docEquals` uses the same rules for lists, plain records and the other objects. It has no rules for closures, for\n * `Held` values and for a rule of the caller. Thus two closures are equal there only when they are the same function.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param equal - The rule of the caller for other values. It answers first, and `undefined` gives the rules above.\n * @returns `true` when the values are the same.\n */\nexport function sameValue(a: unknown, b: unknown, equal?: (a: unknown, b: unknown) => boolean | undefined): boolean {\n const stack: (readonly [unknown, unknown])[] = [[a, b]];\n const seen = new Map<object, Set<object>>();\n while (stack.length > 0) {\n const [x, y] = stack.pop() as readonly [unknown, unknown];\n if (Object.is(x, y)) continue;\n const told = equal?.(x, y);\n if (told !== undefined) {\n if (told) continue;\n return false;\n }\n if (typeof x !== \"object\" && typeof x !== \"function\") return false;\n if (typeof y !== \"object\" && typeof y !== \"function\") return false;\n if (x === null || y === null) return false;\n // A pair that the comparison already visits is the same, unless another pair shows a difference.\n const pairs = seen.get(x) ?? new Set<object>();\n if (pairs.has(y)) continue;\n pairs.add(y);\n seen.set(x, pairs);\n if (isClosure(x) || isClosure(y)) {\n if (!(isClosure(x) && isClosure(y))) return false;\n stack.push([closureParams(x), closureParams(y)]);\n continue;\n }\n if (x instanceof Held || y instanceof Held) {\n if (!(x instanceof Held && y instanceof Held) || errorDiffers(x.error, y.error, false) !== undefined) return false;\n continue;\n }\n if (Array.isArray(x) || Array.isArray(y)) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) return false;\n for (let index = 0; index < x.length; index += 1) stack.push([x[index], y[index]]);\n continue;\n }\n if (!isRecord(x) || !isRecord(y)) return false;\n const keys = Object.keys(x);\n if (keys.length !== Object.keys(y).length) return false;\n for (const key of keys) {\n if (!Object.hasOwn(y, key)) return false;\n stack.push([x[key], y[key]]);\n }\n }\n return true;\n}\n\nconst CLOSURE = Symbol.for(\"coeval.closure\");\n\nfunction closureParams(fn: object): unknown {\n return (fn as { readonly [CLOSURE]?: { readonly params: readonly string[] } })[CLOSURE]?.params;\n}\n\nfunction codeAndPlace(error: EvalError): string {\n return error.place === undefined ? error.code : `${error.code} at [${error.place.join(\", \")}]`;\n}\n\n/** This function gives the difference of two errors, or `undefined` when they agree. */\nfunction errorDiffers(a: EvalError, b: EvalError, strict: boolean): string | undefined {\n if (a.code !== b.code) return `The plan gives ${codeAndPlace(a)}, and the tier gives ${codeAndPlace(b)}.`;\n if (strict && (a.place === undefined || b.place === undefined)) return `An error ${a.code} has no place.`;\n if (a.place !== undefined && b.place !== undefined && !docEquals(a.place as readonly Key[], b.place as readonly Key[])) {\n return `The error ${a.code} has the place [${a.place.join(\", \")}] in the plan, and [${b.place.join(\", \")}] in the tier.`;\n }\n if (strict && a.reason !== b.reason) return `The error ${a.code} has another reason in the tier: \"${b.reason}\" for \"${a.reason}\".`;\n return undefined;\n}\n\n/** A host stack overflow is the one permitted difference (VALUE.DEPTH): the tiers use different numbers of frames. */\nfunction overflowed(result: Result): boolean {\n return !result.ok && result.error.code === \"#DEPTH!\" && isStackOverflow(result.error.cause);\n}\n\n/** This function gives the difference of two results, or `undefined` when they agree. */\nfunction resultDiffers(a: Result, b: Result, options: AgreeOptions): string | undefined {\n if (a.ok && b.ok) return sameValue(a.value, b.value, options.equal) ? undefined : \"The plan and the tier give different values.\";\n if (!a.ok && !b.ok) return errorDiffers(a.error, b.error, options.strict === true);\n return a.ok ? `The plan gives a value, and the tier gives ${codeAndPlace((b as { readonly error: EvalError }).error)}.` : `The plan gives ${codeAndPlace(a.error)}, and the tier gives a value.`;\n}\n\n/** This function gives the difference of two lists of effects, or `undefined` when they agree (EFFECT.ORDER). */\nfunction effectsDiffer(a: readonly Effect[], b: readonly Effect[], options: AgreeOptions): string | undefined {\n if (a.length !== b.length) return `The plan causes ${a.length} effects, and the tier causes ${b.length}.`;\n for (let index = 0; index < a.length; index += 1) {\n const x = a[index] as Effect;\n const y = b[index] as Effect;\n if (x.kind !== y.kind || !docEquals(x.place as readonly Key[], y.place as readonly Key[]) || !sameValue(x.payload, y.payload, options.equal)) {\n return `The effect ${index} differs: ${x.kind} at [${x.place.join(\", \")}] in the plan, and ${y.kind} at [${y.place.join(\", \")}] in the tier.`;\n }\n }\n return undefined;\n}\n\n/**\n * This function evaluates a document with a plan and with other tiers, and compares the results (PLAN.AGREES). Two\n * results agree when they have the same value by `sameValue`, or errors with the same code, and the same place when\n * both have one. The effects must have the same kinds, places and payloads, in the same order. A language gives its\n * own tier with the option `other`.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document.\n * @param context - The names and the capabilities at the root.\n * @param options - The tiers, the definitions for the reference, the rules of the comparison and the second tier.\n * @returns The result of the plan, or the first tier that disagrees and the reason.\n */\nexport function agree(machine: Machine, doc: unknown, context: Context = makeContext(), options: AgreeOptions = {}): Agreement {\n const declared = options.declaredType === undefined ? {} : { declaredType: options.declaredType };\n const observe = options.observe;\n observe?.();\n const plan = prepare(machine, doc, declared);\n const effects: Effect[] = [];\n const result = plan.evaluate(context, { effects });\n const saw = observe?.();\n\n const differs = (other: Result, otherEffects: readonly Effect[] | undefined): string | undefined => {\n if (overflowed(result) || overflowed(other)) return undefined;\n const why = resultDiffers(result, other, options) ?? (otherEffects === undefined ? undefined : effectsDiffer(effects, otherEffects, options));\n if (why !== undefined || observe === undefined) return why;\n return sameValue(saw, observe(), options.equal) ? undefined : \"The host saw other calls in the tier.\";\n };\n\n for (const tier of options.tiers ?? [\"reference\", \"traced\", \"again\"]) {\n let other: Result;\n let otherEffects: Effect[] = [];\n if (tier === \"reference\") {\n other = reference(machine, doc, context, { ...declared, effects: otherEffects, ...(options.definitions === undefined ? {} : { definitions: options.definitions }) });\n } else if (tier === \"traced\") {\n const traced = evaluate(machine, doc, context, options.declaredType);\n other = traced.result;\n otherEffects = [...traced.effects];\n } else {\n other = plan.evaluate(context, { effects: otherEffects });\n }\n const why = differs(other, otherEffects);\n if (why !== undefined) return { ok: false, tier, plan: result, other, reason: why };\n }\n\n if (options.other !== undefined) {\n let given: Result | TierResult;\n try {\n given = options.other(doc, context);\n } catch (error) {\n given = thrown(error, \"the tier\");\n }\n const other = \"result\" in given ? given.result : given;\n const why = differs(other, \"result\" in given ? given.effects : undefined);\n if (why !== undefined) return { ok: false, tier: \"other\", plan: result, other, reason: why };\n }\n return { ok: true, result, effects };\n}\n","import { type Json, type Key, docEquals, isEnvelope, typePath } from \"./doc.ts\";\nimport { type Kind, type ScopeRule, type Shape, type World, type WorldEntry, isAlias, isKind, isNamespace, lookupKind } from \"./world.ts\";\nimport { pathMatches } from \"./parts.ts\";\nimport { ROOTS, type Root } from \"./deref.ts\";\n\n/** A source of random numbers with a seed. The same seed gives the same numbers. */\nexport interface Random {\n /** This function gives a number from 0 up to 1, without 1. */\n next(): number;\n /** This function gives a whole number from 0 up to `below`, without `below`. */\n int(below: number): number;\n /** This function gives `true` with the chance `p`. */\n chance(p: number): boolean;\n /** This function gives one item of a list that is not empty. */\n pick<T>(items: readonly T[]): T;\n}\n\n/**\n * This function makes a source of random numbers with a seed (the algorithm mulberry32). It needs no package.\n *\n * @param seed - The seed: a whole number.\n * @returns The source.\n */\nexport function random(seed: number): Random {\n let state = seed >>> 0;\n const next = (): number => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n const int = (below: number): number => Math.floor(next() * below);\n return { next, int, chance: (p) => next() < p, pick: (items) => items[int(items.length)] as never };\n}\n\n/** The options of `generate`. */\nexport interface GenerateOptions {\n /** The seed. The same seed and the same options give the same document. */\n readonly seed: number;\n /** The types that a document can have. The default is `typesOf(world)`. A namespace with a fallback needs its keys here. */\n readonly types?: readonly (readonly Key[])[];\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 deepest nesting of documents. The default is 4. */\n readonly maxDepth?: number;\n /** The most documents in one document. The default is 24. */\n readonly maxSize?: number;\n /** The chance of a malformed choice at each document. The default is 0.05. */\n readonly malformed?: number;\n /**\n * This function gives the data of a document of a type without parts, for example a number for the kind `number`.\n *\n * @param type - The keys of the type.\n * @param random - The source of random numbers.\n * @returns The data, or `undefined` for a random JSON value.\n */\n readonly data?: (type: readonly Key[], random: Random) => Json | undefined;\n /**\n * This function gives the types to prefer for a part, for example a function for the field `fn` of `call`.\n *\n * @param type - The keys of the type of the parent.\n * @param path - The path of the part in the value of the parent.\n * @returns The types, or `undefined` for no preference.\n */\n readonly hints?: (type: readonly Key[], path: readonly Key[]) => readonly (readonly Key[])[] | undefined;\n /** The evaluator names for own entries. The default is none. */\n readonly own?: readonly string[];\n /** The keys for the steps of a path after its root and its name. */\n readonly keys?: readonly Key[];\n /** The roots that a path can start at. The default is each root. */\n readonly roots?: readonly Root[];\n /** The most steps of a path after its root and its name. The default is 2. */\n readonly steps?: number;\n}\n\n/**\n * This function lists the types of a world: each kind and each alias, also in a namespace. A namespace with a\n * fallback gives no types, because each key names a kind.\n *\n * @param world - The world.\n * @returns The keys of each type.\n */\nexport function typesOf(world: World): readonly (readonly Key[])[] {\n const out: (readonly Key[])[] = [];\n const visit = (entries: Readonly<Record<string, WorldEntry>>, prefix: readonly Key[]): void => {\n for (const key of Object.keys(entries)) {\n const entry = entries[key];\n if (isKind(entry) || isAlias(entry)) out.push([...prefix, key]);\n else if (isNamespace(entry)) visit(entry.kinds, [...prefix, key]);\n }\n };\n visit(world.kinds, []);\n return out;\n}\n\nconst NAMES = [\"a\", \"b\", \"x\", \"n\", \"last\", \"__proto__\"] as const;\nconst FIELDS = [\"a\", \"b\", \"c\", \"1\", \"__proto__\"] as const;\nconst KEYS: readonly Key[] = [\"a\", \"b\", \"x\", 0, 1, \"0\", \"length\", \"type\", \"value\", \"parent\"];\n\n/** This function tells if a kind can be a leaf: it needs no part. */\nfunction leafKind(kind: Kind | undefined): boolean {\n const shape = kind?.parts;\n return shape === undefined || shape.shape === \"none\" || shape.shape === \"list\" || shape.shape === \"map\" || shape.shape === \"text\" || shape.shape === \"number\" || shape.shape === \"one\";\n}\n\n/** A position of a document: the type that it declares, the kinds that it permits, the names that it sees and its depth. */\ninterface Position {\n readonly declared: string | undefined;\n readonly kinds: readonly (readonly Key[])[] | undefined;\n readonly names: readonly string[];\n readonly depth: number;\n readonly hint: readonly (readonly Key[])[] | undefined;\n}\n\n/** The names that the scope rules of one document bind, and the parts that see them. */\ninterface Scope {\n readonly rules: readonly ScopeRule[];\n /** The names of each rule, or the names of the headers so far for a rule `headers`. */\n readonly names: string[][];\n /** The number of parts that each rule covered so far. */\n readonly covered: number[];\n /** The data of a source of names, by its path as one text. */\n readonly sources: Map<string, { readonly keys: readonly string[] } | { readonly list: readonly string[] } | { readonly text: string }>;\n}\n\n/**\n * This function builds a random document for a world from the contracts of its kinds. It reads the shapes of the\n * parts, the declared types, the permitted kinds and the names that the scope rules bind. Some choices are malformed\n * on purpose, for example an unknown kind or an unknown name under a namespace with a fallback. Other examples are a\n * value without its shape, a bare value without a type and a name that nothing binds. The depth and the size have\n * limits.\n *\n * @param world - The world.\n * @param options - The seed, the types, the limits and the data of the leaves.\n * @returns The document, as JSON.\n */\nexport function generate(world: World, options: GenerateOptions): unknown {\n const rng = random(options.seed);\n const types = options.types ?? typesOf(world);\n const maxDepth = options.maxDepth ?? 4;\n const maxSize = options.maxSize ?? 24;\n const malformed = options.malformed ?? 0.05;\n const keys = options.keys ?? KEYS;\n const steps = options.steps ?? 2;\n const roots: readonly Root[] = options.roots ?? ROOTS;\n const stepTypes = types.filter((type) => {\n const found = lookupKind(world, type);\n return found.ok && Object.hasOwn(found.kind.verbs, \"step\");\n });\n // A name under each namespace with a fallback that no evaluator knows, for example [\"ops\", \"nope\"].\n const unknownNames: readonly (readonly Key[])[] = Object.keys(world.kinds)\n .filter((key) => {\n const entry = world.kinds[key];\n return isNamespace(entry) && entry.fallback !== undefined;\n })\n .map((key) => [key, \"nope\"]);\n let size = 0;\n\n const kindOf = (type: readonly Key[]): Kind | undefined => {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : undefined;\n };\n\n const anyJson = (depth = 0): Json => {\n const roll = rng.int(depth > 1 ? 6 : 8);\n if (roll === 0) return null;\n if (roll === 1) return rng.chance(0.5);\n if (roll === 2) return rng.pick([0, 1, 2, -1, 0.5, 1e21]);\n if (roll === 3) return rng.pick([\"\", \"a\", \"text\", \"0\"]);\n if (roll === 4) return rng.int(10);\n if (roll === 5) return rng.pick(NAMES);\n if (roll === 6) return Array.from({ length: rng.int(3) }, () => anyJson(depth + 1));\n const out: Record<string, Json> = {};\n for (let index = rng.int(3); index > 0; index -= 1) Object.defineProperty(out, rng.pick(FIELDS), { value: anyJson(depth + 1), enumerable: true, writable: true, configurable: true });\n return out;\n };\n\n const dataOf = (type: readonly Key[]): Json => options.data?.(type, rng) ?? anyJson();\n\n const renderType = (type: readonly Key[]): Json => {\n const roll = rng.next();\n if (roll < 0.06) return { type: \"ref\", value: [\"world\", ...type] };\n if (type.length === 1 && roll < 0.8) return type[0] as Json;\n return [...type];\n };\n\n const permitted = (type: readonly Key[], kinds: readonly (readonly Key[])[] | undefined): boolean =>\n kinds === undefined || kinds.some((kind) => kind.length <= type.length && kind.every((key, index) => String(key) === String(type[index])));\n\n const pickName = (names: readonly string[]): string => (names.length === 0 || rng.chance(malformed) ? rng.pick([\"unbound\", \"zz\"]) : rng.pick(names));\n\n const someNames = (): string[] => {\n const out = new Set<string>();\n for (let index = 1 + rng.int(2); index > 0; index -= 1) out.add(rng.pick(NAMES));\n return [...out];\n };\n\n const envelope = (type: readonly Key[], value: Json, header?: string): Json => {\n const out: Record<string, Json> = { type: renderType(type), value };\n if (header !== undefined) out[\"name\"] = header;\n if (options.own !== undefined && options.own.length > 0 && rng.chance(0.03)) out[\"own\"] = { eval: rng.pick(options.own) };\n return out;\n };\n\n /** A path from a root (D10). It uses the names in scope, and sometimes a step document. */\n const pathFor = (pos: Position, refKind: Kind | undefined): Json => {\n if (rng.chance(malformed)) return rng.pick<Json>([\"names\", [], { names: \"a\" }, [\"nowhere\", \"a\"]]);\n const others = roots.filter((name) => name !== \"names\");\n const named = roots.includes(\"names\") && pos.names.length > 0 && (others.length === 0 || rng.chance(0.75));\n const root = named || others.length === 0 ? \"names\" : rng.pick(others);\n const path: Json[] = [root];\n if (root === \"names\") path.push(pickName(pos.names));\n if (root === \"world\") path.push(String(rng.pick(types)[0]));\n for (let index = rng.int(steps + 1); index > 0; index -= 1) {\n if (stepTypes.length > 0 && rng.chance(0.2)) {\n const type = rng.pick(stepTypes);\n const kind = kindOf(type);\n // With a deep shape of the kind ref, the value of a step document can hold parts.\n const value = refKind?.parts?.shape === \"deep\" && kind?.parts !== undefined ? valueOf(kind.parts, [], { ...pos, depth: pos.depth + 1 }, emptyScope()) : dataOf(type);\n path.push({ type: renderType(type), value });\n } else {\n path.push(rng.pick(keys) as Json);\n }\n }\n return path;\n };\n\n const emptyScope = (): Scope => ({ rules: [], names: [], covered: [], sources: new Map() });\n\n /** This function decides the names of the scope rules before the parts, so that each part knows what it sees. */\n const scopeOf = (kind: Kind): Scope => {\n const rules = kind.scope ?? [];\n const scope: Scope = { rules, names: [], covered: rules.map(() => 0), sources: new Map() };\n for (const rule of rules) {\n const source = rule.names;\n let names: string[] = [];\n if (\"fixed\" in source) names = [...source.fixed];\n else if (\"keysAt\" in source) {\n names = someNames();\n scope.sources.set(source.keysAt.join(\".\"), { keys: names });\n } else if (\"listAt\" in source) {\n names = someNames();\n scope.sources.set(source.listAt.join(\".\"), { list: rng.chance(malformed) ? [...names, ...names] : names });\n } else if (\"textAt\" in source) {\n names = [rng.pick(NAMES)];\n scope.sources.set(source.textAt.join(\".\"), { text: names[0] as string });\n }\n scope.names.push(names);\n }\n return scope;\n };\n\n /** The names that a part sees from the scope rules of its parent. A rule `sequential` shows only earlier names. */\n const seenBy = (scope: Scope, path: readonly Key[]): { readonly names: readonly string[]; readonly headers: boolean } => {\n const names: string[] = [];\n let headers = false;\n scope.rules.forEach((rule, index) => {\n if (!rule.in.some((pattern) => pathMatches(path, pattern))) return;\n const ruleNames = scope.names[index] ?? [];\n if (\"headers\" in rule.names) headers = true;\n if (rule.sequential !== true || \"headers\" in rule.names || (scope.covered[index] ?? 0) > 0) names.push(...ruleNames);\n });\n return { names, headers };\n };\n\n /** This function records the part at a path, and the header name that it got, for the rules that cover it. */\n const saw = (scope: Scope, path: readonly Key[], part: Json): void => {\n const header = isEnvelope(part) && typeof (part as { readonly name?: unknown }).name === \"string\" ? (part as { readonly name: string }).name : undefined;\n scope.rules.forEach((rule, index) => {\n if (!rule.in.some((pattern) => pathMatches(path, pattern))) return;\n scope.covered[index] = (scope.covered[index] ?? 0) + 1;\n if (\"headers\" in rule.names && header !== undefined) scope.names[index]?.push(header);\n });\n };\n\n const partAt = (pos: Position, scope: Scope, path: readonly Key[], spec: Extract<Shape, { readonly shape: \"term\" }> | { readonly shape: \"term\"; readonly of?: string }, parentType: readonly Key[] | undefined): Json => {\n const seen = seenBy(scope, path);\n const header = seen.headers && rng.chance(0.5) ? rng.pick(NAMES) : undefined;\n const part = docAt(\n {\n declared: spec.of,\n kinds: \"kinds\" in spec ? spec.kinds : undefined,\n names: seen.names.length === 0 ? pos.names : [...pos.names, ...seen.names],\n depth: pos.depth + 1,\n hint: parentType === undefined ? undefined : options.hints?.(parentType, path),\n },\n header,\n );\n saw(scope, path, part);\n return part;\n };\n\n /** This function builds a value of a shape (SHAPE.*). A part is a document at the next depth. */\n const valueOf = (shape: Shape | undefined, path: readonly Key[], pos: Position, scope: Scope, type?: readonly Key[]): Json => {\n const source = scope.sources.get(path.join(\".\"));\n if (source !== undefined && \"list\" in source) return [...source.list];\n if (source !== undefined && \"text\" in source) return source.text;\n const term = (of: string | undefined): { readonly shape: \"term\"; readonly of?: string } => (of === undefined ? { shape: \"term\" } : { shape: \"term\", of });\n const small = (): number => (pos.depth >= maxDepth ? 0 : size >= maxSize ? rng.int(2) : rng.int(4));\n if (shape === undefined || shape.shape === \"none\") return path.length === 0 && type !== undefined ? dataOf(type) : anyJson();\n switch (shape.shape) {\n case \"term\":\n return partAt(pos, scope, path, shape, type);\n case \"list\": {\n const items = Array.from({ length: small() }, (_, index) => valueOf(shape.item ?? term(shape.of), [...path, index], pos, scope, type));\n if (shape.distinct !== true || rng.chance(malformed)) return items;\n return items.filter((item, index) => !items.slice(0, index).some((before) => docEquals(before, item)));\n }\n case \"map\": {\n const out: Record<string, Json> = {};\n const names = source !== undefined && \"keys\" in source ? source.keys : Array.from({ length: small() }, () => rng.pick(FIELDS));\n for (const key of names) Object.defineProperty(out, key, { value: valueOf(shape.item ?? term(shape.of), [...path, key], pos, scope, type), enumerable: true, writable: true, configurable: true });\n return out;\n }\n case \"record\": {\n const named: Readonly<Record<string, Shape>> = Array.isArray(shape.fields)\n ? Object.fromEntries((shape.fields as readonly string[]).map((name) => [name, term(shape.of)]))\n : (shape.fields as Readonly<Record<string, Shape>>);\n const fieldKeys = new Set<string>([...(shape.required ?? []), ...Object.keys(named).filter(() => rng.chance(0.75))]);\n if (shape.closed !== true && shape.rest === undefined && rng.chance(0.15)) fieldKeys.add(\"extra\");\n const ordered = rng.chance(0.2) ? [...fieldKeys].reverse() : [...fieldKeys];\n const out: Record<string, Json> = {};\n for (const key of ordered) {\n if (rng.chance(malformed / 2) && (shape.required ?? []).includes(key)) continue;\n const fieldShape = Object.hasOwn(named, key) ? named[key] : shape.rest;\n Object.defineProperty(out, key, { value: valueOf(fieldShape, [...path, key], pos, scope, type), enumerable: true, writable: true, configurable: true });\n }\n if (shape.closed === true && rng.chance(malformed)) out[\"stray\"] = 1;\n return out;\n }\n case \"deep\":\n return rng.chance(0.5)\n ? [partAt(pos, scope, [...path, 0], term(shape.of), type), anyJson()]\n : { at: partAt(pos, scope, [...path, \"at\"], term(shape.of), type), data: anyJson() };\n case \"text\":\n return rng.chance(malformed) ? 1 : rng.pick([\"\", \"a\", \"label\"]);\n case \"number\": {\n if (rng.chance(malformed)) return \"1\";\n const low = shape.min ?? -2;\n const value = low + rng.int(5) + (shape.whole === true ? 0 : rng.pick([0, 0.5]));\n return shape.max !== undefined && value > shape.max ? shape.max : value;\n }\n case \"one\":\n return rng.chance(malformed) ? \"other\" : (rng.pick(shape.values) as Json);\n }\n };\n\n /**\n * A malformed document: an unknown kind, or an unknown name under a namespace with a fallback. It can also be a\n * bad shape, a bare value without a type, or a bad reference.\n */\n const brokenAt = (pos: Position): Json => {\n const roll = rng.int(5);\n if (roll === 0 && unknownNames.length > 0 && rng.chance(0.5)) {\n // The fallback kind answers the name, and its evaluator does not know it, for example an unknown operation.\n const type = rng.pick(unknownNames);\n const kind = kindOf(type);\n return envelope(type, kind?.parts === undefined ? dataOf(type) : valueOf(kind.parts, [], pos, scopeOf(kind), type));\n }\n if (roll === 0) return { type: rng.pick<Json>([\"nothing\", [\"no\", \"such\"]]), value: 1 };\n if (roll === 1) return pos.declared === undefined ? rng.pick<Json>([7, \"bare\", [1]]) : { type: \"ref\", value: [\"names\", \"unbound\"] };\n if (roll === 2) {\n const shaped = types.filter((type) => kindOf(type)?.parts !== undefined);\n if (shaped.length > 0) return envelope(rng.pick(shaped), rng.pick<Json>([7, \"x\", null]));\n }\n if (roll === 3) return { type: \"ref\", value: rng.pick<Json>([[\"names\", \"unbound\"], [\"nowhere\"], \"names\"]) };\n return { type: rng.pick(types) as Json, value: anyJson() };\n };\n\n const docAt = (pos: Position, header?: string): Json => {\n size += 1;\n const leaf = pos.depth >= maxDepth || size >= maxSize;\n if (rng.chance(malformed)) return brokenAt(pos);\n if (pos.declared !== undefined && rng.chance(leaf ? 0.7 : 0.3)) {\n const bare = dataOf([pos.declared]);\n // A bare value with the form of an envelope is a document of its own type, and the position must permit that type.\n if (!isEnvelope(bare) || permitted(typePath(bare.type) ?? [], pos.kinds)) return bare;\n }\n let candidates = types.filter((type) => permitted(type, pos.kinds) && (!leaf || leafKind(kindOf(type))));\n if (pos.hint !== undefined && rng.chance(0.6)) {\n const hinted = candidates.filter((type) => pos.hint?.some((hint) => hint.length === type.length && hint.every((key, index) => key === type[index])));\n if (hinted.length > 0) candidates = hinted;\n }\n if (candidates.length === 0) candidates = [...types];\n const type = rng.pick(candidates);\n const kind = kindOf(type);\n if (type.length === 1 && type[0] === \"ref\") return envelope(type, pathFor(pos, kind), header);\n const value = kind === undefined ? dataOf(type) : valueOf(kind.parts, [], pos, scopeOf(kind), type);\n return envelope(type, value, header);\n };\n\n return docAt({ declared: options.declaredType, kinds: undefined, names: options.names ?? [], depth: 0, hint: undefined });\n}\n"],"mappings":";;AAqCA,MAAa,gBAAgB;CAAC;CAAQ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["NONE","setOwn","own","entryOf","setOwn","makeRootContext","drive","record","CLOSURE","partsOf","CLOSURE"],"sources":["../src/doc.ts","../src/errors.ts","../src/world.ts","../src/merge.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","../src/reference.ts","../src/agree.ts","../src/generate.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 values are equal. Plain JSON compares by its structure. Equal values have the same\n * texts, numbers and truth values, the same items in the same order, and the same fields. The order of the fields\n * does not matter. Each leaf compares with `Object.is`, thus `-0` is not `0`, and `NaN` is `NaN`.\n *\n * Only lists and plain records (`isRecord`) compare by their items and fields. Each other object compares by\n * identity: a date, a map, a function and an instance of a class are equal only to themselves. Thus an early cutoff\n * with this function does not keep a stale host value.\n *\n * The function does not use the stack for the depth, thus a deep document cannot overflow it. A cycle of lists or\n * records does not make it loop. `sameValue` of `agree` uses the same rules, and it adds rules for closures and for\n * a rule of the caller.\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 // The pairs of containers that the comparison already visits. It is made at the first pair of containers.\n let seen: Map<object, Set<object>> | undefined;\n while (stack.length > 0) {\n const [x, y] = stack.pop() as [unknown, unknown];\n if (Object.is(x, y)) continue;\n const list = Array.isArray(x);\n if (list !== Array.isArray(y)) return false;\n // An object that is not a list and not a plain record is a host value: Object.is above compared it.\n if (!list && (!isRecord(x) || !isRecord(y))) return false;\n seen ??= new Map();\n const pairs = seen.get(x as object);\n if (pairs?.has(y as object) === true) continue;\n if (pairs === undefined) seen.set(x as object, new Set([y as object]));\n else pairs.add(y as object);\n if (list) {\n const xs = x as readonly unknown[];\n const ys = y as readonly unknown[];\n if (xs.length !== ys.length) return false;\n for (let index = 0; index < xs.length; index += 1) stack.push([xs[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 try {\n // A regular expression that compiles near the limit of the stack throws a SyntaxError with the same message.\n // Thus the test reads the message with includes, and it accepts a SyntaxError.\n return (error instanceof RangeError || error instanceof SyntaxError) && error.message.includes(\"call stack\");\n } catch {\n // Near the limit of the stack, the test itself can overflow.\n return true;\n }\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 Key, docEquals, isRecord } from \"./doc.ts\";\nimport type { DerefCode, Walker } from \"./deref.ts\";\nimport type { Evaluator, Machine, Runner } from \"./evaluate.ts\";\nimport { type Kind, type World, type WorldEntry, isAlias, isKind, isNamespace } from \"./world.ts\";\n\n/** The keys from a part of a merge to one of its entries, for example `[\"kinds\", \"ref\"]`. */\nexport type MergePath = readonly Key[];\n\n/**\n * A world as a part of a merge. Each field is optional. `replaces` names the paths of the entries that this part\n * replaces, for example `[\"kinds\", \"ref\"]` or `[\"defaults\", \"view\"]`. The result of a merge has no `replaces`.\n */\nexport interface WorldPart {\n readonly kinds?: Readonly<Record<string, WorldEntry>>;\n readonly defaults?: Readonly<Record<string, string>>;\n readonly fallback?: Kind;\n readonly replaces?: readonly MergePath[];\n}\n\n/**\n * A machine as a part of a merge. Each field is optional. `replaces` names paths in the machine, for example\n * `[\"evaluators\", \"formula.op\"]` or `[\"world\", \"kinds\", \"ref\"]`. The paths in `world.replaces` start at the world.\n */\nexport interface MachinePart extends Omit<Partial<Machine>, \"world\"> {\n readonly world?: WorldPart;\n readonly replaces?: readonly MergePath[];\n}\n\n/**\n * One conflict of a merge. `path` is the path of the entry, as `replaces` names it. Thus the same path in the\n * `replaces` of the later part resolves the conflict. `parts` gives the indices of the two parts, the earlier first.\n */\nexport interface MergeConflict {\n readonly path: MergePath;\n readonly parts: readonly [number, number];\n readonly reason: string;\n}\n\n/** The exception of a merge with conflicts. It lists each conflict of the merge, not only the first. */\nexport class MergeError extends Error {\n readonly conflicts: readonly MergeConflict[];\n\n /**\n * This constructor makes the exception.\n *\n * @param conflicts - The conflicts, in the order that the merge found them.\n */\n constructor(conflicts: readonly MergeConflict[]) {\n const lines = conflicts.map((item) => `At ${JSON.stringify(item.path)}, the parts ${item.parts[0]} and ${item.parts[1]}: ${item.reason}`);\n super(`The merge has ${conflicts.length === 1 ? \"1 conflict\" : `${conflicts.length} conflicts`}. ${lines.join(\" \")}`);\n this.name = \"MergeError\";\n this.conflicts = conflicts;\n }\n}\n\ntype Known = NonNullable<Machine[\"known\"]>;\n\nconst NONE: ReadonlySet<string> = new Set();\n\nfunction keyOf(path: MergePath): string {\n return JSON.stringify(path.map(String));\n}\n\n/** This function sets an own data property. An assignment to the key `__proto__` changes the prototype. */\nfunction setOwn<T>(target: Record<string, T>, key: string, value: T): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\nfunction own<T>(table: Readonly<Record<string, T>> | undefined, key: string): T | undefined {\n return table !== undefined && Object.hasOwn(table, key) ? table[key] : undefined;\n}\n\n/** This function gives a copy of a JSON value without the fields whose value is `undefined`, as JSON writes it. */\nfunction defined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(defined);\n if (!isRecord(value)) return value;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) if (value[key] !== undefined) setOwn(out, key, defined(value[key]));\n return out;\n}\n\n/** Two values are the same when they are equal by `docEquals`. A function and a host value are equal only to themselves. */\nfunction same(a: unknown, b: unknown): boolean {\n return Object.is(a, b) || docEquals(defined(a), defined(b));\n}\n\n/** Two lists of roots are the same when they hold the same roots, in any order. */\nfunction sameRoots(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) return same(a, b);\n return same([...new Set(a.map(String))].sort(), [...new Set(b.map(String))].sort());\n}\n\n/** The record of a merge: the conflicts, and the part that gave each entry. */\nclass Merger {\n readonly conflicts: MergeConflict[] = [];\n private readonly sources = new Map<string, number>();\n\n /** This method gives the part that gave the entry at a path, or the entry nearest above it. */\n sourceOf(path: MergePath): number {\n for (let length = path.length; length >= 0; length -= 1) {\n const found = this.sources.get(keyOf(path.slice(0, length)));\n if (found !== undefined) return found;\n }\n return 0;\n }\n\n /** This method records the part that gives a new entry. */\n give(path: MergePath, part: number): void {\n this.sources.set(keyOf(path), part);\n }\n\n /** This method records the part that replaces an entry, and forgets the parts of each entry below it. */\n replace(path: MergePath, part: number): void {\n const below = `${keyOf(path).slice(0, -1)},`;\n for (const key of [...this.sources.keys()]) if (key.startsWith(below)) this.sources.delete(key);\n this.give(path, part);\n }\n\n clash(path: MergePath, part: number, reason: string): void {\n this.conflicts.push({ path, parts: [this.sourceOf(path), part], reason });\n }\n}\n\n/**\n * This function merges one entry of a table into the table. A new entry joins the table. A path in `replaces` gives\n * the later entry. Two entries that are the same give one entry. Each other pair is a conflict.\n */\nfunction mergeLeaf<T>(\n m: Merger,\n table: Record<string, T>,\n key: string,\n later: T | undefined,\n path: MergePath,\n part: number,\n replaces: ReadonlySet<string>,\n equal: (a: T, b: T) => boolean,\n reason: string,\n): void {\n if (later === undefined) return;\n const earlier = own(table, key);\n if (earlier === undefined) {\n setOwn(table, key, later);\n m.give(path, part);\n } else if (replaces.has(keyOf(path))) {\n setOwn(table, key, later);\n m.replace(path, part);\n } else if (!equal(earlier, later)) {\n m.clash(path, part, reason);\n }\n}\n\nfunction what(entry: WorldEntry): string {\n if (isKind(entry)) return \"a kind\";\n if (isAlias(entry)) return \"an alias\";\n return isNamespace(entry) ? \"a namespace\" : \"an entry\";\n}\n\nfunction mergeFallback(m: Merger, earlier: Kind | undefined, later: Kind | undefined, path: MergePath, part: number, replaces: ReadonlySet<string>): Kind | undefined {\n const table: Record<string, Kind> = earlier === undefined ? {} : { fallback: earlier };\n mergeLeaf(m, table, \"fallback\", later, path, part, replaces, same, \"Two parts give two different fallback kinds.\");\n return table[\"fallback\"];\n}\n\nfunction mergeEntries(m: Merger, into: Record<string, WorldEntry>, from: Readonly<Record<string, WorldEntry>>, path: MergePath, part: number, replaces: ReadonlySet<string>): void {\n for (const key of Object.keys(from)) {\n const later = from[key];\n if (later === undefined) continue;\n const at = [...path, key];\n const earlier = own(into, key);\n if (earlier === undefined) {\n setOwn(into, key, later);\n m.give(at, part);\n } else {\n setOwn(into, key, mergeEntry(m, earlier, later, at, part, replaces));\n }\n }\n}\n\n/** This function merges two entries at one path. Two namespaces merge key by key, and their fallbacks merge too. */\nfunction mergeEntry(m: Merger, earlier: WorldEntry, later: WorldEntry, path: MergePath, part: number, replaces: ReadonlySet<string>): WorldEntry {\n if (replaces.has(keyOf(path))) {\n m.replace(path, part);\n return later;\n }\n if (same(earlier, later)) return earlier;\n if (isNamespace(earlier) && isNamespace(later)) {\n const kinds: Record<string, WorldEntry> = { ...earlier.kinds };\n mergeEntries(m, kinds, later.kinds, [...path, \"kinds\"], part, replaces);\n const fallback = mergeFallback(m, earlier.fallback, later.fallback, [...path, \"fallback\"], part, replaces);\n return fallback === undefined ? { kinds } : { kinds, fallback };\n }\n const a = what(earlier);\n const b = what(later);\n m.clash(path, part, a === b ? `Two parts give two different ${a === \"an alias\" ? \"aliases\" : \"kinds\"}.` : `One part gives ${a}, and the other part gives ${b}.`);\n return earlier;\n}\n\ninterface WorldDraft {\n readonly kinds: Record<string, WorldEntry>;\n readonly defaults: Record<string, string>;\n fallback?: Kind;\n}\n\nfunction worldOf(draft: WorldDraft): World {\n const world = { kinds: { ...draft.kinds }, defaults: { ...draft.defaults } };\n return draft.fallback === undefined ? world : { ...world, fallback: draft.fallback };\n}\n\nfunction mergeWorldInto(m: Merger, draft: WorldDraft, part: WorldPart | undefined, index: number, replaces: ReadonlySet<string>, base: MergePath): void {\n if (part === undefined) return;\n if (part.kinds !== undefined) mergeEntries(m, draft.kinds, part.kinds, [...base, \"kinds\"], index, replaces);\n const defaults = part.defaults ?? {};\n for (const verb of Object.keys(defaults)) {\n mergeLeaf(m, draft.defaults, verb, defaults[verb], [...base, \"defaults\", verb], index, replaces, Object.is, \"Two parts give two different defaults for this verb.\");\n }\n const fallback = mergeFallback(m, draft.fallback, part.fallback, [...base, \"fallback\"], index, replaces);\n if (fallback !== undefined) draft.fallback = fallback;\n}\n\n/**\n * This function merges worlds into one world, in the order of the parts. It does not change a part.\n *\n * - Two entries that are equal by `docEquals` give one entry.\n * - Two namespaces merge key by key, at each depth. Their fallbacks merge as each other entry.\n * - The defaults merge verb by verb, and the world keeps one fallback.\n * - Each other pair of entries at one path is a conflict, unless the later part names the path in `replaces`.\n * Then the later entry wins, with no merge below it.\n *\n * A part can be a function of the merge of the parts before it (`prev`, as an overlay of Nix). Thus a part can read\n * the entry that it replaces.\n *\n * @param parts - The worlds, or functions that give a world from the merge before them.\n * @returns The world. It has no `replaces`.\n * @throws {MergeError} The merge has a conflict. The error lists each conflict.\n */\nexport function mergeWorlds(...parts: readonly (WorldPart | ((prev: World) => WorldPart))[]): World {\n const m = new Merger();\n const draft: WorldDraft = { kinds: {}, defaults: {} };\n parts.forEach((input, index) => {\n const part = typeof input === \"function\" ? input(worldOf(draft)) : input;\n mergeWorldInto(m, draft, part, index, new Set((part.replaces ?? []).map(keyOf)), []);\n });\n if (m.conflicts.length > 0) throw new MergeError(m.conflicts);\n return worldOf(draft);\n}\n\n/** The fields of a machine that merge by their own rules. Each other field is one value, or a conflict. */\nconst TABLES = new Set([\"world\", \"evaluators\", \"runners\", \"derefs\", \"walkers\", \"known\", \"replaces\"]);\n\ninterface MachineDraft {\n readonly world: WorldDraft;\n readonly evaluators: Record<string, Evaluator>;\n runners?: Record<string, Runner>;\n derefs?: Record<string, DerefCode>;\n walkers?: Record<string, Walker>;\n readonly hooks: { readonly part: number; readonly known: Known }[];\n /** The last part that replaced the code of each evaluator name. */\n readonly replaced: Map<string, number>;\n readonly rest: Record<string, unknown>;\n readonly parts: MachinePart[];\n}\n\n/**\n * This function composes the hooks `known` in the order of their parts. The first answer that is not `true` wins. A\n * hook does not answer for an evaluator name whose code a later part replaces.\n */\nfunction composeKnown(hooks: readonly { readonly part: number; readonly known: Known }[], replaced: ReadonlyMap<string, number>): Known | undefined {\n const first = hooks[0];\n if (first === undefined) return undefined;\n if (hooks.length === 1 && replaced.size === 0) return first.known;\n const list = [...hooks];\n const last = new Map(replaced);\n return (path, evaluator) => {\n const after = last.get(evaluator);\n for (const hook of list) {\n if (after !== undefined && hook.part < after) continue;\n const answer = hook.known(path, evaluator);\n if (answer !== true) return answer;\n }\n return true;\n };\n}\n\nfunction machineOf(draft: MachineDraft): Machine {\n const known = composeKnown(draft.hooks, draft.replaced);\n return {\n ...draft.rest,\n world: worldOf(draft.world),\n evaluators: { ...draft.evaluators },\n ...(draft.runners === undefined ? {} : { runners: { ...draft.runners } }),\n ...(draft.derefs === undefined ? {} : { derefs: { ...draft.derefs } }),\n ...(draft.walkers === undefined ? {} : { walkers: { ...draft.walkers } }),\n ...(known === undefined ? {} : { known }),\n };\n}\n\n/** This function merges the evaluators and the runners of a part. The evaluator and the runner of a name are its code. */\nfunction mergeCode(m: Merger, draft: MachineDraft, part: MachinePart, index: number, replaces: ReadonlySet<string>): void {\n if (part.runners !== undefined) draft.runners ??= {};\n const names = new Set([...Object.keys(part.evaluators ?? {}), ...Object.keys(part.runners ?? {})]);\n for (const name of names) {\n const evaluator = own(part.evaluators, name);\n const runner = own(part.runners, name);\n if (evaluator === undefined && runner === undefined) continue;\n const evaluatorPath = [\"evaluators\", name];\n const runnerPath = [\"runners\", name];\n if (replaces.has(keyOf(evaluatorPath)) || replaces.has(keyOf(runnerPath))) {\n // The part replaces the code of the name: the evaluator and the runner of the earlier parts go.\n if (evaluator === undefined) delete draft.evaluators[name];\n else setOwn(draft.evaluators, name, evaluator);\n if (runner !== undefined) setOwn((draft.runners ??= {}), name, runner);\n else if (draft.runners !== undefined) delete draft.runners[name];\n m.replace(evaluatorPath, index);\n m.replace(runnerPath, index);\n draft.replaced.set(name, index);\n continue;\n }\n mergeLeaf(m, draft.evaluators, name, evaluator, evaluatorPath, index, NONE, Object.is, \"Two parts give two different evaluators for this name.\");\n if (runner !== undefined) mergeLeaf(m, (draft.runners ??= {}), name, runner, runnerPath, index, NONE, Object.is, \"Two parts give two different runners for this name.\");\n }\n}\n\n/** A runner hides the evaluator of its name. Thus a name with a runner and an evaluator needs one part that gives both. */\nfunction checkHidden(m: Merger, draft: MachineDraft): void {\n const runners = draft.runners ?? {};\n for (const name of Object.keys(runners)) {\n const runner = runners[name];\n const evaluator = own(draft.evaluators, name);\n if (runner === undefined || evaluator === undefined) continue;\n if (draft.parts.some((part) => own(part.evaluators, name) === evaluator && own(part.runners, name) === runner)) continue;\n const a = m.sourceOf([\"evaluators\", name]);\n const b = m.sourceOf([\"runners\", name]);\n m.conflicts.push({\n path: [\"runners\", name],\n parts: [Math.min(a, b), Math.max(a, b)],\n reason: \"The runner of one part hides the evaluator of the other part, because a runner wins over an evaluator of its name.\",\n });\n }\n}\n\n/**\n * This function merges machines into one machine, in the order of the parts. It does not change a part.\n *\n * - The worlds merge with the rules of `mergeWorlds`. The paths of their conflicts start with `\"world\"`.\n * - The tables `evaluators`, `runners`, `derefs` and `walkers` merge name by name. A function is equal only to itself.\n * - The evaluator and the runner of a name are its code. A replacement of the name replaces both.\n * - A runner hides the evaluator of its name. Thus one part must give both, or the merge gives a conflict.\n * - The hooks `known` compose in the order of the parts. A hook does not answer for a name that a later part replaces.\n * - Each other field, for example `permits`, `adopt`, `roots`, `plain` or `maxDepth`, is one value. Two different\n * values are a conflict. An absent field has no value.\n *\n * A conflict stops the merge, unless the later part names its path in `replaces`. A part can be a function of the\n * merge of the parts before it (`prev`, as an overlay of Nix). Thus a part can wrap the code that it replaces.\n *\n * @param parts - The machines, or functions that give a machine from the merge before them.\n * @returns The machine.\n * @throws {MergeError} The merge has a conflict. The error lists each conflict.\n */\nexport function mergeMachines(...parts: readonly (MachinePart | ((prev: Machine) => MachinePart))[]): Machine {\n const m = new Merger();\n const draft: MachineDraft = { world: { kinds: {}, defaults: {} }, evaluators: {}, hooks: [], replaced: new Map(), rest: {}, parts: [] };\n parts.forEach((input, index) => {\n const part = typeof input === \"function\" ? input(machineOf(draft)) : input;\n draft.parts.push(part);\n const replaces = new Set([...(part.replaces ?? []), ...(part.world?.replaces ?? []).map((path) => [\"world\", ...path])].map(keyOf));\n mergeWorldInto(m, draft.world, part.world, index, replaces, [\"world\"]);\n mergeCode(m, draft, part, index, replaces);\n if (part.derefs !== undefined) {\n const derefs = (draft.derefs ??= {});\n for (const name of Object.keys(part.derefs)) mergeLeaf(m, derefs, name, part.derefs[name], [\"derefs\", name], index, replaces, Object.is, \"Two parts give two different deref codes for this name.\");\n }\n if (part.walkers !== undefined) {\n const walkers = (draft.walkers ??= {});\n for (const name of Object.keys(part.walkers)) mergeLeaf(m, walkers, name, part.walkers[name], [\"walkers\", name], index, replaces, Object.is, \"Two parts give two different walkers for this name.\");\n }\n if (part.known !== undefined && !draft.hooks.some((hook) => hook.known === part.known)) draft.hooks.push({ part: index, known: part.known });\n const fields = part as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(fields)) {\n if (TABLES.has(key)) continue;\n mergeLeaf(m, draft.rest, key, fields[key], [key], index, replaces, key === \"roots\" ? sameRoots : same, `Two parts give two different values for ${key}.`);\n }\n });\n checkHidden(m, draft);\n if (m.conflicts.length > 0) throw new MergeError(m.conflicts);\n return machineOf(draft);\n}\n\n/** This function removes the entry at a path from a table of entries. It gives the same table when no entry is there. */\nfunction removeEntry(entries: Readonly<Record<string, WorldEntry>>, path: readonly Key[]): Readonly<Record<string, WorldEntry>> {\n const [first, ...rest] = path;\n if (first === undefined) return entries;\n const key = String(first);\n const entry = own(entries, key);\n if (entry === undefined) return entries;\n let next: WorldEntry | undefined;\n if (rest.length > 0) {\n if (!isNamespace(entry)) return entries;\n if (rest.length === 1 && String(rest[0]) === \"fallback\") {\n if (entry.fallback === undefined) return entries;\n next = { kinds: entry.kinds };\n } else {\n if (String(rest[0]) !== \"kinds\") return entries;\n const kinds = removeEntry(entry.kinds, rest.slice(1));\n if (kinds === entry.kinds) return entries;\n next = entry.fallback === undefined ? { kinds } : { kinds, fallback: entry.fallback };\n }\n }\n const out: Record<string, WorldEntry> = { ...entries };\n if (next === undefined) delete out[key];\n else setOwn(out, key, next);\n return out;\n}\n\n/**\n * This function removes entries from a world, for a language that restricts another language. A path names an entry\n * as `replaces` names it, for example `[\"kinds\", \"fn\"]`, `[\"kinds\", \"ops\", \"kinds\", \"mul\"]`,\n * `[\"kinds\", \"ops\", \"fallback\"]`, `[\"defaults\", \"view\"]` or `[\"fallback\"]`. A path that names no entry changes\n * nothing. The function does not change the world.\n *\n * A removed kind gives `#KIND?`, also through an alias to it. A namespace without its fallback knows only its own keys.\n * A world without its fallback is closed.\n *\n * @param world - The world.\n * @param paths - The paths of the entries to remove.\n * @returns The world without the entries.\n */\nexport function restrictWorld(world: World, paths: readonly MergePath[]): World {\n let kinds = world.kinds;\n const defaults: Record<string, string> = { ...world.defaults };\n let fallback = world.fallback;\n for (const path of paths) {\n const [first, ...rest] = path.map(String);\n if (first === \"kinds\") kinds = removeEntry(kinds, rest);\n else if (first === \"defaults\" && rest.length === 1) delete defaults[rest[0] as string];\n else if (first === \"fallback\" && rest.length === 0) fallback = undefined;\n }\n const out = { kinds: { ...kinds }, defaults };\n return fallback === undefined ? out : { ...out, fallback };\n}\n\n/** The tables of the code of a machine, as the paths of a restriction name them. */\nconst CODE_TABLES = [\"evaluators\", \"runners\", \"derefs\", \"walkers\"] as const;\n\n/**\n * This function removes entries from a machine, for a language that restricts another language. A path names an\n * entry as `replaces` names it:\n *\n * - A path that starts with `\"world\"` removes an entry of the world, with the rules of `restrictWorld`.\n * - `[\"evaluators\", name]` or `[\"runners\", name]` removes the code of the name: its evaluator and its runner.\n * - `[\"derefs\", name]` and `[\"walkers\", name]` remove one entry of their tables.\n *\n * A path that names no entry changes nothing. The function does not change the machine. An own entry names an\n * evaluator directly, thus only a machine without the code of a name refuses each document that names it.\n *\n * @param machine - The machine.\n * @param paths - The paths of the entries to remove.\n * @returns The machine without the entries.\n */\nexport function restrictMachine(machine: Machine, paths: readonly MergePath[]): Machine {\n const world = paths.filter((path) => String(path[0]) === \"world\").map((path) => path.slice(1));\n const tables: Record<(typeof CODE_TABLES)[number], Record<string, unknown> | undefined> = {\n evaluators: { ...machine.evaluators },\n runners: machine.runners === undefined ? undefined : { ...machine.runners },\n derefs: machine.derefs === undefined ? undefined : { ...machine.derefs },\n walkers: machine.walkers === undefined ? undefined : { ...machine.walkers },\n };\n for (const path of paths) {\n const [table, name, ...rest] = path.map(String);\n if (name === undefined || rest.length > 0 || !(CODE_TABLES as readonly (string | undefined)[]).includes(table)) continue;\n // The evaluator and the runner of a name are its code, as for a replacement (MACHINE.RUNNER).\n const from = table === \"evaluators\" || table === \"runners\" ? [\"evaluators\", \"runners\"] : [table as string];\n for (const key of from) {\n const entries = tables[key as (typeof CODE_TABLES)[number]];\n if (entries !== undefined) delete entries[name];\n }\n }\n return {\n ...machine,\n world: world.length === 0 ? machine.world : restrictWorld(machine.world, world),\n evaluators: tables.evaluators as Machine[\"evaluators\"],\n ...(tables.runners === undefined ? {} : { runners: tables.runners as NonNullable<Machine[\"runners\"]> }),\n ...(tables.derefs === undefined ? {} : { derefs: tables.derefs as NonNullable<Machine[\"derefs\"]> }),\n ...(tables.walkers === undefined ? {} : { walkers: tables.walkers as NonNullable<Machine[\"walkers\"]> }),\n };\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 Envelope, type Json, type Key, docEquals, isEnvelope, isRecord, typeName, typePath } from \"./doc.ts\";\nimport { type Kind, type Shape, type World, lookupKind } 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 tells if a shape holds only data: no value of the shape can hold a part. */\nfunction isData(shape: Shape): boolean {\n return shape.shape === \"none\" || shape.shape === \"text\" || shape.shape === \"number\" || shape.shape === \"one\";\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 const items = list.map((child, index) => walk(each, child, [...path, index]));\n // A list of data is data, also when it is empty. Only a list that can hold parts gives null in the data.\n return isData(each) ? { t: \"data\", value: item } : { t: \"list\", items };\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 * The kind and the parts of one document: what `partsOf` gives. `ok` is `false` only when the value is not a\n * document: it has no envelope, and its position declares no type. A value without the shape of its kind gives a\n * failed `split`.\n */\nexport type DocParts =\n | {\n readonly ok: true;\n /** The document. A bare value gets 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, or `undefined` when the world has no kind for the type. Then the value is data. */\n readonly kind: Kind | undefined;\n /** The keys of the kind after each alias, or `undefined` without a kind. */\n readonly typePath: readonly Key[] | undefined;\n /**\n * The split of the value by the shape of the kind. The reason of a failed split is the reason of the `#VALUE!`\n * of an evaluation: it names the kind. Its `at` gives the keys from the value to the problem.\n */\n readonly split: Split;\n }\n | { readonly ok: false; readonly code: \"#PART?\"; readonly reason: string };\n\n/**\n * This function reads one document by the contracts of the world. It finds the kind of the type. A bare value gets\n * the type that its position declares. Then the function splits the value by the shape of the kind. The plan, the\n * reference interpreter and the static kit read each document with this function. Thus they see the same parts.\n *\n * @param world - The world of the kinds.\n * @param value - The document, or a bare value.\n * @param declaredType - The type that the position of a bare value declares.\n * @returns The document, its kind and its parts, or the reason why the value is not a document.\n */\nexport function partsOf(world: World, value: unknown, declaredType?: string): DocParts {\n const envelope = isEnvelope(value) ? (value as Envelope) : undefined;\n if (envelope === undefined && declaredType === undefined) return { ok: false, code: \"#PART?\", reason: \"The value has no envelope, and its position declares no type.\" };\n const doc: Envelope = envelope ?? { type: declaredType as string, value: value as Json };\n const found = lookupKind(world, doc.type);\n const kind = found.ok ? found.kind : undefined;\n const split = splitParts(kind?.parts, doc.value);\n const typePath = found.ok ? found.path : undefined;\n if (split.ok) return { ok: true, doc, declared: envelope === undefined, kind, typePath, split };\n // The reason names the place in the value and the kind, as each reader of the document gives it.\n const where = split.at.length === 0 ? \"\" : ` (at ${split.at.join(\".\")})`;\n const reason = `${split.reason}${where} The kind is ${typeName(doc.type)}.`;\n return { ok: true, doc, declared: envelope === undefined, kind, typePath, split: { ok: false, reason, at: split.at } };\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, partsOf, pathMatches } from \"./parts.ts\";\nimport { ask, type Answer } from \"./ladder.ts\";\nimport type { CapsRule, Kind, Side, World } 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 * - `known`: the names that the evaluators know, for `check`. Without it, `check` does not check such names.\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 * This function tells if an evaluator knows the name in the path of a kind. An example is the operation\n * `[\"ops\", \"add\"]` of a formula language: a fallback kind names it, and the evaluator finds it in a table.\n * `check` asks it for each document with an evaluator. The function must be pure.\n *\n * @param path - The keys of the kind of the document, after each alias.\n * @param evaluator - The name of the evaluator that the ladder gives the document.\n * @returns `true` when the evaluator knows the name, or else the reason of the `#NAME?` that a run gives.\n */\n readonly known?: (path: readonly Key[], evaluator: string) => true | string;\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 return failingWith(c, meta, fail(code, reason, { place }));\n}\n\n/** This function gives the code of a document that fails with one result at each evaluation. */\nfunction failingWith(c: Compiler, meta: Meta, result: Result): { readonly code: Code; readonly run: RunCode } {\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, kind: Kind | undefined): { 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 (kind === undefined) return { unknown: true };\n const verbs = 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 world = c.machine.world;\n const read = partsOf(world, value, declared);\n if (!read.ok) {\n const meta: Meta = c.traced ? { path: place.map(String), doc: { type: \"?\", value: value as Json }, declared: true, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n return failing(c, meta, place, read.code, read.reason);\n }\n const { doc, kind, split } = read;\n const envelope = read.declared ? undefined : doc;\n const meta0: Meta = c.traced ? { path: place.map(String), doc, declared: read.declared, answer: NO_ANSWER, side: \"derive\" } : NO_META;\n if (depth > c.maxDepth) return failing(c, meta0, place, \"#DEPTH!\", `The nesting is deeper than ${c.maxDepth} documents.`);\n\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, kind);\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 if (!split.ok) return failing(c, meta, place, \"#VALUE!\", split.reason);\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 = read.typePath ?? [];\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 // A compiler that throws fails its own document when that document evaluates, with its place (PLAN.FAIL-LATE).\n if (runner !== undefined) {\n let inner: RunCode;\n try {\n inner = isCompiledRunner(runner) ? runner.compileRun(input) : interpretRun(runner, input, split.fill);\n } catch (error) {\n return failingWith(c, meta, placed(thrown(error, `the runner ${name}`), place));\n }\n const run = placedRun(inner, place, name);\n return finish(c, meta, runnerCode(run, place, kindText), run);\n }\n\n let inner: Code;\n try {\n inner = isCompiledEvaluator(evaluator as Evaluator) ? (evaluator as CompiledEvaluator).compile(input) : interpret(evaluator as EvalFn, input, split.fill);\n } catch (error) {\n return failingWith(c, meta, placed(thrown(error, `the evaluator ${name}`), place));\n }\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/**\n * This function gives the code of a runner in an evaluation: its steps, which cannot wait. A step that waits gives\n * `#CALC!` at the place of the runner, where the error started (RUN.WAIT).\n */\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 : placed(drive(run(ctx, rt)), place);\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 = placed(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 EvalInput, type Evaluator, type Machine, type Part, type Result, type RunPart, type Runner, type Steps, fail, ok } from \"./evaluate.ts\";\nimport { Failure } from \"./errors.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 // An attribute evaluates on demand, thus in an order that is not the order of the document. It causes no effect.\n caps: [{ rule: \"mask\" }],\n summary: \"A node of a tree. Each part is an attribute that evaluates on demand, one time, with the node as self.\",\n },\n box: {\n verbs: { eval: \"tree.node\", view: \"view.op\" },\n parts: { shape: \"record\", fields: [\"width\", \"height\", \"children\"], of: \"number\" },\n caps: [{ rule: \"mask\" }],\n summary: \"A node of a tree, as panel. A formula in a box can read its parent and its siblings.\",\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),\n};\n\n/*\n * The decorated tree (TREE.*, R3 P1). Each node is a host thing, and each part of a node is an attribute. An attribute\n * evaluates on demand, with the node as self. One memo cell for each node and attribute keeps its result for one\n * evaluation. The structure comes first: a node inside an attribute of an open tree gives its thing and evaluates\n * nothing. The root gives the JSON of the tree. Thus a reference to a sibling reads the finished list of children.\n */\n\n/** The brand of a node of the decorated tree. Its value is the state that the kit reads. */\nconst TREE_NODE: unique symbol = Symbol.for(\"coeval.tree.node\") as never;\n\n/** One tree in one evaluation. It is open until its root gives the JSON of the tree. */\ninterface TreeBuild {\n open: boolean;\n}\n\n/** The state of a node behind its brand. */\ninterface NodeState {\n readonly build: TreeBuild;\n readonly type: string;\n readonly place: readonly Key[];\n /**\n * This function gives the JSON of the node: each attribute in the order of the parts, with the JSON of each node in\n * its value.\n *\n * @param path - The nodes and the containers whose JSON is in progress. A node on it gives `#CYCLE!`.\n * @returns The JSON, or the first error.\n */\n json(path: Set<object>): Result;\n}\n\n/** The memo cell of one attribute: in evaluation, or done with its result. */\ntype Cell = { readonly busy: true } | { readonly busy: false; readonly result: Result };\n\nconst BUSY: Cell = Object.freeze({ busy: true });\n\n/** One attribute in evaluation. The text names it in the reason of a cycle. */\ninterface Demand {\n readonly cells: Map<string, Cell>;\n readonly key: string;\n readonly text: string;\n}\n\n/** The attributes in evaluation, in the order of their demands. An evaluation does not wait, thus one list serves. */\nconst demands: Demand[] = [];\n\nfunction attributeText(key: string, type: string, place: readonly Key[]): string {\n return `${key} of ${type} at [${place.join(\", \")}]`;\n}\n\n/** This function gives the `#CYCLE!` of a demand that reached an attribute in evaluation, with the chain of demands. */\nfunction cycleAt(cells: Map<string, Cell>, key: string, text: string): Result {\n const first = demands.findIndex((demand) => demand.cells === cells && demand.key === key);\n const chain = first === -1 ? [text] : demands.slice(first).map((demand) => demand.text);\n chain.push(text);\n return fail(\"#CYCLE!\", `The attributes form a cycle: ${chain.join(\" -> \")}.`);\n}\n\nfunction stateOf(thing: unknown): NodeState | undefined {\n return typeof thing === \"object\" && thing !== null ? (thing as { readonly [TREE_NODE]?: NodeState })[TREE_NODE] : undefined;\n}\n\n/** This function sets an own field, also the field `__proto__` (SHAPE.PROTO). */\nfunction putField(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * This function gives a value with the JSON of each node of a tree in it. A list or a plain record is new only when\n * it holds a node. A container that holds itself stays as it is.\n */\nfunction plainOf(value: unknown, path: Set<object>): Result {\n const state = stateOf(value);\n if (state !== undefined) {\n if (path.has(value as object)) return fail(\"#CYCLE!\", `The JSON of the node ${state.type} at [${state.place.join(\", \")}] holds the node itself.`);\n return state.json(path);\n }\n if (typeof value !== \"object\" || value === null || path.has(value) || isHostThing(value)) return ok(value);\n if (!Array.isArray(value) && !isRecord(value)) return ok(value);\n path.add(value);\n try {\n if (Array.isArray(value)) {\n let list: unknown[] | undefined;\n for (let index = 0; index < value.length; index += 1) {\n const item = plainOf(value[index], path);\n if (!item.ok) return item;\n if (item.value !== value[index]) (list ??= [...(value as readonly unknown[])])[index] = item.value;\n }\n return ok(list ?? value);\n }\n const record = value as Readonly<Record<string, unknown>>;\n let out: Record<string, unknown> | undefined;\n for (const key of Object.keys(record)) {\n const item = plainOf(record[key], path);\n if (!item.ok) return item;\n if (item.value === record[key]) continue;\n if (out === undefined) {\n out = {};\n for (const other of Object.keys(record)) putField(out, other, record[other]);\n }\n putField(out, key, item.value);\n }\n return ok(out ?? value);\n } finally {\n path.delete(value);\n }\n}\n\n/**\n * This function makes a node of the decorated tree. A step `parent` gives the self of the context of the node, and a\n * step `type` gives its type. A step with the key of a part reads that attribute. A failed attribute throws `Failure`\n * with its own error, thus a reference to it gives that error.\n */\nfunction treeThing(parts: readonly Part[], context: Context, type: string, place: readonly Key[], build: TreeBuild): HostThing {\n const cells = new Map<string, Cell>();\n const read = (key: string): Result | undefined => {\n const cell = cells.get(key);\n if (cell !== undefined) return cell.busy ? cycleAt(cells, key, attributeText(key, type, place)) : cell.result;\n const part = parts.find((item) => item.key === key);\n if (part === undefined) return undefined;\n cells.set(key, BUSY);\n demands.push({ cells, key, text: attributeText(key, type, place) });\n let result: Result;\n try {\n result = part.evaluate({ ...context, self: node });\n } catch (error) {\n // An exception of the host, for example an overflow of the stack, leaves the attribute without a result.\n cells.delete(key);\n throw error;\n } finally {\n demands.pop();\n }\n cells.set(key, { busy: false, result });\n return result;\n };\n const state: NodeState = {\n build,\n type,\n place,\n json(path) {\n path.add(node);\n try {\n const out: Record<string, unknown> = {};\n for (const part of parts) {\n const result = read(part.key) as Result;\n if (!result.ok) return result;\n const value = plainOf(result.value, path);\n if (!value.ok) return value;\n putField(out, part.key, value.value);\n }\n return ok(out);\n } finally {\n path.delete(node);\n }\n },\n };\n const node: HostThing & { readonly type: string; readonly [TREE_NODE]: NodeState } = {\n [THING]: true,\n [TREE_NODE]: state,\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 if (result === undefined) return undefined;\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n toJson(): unknown {\n const result = state.json(new Set());\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n };\n return node;\n}\n\n/**\n * This function evaluates a node of the decorated tree. Inside an attribute of an open tree, the node gives its host\n * thing, and no attribute evaluates. Else the node is the root of a new tree, and it gives the JSON of the tree.\n */\nfunction treeNode({ parts, context, kind, place }: EvalInput): Result {\n const above = stateOf(context.self);\n if (above !== undefined && above.build.open) return ok(treeThing(parts, context, kind, place, above.build));\n const build: TreeBuild = { open: true };\n const root = treeThing(parts, context, kind, place, build);\n try {\n return (stateOf(root) as NodeState).json(new Set());\n } finally {\n build.open = false;\n }\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, partsOf, pathMatches } 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 read = partsOf(world, item.value, item.declared);\n if (!read.ok) {\n options.problem?.({ place: keysOf(item.place), at: keysOf(item.at), code: read.code, reason: read.reason });\n continue;\n }\n const { doc, kind, split } = read;\n const here = new Visit(\n item.place,\n item.at,\n doc,\n read.declared,\n item.depth,\n item.names,\n item.later,\n item.slot,\n item.parent,\n kind,\n read.typePath,\n item.address ? true : undefined,\n item.caps,\n );\n const answer = visit(here);\n if (answer === \"skip\" || kind === undefined) continue;\n const base: Trail | undefined = read.declared ? item.at : { up: item.at, keys: [\"value\"] };\n if (!split.ok) {\n options.problem?.({ place: keysOf(item.place), at: keysOf({ up: base, keys: split.at }), code: \"#VALUE!\", reason: split.reason });\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. With the hook `known` of the machine, also a name that the language does not\n * have, for example an operation.\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 } else if (machine.known !== undefined) {\n // The evaluator gives #NAME? in a run for a name that the language does not have, for example an operation.\n const known = machine.known(v.typePath ?? [], name);\n if (known !== true) issues.push({ code: \"#NAME?\", place: v.place, reason: known, 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 // The step documents of the path are parts, and they evaluate before the path, thus the walk visits them.\n return undefined;\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, type Key, 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\";\nimport { type MachinePart, mergeMachines } from \"./merge.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: { params: { shape: \"list\", item: { shape: \"text\" }, distinct: true }, 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 const held = (ctx: Context): Failed | undefined => {\n if (head === undefined || !Object.hasOwn(ctx.names, head)) return undefined;\n const bound = ctx.names[head];\n return bound instanceof Held ? { ok: false, error: bound.error } : undefined;\n };\n if (parts.length === 0) return (ctx, rt) => held(ctx) ?? give(rt.resolve(ctx, path));\n // The step documents of a path are its parts when the kind ref has a deep shape. They evaluate first, in order,\n // thus the error of a step comes before the error of a binding that the path reads (FORMULA.STEPS).\n return (ctx, rt) => {\n const steps = valuesOf(parts, ctx, rt);\n if (!Array.isArray(steps)) return steps;\n return held(ctx) ?? give(rt.resolve(ctx, fill(steps) as readonly unknown[]));\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 the hook `known` of the formula kit for one profile (STATIC.KNOWN). The evaluator\n * `formula.op` knows an operation of `lazy` or of `ops`. A profile whose `ops` is a function answers through a call\n * of that function. A function that throws counts as an answer, because the run then gives `#CALC!`. The evaluator\n * `formula.ext` knows an extension of `ext` and each standard extension. The hook knows each name of the other\n * evaluators.\n *\n * @param profile - The operations and the extensions of the language.\n * @returns The hook: `true`, or the reason of the `#NAME?` that the evaluator gives in a run.\n */\nexport function formulaKnown(profile: FormulaProfile = {}): (path: readonly Key[], evaluator: string) => true | string {\n const hasOp = (name: string): boolean => {\n if (profile.lazy !== undefined && Object.hasOwn(profile.lazy, name)) return true;\n const ops = profile.ops;\n if (ops === undefined) return false;\n if (typeof ops !== \"function\") return Object.hasOwn(ops, name);\n try {\n return ops(name) !== undefined;\n } catch {\n return true;\n }\n };\n const hasExt = (name: string): boolean => (profile.ext !== undefined && Object.hasOwn(profile.ext, name)) || Object.hasOwn(STD_EXT, name);\n return (path, evaluator) => {\n if (evaluator !== \"formula.op\" && evaluator !== \"formula.ext\") return true;\n // The evaluators give the same reasons when they do not find the name.\n const name = path.slice(1).join(\".\");\n if (evaluator === \"formula.op\") return hasOp(name) ? true : `The language has no operation ${name}.`;\n return hasExt(name) ? true : `The language has no extension ${name}.`;\n };\n}\n\n/**\n * This function makes a machine for a formula language. It merges the kit and the parts that the language adds with\n * `mergeMachines`. Thus a kind `ops.*` or a namespace `ops` of the language extends the namespace of the kit, and\n * the fallback of the kit stays. The hook `known` of the kit comes from the profile (`formulaKnown`). A hook `known`\n * of the language answers after it.\n *\n * A kind or an evaluator of the language that differs from the entry of the kit with its name is a conflict. The\n * language names the path in `replaces` to replace the entry, for example `[\"world\", \"kinds\", \"ref\"]` or\n * `[\"evaluators\", \"formula.op\"]`. Then the hook of the kit does not answer for a replaced evaluator.\n *\n * @param profile - The operations and the rules of the language.\n * @param more - The parts of a machine that the language adds, with the paths of the entries that it replaces.\n * @returns The machine.\n * @throws {MergeError} The language and the kit have a conflict.\n */\nexport function formulaMachine(profile: FormulaProfile = {}, more: MachinePart = {}): Machine {\n return mergeMachines({ world: { kinds: formulaKinds() }, evaluators: formulaEvaluators(profile), known: formulaKnown(profile) }, more);\n}\n","import { type Envelope, type Json, type Key, isEnvelope, isRecord, typeName } from \"./doc.ts\";\nimport { ask } from \"./ladder.ts\";\nimport type { CapsRule, Kind } from \"./world.ts\";\nimport { type PartSlot, type Split, partsOf, pathMatches } from \"./parts.ts\";\nimport { type Cap, type Context, type HostThing, type Resolution, type ResolveOptions, type Thing, THING, isHostThing, resolve, valueOfThing, worldThing } from \"./deref.ts\";\nimport { STD_EVALUATORS } from \"./stdlib.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, placed, thrown } from \"./errors.ts\";\nimport {\n type AllOptions,\n type Effect,\n type EvalFn,\n type EvalInput,\n type Machine,\n type Part,\n type RunFn,\n type RunInput,\n type RunPart,\n type Steps,\n intersectCaps,\n makeContext,\n permits,\n} from \"./evaluate.ts\";\nimport { type FormulaProfile, type OpFn, Held, STD_EXT } from \"./formula.ts\";\n\n/*\n * The reference interpreter: a direct reading of the rules of docs/SPEC.md. It compiles nothing and caches nothing.\n * At each evaluation of a document, it asks the ladder, finds the kind, splits the value and calls the evaluator. A\n * part evaluates only when its evaluator asks. Thus it shares no compiler with a plan, and a test can compare them.\n */\n\n/**\n * The definitional code of the reference, by evaluator name. The reference cannot read compiled code, thus each\n * compiled evaluator or runner of a machine needs a definition here. A function evaluator needs none.\n */\nexport interface Definitions {\n readonly evaluators?: Readonly<Record<string, EvalFn>>;\n readonly runners?: Readonly<Record<string, RunFn>>;\n}\n\n/** The options of the reference interpreter. */\nexport interface ReferenceOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The definitional code of the compiled evaluators and runners of the machine. */\n readonly definitions?: Definitions;\n /** A list that gets each effect, in its order. */\n readonly effects?: Effect[];\n}\n\n/** The state of one evaluation of the reference. */\ninterface Env {\n readonly machine: Machine;\n readonly definitions: Definitions;\n readonly effects: Effect[];\n readonly maxDepth: number;\n}\n\n/** The code that answers a document: a function evaluator, a runner, or a gap of the reference. */\ntype Chosen = { readonly evaluator: EvalFn } | { readonly runner: RunFn } | { readonly gap: string };\n\n/** The answers of the ladder and of the contract of the kind for one document. */\ninterface Seen {\n readonly doc: Envelope;\n readonly kindText: string;\n readonly typePath: readonly Key[];\n readonly kind: Kind | undefined;\n readonly name: string;\n readonly chosen: Chosen;\n readonly split: Extract<Split, { readonly ok: true }>;\n}\n\n/** One position of a document: its value, its place, the type that it declares, its depth and its context. */\ninterface At {\n readonly value: unknown;\n readonly place: readonly Key[];\n readonly declared: string | undefined;\n readonly depth: number;\n readonly address: boolean;\n readonly ctx: Context;\n}\n\nfunction own<T>(table: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return table !== undefined && Object.hasOwn(table, name) ? table[name] : undefined;\n}\n\n/**\n * This function finds the code of an evaluator name. A runner wins over an evaluator of the same name. A standard\n * evaluator gets the definition of the reference, unless the options give another definition (REF.TREE).\n */\nfunction choose(env: Env, name: string): Chosen | undefined {\n const runner = own(env.machine.runners, name);\n if (runner !== undefined) {\n const defined = own(env.definitions.runners, name);\n if (defined !== undefined) return { runner: defined };\n return typeof runner === \"function\" ? { runner } : { gap: `The reference has no definition of the compiled runner ${name}.` };\n }\n const evaluator = own(env.machine.evaluators, name);\n if (evaluator === undefined) return undefined;\n const standard = evaluator === own(STD_EVALUATORS, name) ? own(STD_DEFINITIONS.evaluators, name) : undefined;\n const defined = own(env.definitions.evaluators, name) ?? standard;\n if (defined !== undefined) return { evaluator: defined };\n return typeof evaluator === \"function\" ? { evaluator } : { gap: `The reference has no definition of the compiled evaluator ${name}.` };\n}\n\n/**\n * This function reads one document by the rules, in their order. First come an envelope or a declared type\n * (EVAL.ERRORS) and the limit of the depth (PLAN.DEPTH). Then come the ladder (LADDER.*), an evaluator and the shape\n * of the parts (SHAPE.*).\n */\nfunction examine(env: Env, at: At): Seen | Failed {\n const { place, declared } = at;\n const world = env.machine.world;\n // The lookup of the kind and the split of the value are definitions of the model (D15): partsOf gives both.\n const read = partsOf(world, at.value, declared);\n if (!read.ok) return fail(read.code, read.reason, { place });\n if (at.depth > env.maxDepth) return fail(\"#DEPTH!\", `The nesting is deeper than ${env.maxDepth} documents.`, { place });\n const { doc, kind, split } = read;\n const kindText = typeName(doc.type);\n const answer = ask(world, read.declared ? {} : doc, \"eval\", declared === undefined ? {} : { declaredType: declared });\n if (answer.error === \"unknown-kind\") return fail(\"#KIND?\", `The world has no kind ${kindText}.`, { place });\n const name = answer.evaluator;\n const chosen = name === undefined ? undefined : choose(env, name);\n if (name === undefined || chosen === undefined) return fail(\"#NOEVAL\", `No rung gives an evaluator for ${kindText}.`, { place });\n if (!split.ok) return fail(\"#VALUE!\", split.reason, { place });\n return { doc, kindText, typePath: read.typePath ?? [], kind, name, chosen, split };\n}\n\n/** This function gives the capabilities that the rules of a kind give one part (D14, CAP.CONTRACT, CAP.ONLY). */\nfunction capsOfPart(rules: readonly CapsRule[] | undefined, path: readonly Key[], caps: readonly Cap[]): readonly Cap[] {\n let out = caps;\n for (const rule of rules ?? []) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(path, pattern))) continue;\n if (rule.rule === \"mask\") return [];\n if (rule.rule === \"only\") out = intersectCaps(out, rule.caps);\n }\n return out;\n}\n\n/**\n * This function gives the context of a part. A context that the evaluator gives keeps only the capabilities of the\n * parent (CAP.NARROW). Then the rules of the kind narrow it (CAP.CONTRACT).\n */\nfunction contextOfPart(seen: Seen, slot: PartSlot, parent: Context, given: Context | undefined): Context {\n const base = given === undefined || given === parent ? parent : { ...given, caps: given.caps.filter((cap) => permits(parent.caps, cap)) };\n const caps = capsOfPart(seen.kind?.caps, slot.path, base.caps);\n return caps === base.caps ? base : { ...base, caps };\n}\n\nfunction headerOf(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 partAt(seen: Seen, at: At, slot: PartSlot, given: Context | undefined): At {\n return {\n value: slot.item,\n place: at.place.concat(slot.path),\n declared: slot.of,\n depth: at.depth + 1,\n address: slot.address === true,\n ctx: contextOfPart(seen, slot, at.ctx, given),\n };\n}\n\n/** This function resolves a path with the full algorithm of `resolve`, not with its short path (DEREF.QUICK). */\nfunction resolveFully(machine: Machine, ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const found = resolve(machine, ctx, path, { hops: true });\n return options?.hops === true ? found : { ...found, hops: [] };\n}\n\n/** This function records an effect when the capabilities permit it (RUN.CAP, CAP.HOOK). */\nfunction record(env: Env, ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Failed | undefined {\n const keys = typeof kind === \"string\" ? kind.split(\".\") : kind;\n const text = keys.join(\".\");\n const machine = env.machine;\n const allowed = machine.permits === undefined ? permits(ctx.caps, keys) : machine.permits(ctx.caps, keys, ctx);\n if (!allowed) return fail(\"#CAP!\", `The context has no capability for the effect ${text}.`, { place });\n env.effects.push({ index: env.effects.length, kind: text, path: keys, payload, node: -1, at: 0, place, context: ctx });\n return undefined;\n}\n\n/** This function evaluates a document. Each error gets the place of the document where it started (K5). */\nfunction evaluateAt(env: Env, at: At): Result {\n const seen = examine(env, at);\n if (!(\"doc\" in seen)) return seen;\n return evaluateSeen(env, seen, at);\n}\n\nfunction evaluateSeen(env: Env, seen: Seen, at: At): Result {\n const { chosen } = seen;\n const { place } = at;\n if (\"gap\" in chosen) return fail(\"#NOEVAL\", chosen.gap, { place });\n if (\"runner\" in chosen) return drive(runSeen(env, seen, at, chosen.runner), place);\n const input = evalInput(env, seen, at);\n try {\n return placed(chosen.evaluator(input), place);\n } catch (error) {\n return placed(thrown(error, `the evaluator ${seen.name}`), place);\n }\n}\n\n/** This function gives the steps of a document for a runner. Nothing happens before the first step. */\nfunction* stepsAt(env: Env, at: At): Steps {\n const seen = examine(env, at);\n if (!(\"doc\" in seen)) return seen;\n if (\"runner\" in seen.chosen) return yield* runSeen(env, seen, at, seen.chosen.runner);\n return evaluateSeen(env, seen, at);\n}\n\nfunction* runSeen(env: Env, seen: Seen, at: At, runner: RunFn): Steps {\n try {\n return placed(yield* runner(runInput(env, seen, at)), at.place);\n } catch (error) {\n return placed(thrown(error, `the runner ${seen.name}`), at.place);\n }\n}\n\n/** This function drives steps that cannot wait. A step that waits gives `#CALC!` at the document (RUN.WAIT). */\nfunction drive(steps: Steps, place: readonly Key[]): Result {\n const step = steps.next();\n if (step.done === true) return step.value;\n void step.value.catch(() => undefined);\n const waited = fail(\"#CALC!\", \"A part waited, and its parent cannot wait.\", { place });\n steps.return(waited);\n return waited;\n}\n\nfunction evalInput(env: Env, seen: Seen, at: At): EvalInput {\n const { split, doc } = seen;\n const parts: Part[] = split.parts.map((slot) => {\n const name = headerOf(slot.item);\n return {\n key: slot.key,\n path: slot.path,\n ...(name === undefined ? {} : { name }),\n evaluate: (given?: Context) => evaluateAt(env, partAt(seen, at, slot, given)),\n };\n });\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n return {\n kind: seen.kindText,\n typePath: seen.typePath,\n doc,\n value: fill(parts),\n data: split.data,\n parts,\n context: at.ctx,\n place: at.place,\n ...(at.address ? { address: true } : {}),\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: (kind, payload) => record(env, at.ctx, kind, payload, at.place) ?? ok(payload),\n fill,\n };\n}\n\nfunction runInput(env: Env, seen: Seen, at: At): RunInput {\n const { split, doc } = seen;\n const parts: RunPart[] = split.parts.map((slot) => {\n const name = headerOf(slot.item);\n return {\n key: slot.key,\n path: slot.path,\n ...(name === undefined ? {} : { name }),\n evaluate: (given?: Context) => stepsAt(env, partAt(seen, at, slot, given)),\n };\n });\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n return {\n kind: seen.kindText,\n typePath: seen.typePath,\n doc,\n value: fill(parts),\n data: split.data,\n parts,\n context: at.ctx,\n place: at.place,\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: function* (kind, payload) {\n return record(env, at.ctx, kind, payload, at.place) ?? ok(payload);\n },\n all: (list, options) => together(list, options),\n fill,\n };\n}\n\n/**\n * This function evaluates parts for `all` (RUN.ALL). The parts start in their order, up to the limit, and each part\n * goes on until it ends or waits. In an evaluation, a part that waits does not end, thus it keeps its place in the\n * limit. With `failFast`, the first failure stops the parts that wait, and the later parts do not start\n * (RUN.FAIL-FAST). When no part failed and a part waits, the steps wait, and the drive gives `#CALC!`.\n */\nfunction* together(list: readonly RunPart[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n const limit = Math.max(1, options.concurrency ?? list.length);\n const results: (Result | undefined)[] = list.map(() => undefined);\n const waiting: { readonly steps: Steps; readonly promise: Promise<unknown> }[] = [];\n let failed = false;\n for (let index = 0; index < list.length && !failed && waiting.length < limit; index += 1) {\n let result: Result | undefined;\n try {\n const steps = (list[index] as RunPart).evaluate();\n const step = steps.next();\n if (step.done === true) result = step.value;\n else waiting.push({ steps, promise: step.value });\n } catch (error) {\n result = thrown(error, \"a part\");\n }\n results[index] = result;\n if (result !== undefined && options.failFast === true && !result.ok) failed = true;\n }\n if (failed) {\n const stopped = fail(\"#ABORT\", \"The part stopped: a part before it failed, and the parts run with failFast.\");\n for (const item of waiting) {\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 return results.map((result) => result ?? stopped);\n }\n if (waiting.length > 0) yield Promise.race(waiting.map((item) => item.promise));\n // An evaluation stops at the first wait, thus only parts that ended reach this line.\n return results as readonly Result[];\n}\n\n/**\n * This function evaluates a document by the rules, without a compilation. It is the reference of the plans: a plan,\n * a traced plan and the second tier of a language must give its results. It covers evaluations, not runs: an effect\n * gives its payload, and a part that waits gives `#CALC!`.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document.\n * @param context - The names and the capabilities at the root.\n * @param options - The type of a bare root value, the definitions of compiled code, and a list for the effects.\n * @returns The result.\n */\nexport function reference(machine: Machine, doc: unknown, context: Context = makeContext(), options: ReferenceOptions = {}): Result {\n const env: Env = { machine, definitions: options.definitions ?? {}, effects: options.effects ?? [], maxDepth: machine.maxDepth ?? 1000 };\n const ctx = context.world === null ? { ...context, world: worldThing(machine.world) } : context;\n try {\n return evaluateAt(env, { value: doc, place: [], declared: options.declaredType, depth: 0, address: false, ctx });\n } catch (error) {\n return placed(thrown(error, \"the reference\"), []);\n }\n}\n\n/*\n * The definition of the decorated tree (TREE.*), written from docs/SPEC.md. It shares no code with `tree.node` of\n * stdlib.ts: its nodes, its memo, its marks for attributes in evaluation and its JSON are its own.\n */\n\n/** One tree of the reference in one evaluation. */\ninterface RefTree {\n open: boolean;\n}\n\n/** A node of the reference. Its host thing is the key of the table `refNodes`. */\ninterface RefNode {\n readonly tree: RefTree;\n readonly kind: string;\n readonly place: readonly Key[];\n readonly parts: readonly Part[];\n readonly ctx: Context;\n /** The results of the attributes that ended. */\n readonly values: Map<string, Result>;\n /** The attributes in evaluation. */\n readonly pending: Set<string>;\n}\n\nconst refNodes = new WeakMap<object, RefNode>();\n\n/** The attributes in evaluation in the reference, in the order of their demands (TREE.CYCLE). */\nconst inEvaluation: { readonly node: RefNode; readonly name: string }[] = [];\n\nfunction nameOfAttribute(node: RefNode, name: string): string {\n return `${name} of ${node.kind} at [${node.place.join(\", \")}]`;\n}\n\nfunction refNodeOf(thing: unknown): RefNode | undefined {\n return typeof thing === \"object\" && thing !== null ? refNodes.get(thing) : undefined;\n}\n\n/** TREE.ONCE, TREE.MEMO and TREE.CYCLE: the result of one attribute, or `undefined` when the node has no such part. */\nfunction attributeOf(node: RefNode, self: HostThing, name: string): Result | undefined {\n const done = node.values.get(name);\n if (done !== undefined) return done;\n if (node.pending.has(name)) {\n const from = inEvaluation.findIndex((entry) => entry.node === node && entry.name === name);\n const steps = from < 0 ? [nameOfAttribute(node, name)] : inEvaluation.slice(from).map((entry) => nameOfAttribute(entry.node, entry.name));\n return fail(\"#CYCLE!\", `The attributes form a cycle: ${[...steps, nameOfAttribute(node, name)].join(\" -> \")}.`);\n }\n const part = node.parts.find((item) => item.key === name);\n if (part === undefined) return undefined;\n node.pending.add(name);\n inEvaluation.push({ node, name });\n try {\n const result = part.evaluate({ ...node.ctx, self });\n node.values.set(name, result);\n return result;\n } finally {\n node.pending.delete(name);\n inEvaluation.pop();\n }\n}\n\n/** TREE.RESULT: the JSON of a node. `open` holds the nodes and the containers whose JSON is in progress. */\nfunction jsonOfNode(node: RefNode, self: HostThing, open: readonly object[]): Result {\n const record: Record<string, unknown> = {};\n for (const part of node.parts) {\n const result = attributeOf(node, self, part.key) as Result;\n if (!result.ok) return result;\n const value = plainValue(result.value, [...open, self]);\n if (!value.ok) return value;\n setField(record, part.key, value.value);\n }\n return ok(record);\n}\n\n/** This function gives a copy of a value with the JSON of each node in it. */\nfunction plainValue(value: unknown, open: readonly object[]): Result {\n const node = refNodeOf(value);\n if (node !== undefined) {\n if (open.includes(value as object)) return fail(\"#CYCLE!\", `The JSON of the node ${node.kind} at [${node.place.join(\", \")}] holds the node itself.`);\n return jsonOfNode(node, value as HostThing, open);\n }\n if (typeof value !== \"object\" || value === null || isHostThing(value) || open.includes(value)) return ok(value);\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n for (const item of value) {\n const plain = plainValue(item, [...open, value]);\n if (!plain.ok) return plain;\n items.push(plain.value);\n }\n return ok(items);\n }\n if (!isRecord(value)) return ok(value);\n const copy: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const plain = plainValue(value[key], [...open, value]);\n if (!plain.ok) return plain;\n setField(copy, key, plain.value);\n }\n return ok(copy);\n}\n\n/**\n * TREE.LAZY, TREE.PARENT, TREE.SIBLING and TREE.ERROR: a node of an open tree gives its thing, and the root of a new\n * tree gives its JSON. A step on the thing reads an attribute, and a failed attribute throws its own error.\n */\nconst treeDefinition: EvalFn = ({ parts, context, kind, place }) => {\n const outer = refNodeOf(context.self);\n const nested = outer !== undefined && outer.tree.open;\n const node: RefNode = { tree: nested ? outer.tree : { open: true }, kind, place, parts, ctx: context, values: new Map(), pending: new Set() };\n const self: HostThing & { readonly type: string } = {\n [THING]: true,\n type: kind,\n label: `node ${kind}`,\n deref: (key): Thing | undefined => {\n if (key === \"parent\") return context.self;\n if (key === \"type\") return kind;\n const result = attributeOf(node, self, String(key));\n if (result === undefined || result.ok) return result?.ok === true ? result.value : undefined;\n throw new Failure(result.error);\n },\n toJson: () => {\n const result = jsonOfNode(node, self, []);\n if (result.ok) return result.value;\n throw new Failure(result.error);\n },\n };\n refNodes.set(self, node);\n if (nested) return ok(self);\n try {\n return jsonOfNode(node, self, []);\n } finally {\n node.tree.open = false;\n }\n};\n\n/**\n * The definitions of the reference for the evaluators of the standard machine that need their own reading. The\n * reference uses them for the standard evaluators, also without the option `definitions`. It holds `tree.node`.\n */\nexport const STD_DEFINITIONS: Definitions = { evaluators: { \"tree.node\": treeDefinition } };\n\n/* The definitions of the formula kit: one function evaluator for each construct, written from docs/SPEC.md. */\n\nconst CLOSURE: unique symbol = Symbol.for(\"coeval.closure\") as never;\n\n/** This function sets an own field, also the field `__proto__` (SHAPE.PROTO). */\nfunction setField(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\nfunction partNamed(parts: readonly Part[], key: string): Part | undefined {\n return parts.find((part) => part.path.length === 1 && part.path[0] === key);\n}\n\nfunction partsUnder(parts: readonly Part[], key: string): readonly Part[] {\n return parts.filter((part) => part.path.length === 2 && part.path[0] === key);\n}\n\n/**\n * This function gives the definitions of the formula kit for one profile. Each construct is a function evaluator in\n * the most direct style. It shares no code with the compilers of `formulaEvaluators`, thus the two readings of the\n * rules can disagree, and a test finds it.\n *\n * @param profile - The operations and the rules of the language.\n * @returns The definitions, by evaluator name.\n */\nexport function formulaDefinitions(profile: FormulaProfile = {}): Definitions {\n const truthy = profile.truthy ?? ((value: unknown): boolean | undefined => (typeof value === \"boolean\" ? value : undefined));\n const opOf = (name: string): OpFn | undefined => (typeof profile.ops === \"function\" ? profile.ops(name) : own(profile.ops, name));\n const noTruth = (what: string): Failed => fail(\"#VALUE!\", `The ${what} must give a truth value.`);\n\n /** FORMULA.LIST, FORMULA.OPS and FORMULA.COMBINE: the values of parts in order, or the error. */\n const valuesOf = (parts: readonly Part[], skip?: (error: EvalError) => boolean): { readonly values: readonly (unknown | typeof SKIP)[] } | Failed => {\n const values: unknown[] = [];\n const errors: EvalError[] = [];\n for (const part of parts) {\n const result = part.evaluate();\n if (result.ok) values.push(result.value);\n else if (skip?.(result.error) === true) values.push(SKIP);\n else if (profile.combine === undefined) return result;\n else errors.push(result.error);\n }\n if (errors.length === 0 || profile.combine === undefined) return { values };\n return { ok: false, error: errors.length === 1 ? (errors[0] as EvalError) : profile.combine(errors) };\n };\n\n const lit: EvalFn = ({ doc }) => ok(doc.value);\n\n const ref: EvalFn = ({ doc, parts, fill, address, context, resolve: walk }) => {\n const path = doc.value;\n if (!Array.isArray(path) || path.length === 0) return fail(\"#VALUE!\", 'The value of ref is a path: a list that starts with a root, for example [\"names\", \"a\"].');\n // FORMULA.STEPS: the step documents of the path are parts. They evaluate first, in order.\n let steps: readonly unknown[] = path;\n if (parts.length > 0) {\n const all = valuesOfStrict(parts);\n if (!(\"values\" in all)) return all;\n steps = fill(all.values) as readonly unknown[];\n }\n // FORMULA.LET: 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 bound = head === undefined ? undefined : own(context.names, head);\n if (bound instanceof Held) return { ok: false, error: bound.error };\n const found = walk(steps);\n if (!found.ok) return fail(found.code, found.reason);\n // FORMULA.ADDRESS: an address gives what the path reaches.\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 (profile.missing?.(reached) === true) return fail(\"#N/A\", \"The path reaches no value.\");\n return ok(reached);\n };\n\n const step: EvalFn = ({ doc, parts, fill }) => {\n if (parts.length === 0) return ok(doc);\n const all = valuesOfStrict(parts);\n return \"values\" in all ? ok({ ...doc, value: fill(all.values) as Json }) : all;\n };\n\n const record: EvalFn = ({ parts }) => {\n const all = valuesOf(parts, profile.omit);\n if (!(\"values\" in all)) return all;\n const out: Record<string, unknown> = {};\n parts.forEach((part, index) => {\n const value = all.values[index];\n if (value !== SKIP) setField(out, String(part.path[0]), value);\n });\n return ok(out);\n };\n\n const list: EvalFn = ({ parts }) => {\n const all = valuesOf(parts);\n return \"values\" in all ? ok([...all.values]) : all;\n };\n\n const letIn: EvalFn = ({ parts, context }) => {\n const names: Record<string, unknown> = {};\n for (const key of Object.keys(context.names)) setField(names, key, context.names[key]);\n for (const binding of partsUnder(parts, \"bind\")) {\n const result = binding.evaluate();\n setField(names, String(binding.path[1]), result.ok ? result.value : new Held(result.error));\n }\n return (partNamed(parts, \"body\") as Part).evaluate({ ...context, names });\n };\n\n const fn: EvalFn = ({ data, parts, context }) => {\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 return fail(\"#VALUE!\", \"The params of fn are a list of different texts.\");\n }\n const names = params as readonly string[];\n const body = partNamed(parts, \"body\") as Part;\n const closure = (...args: readonly unknown[]): unknown => {\n const scope: Record<string, unknown> = {};\n for (const key of Object.keys(context.names)) setField(scope, key, context.names[key]);\n names.forEach((name, index) => setField(scope, name, args[index]));\n const result = body.evaluate({ ...context, names: scope });\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 const call: EvalFn = ({ parts }) => {\n const target = (partNamed(parts, \"fn\") as Part).evaluate();\n if (!target.ok) return target;\n if (typeof target.value !== \"function\") return fail(\"#VALUE!\", \"The fn of call must give a function.\");\n const all = valuesOfStrict(partsUnder(parts, \"args\"));\n if (!(\"values\" in all)) return all;\n try {\n return ok((target.value as (...items: unknown[]) => unknown)(...all.values));\n } catch (error) {\n return thrown(error, \"the function of call\");\n }\n };\n\n const choice: EvalFn = ({ parts }) => {\n const test = (partNamed(parts, \"test\") as Part).evaluate();\n if (!test.ok) return test;\n const truth = truthy(test.value);\n if (truth === undefined) return noTruth(\"test of if\");\n if (truth) return (partNamed(parts, \"then\") as Part).evaluate();\n const other = partNamed(parts, \"else\");\n if (other !== undefined) return other.evaluate();\n return ok(Object.hasOwn(profile, \"otherwise\") ? profile.otherwise : null);\n };\n\n /** FORMULA.LOGIC: `and` stops at the first false term, and `or` at the first true term. */\n const logic =\n (stopAt: boolean, what: string): EvalFn =>\n ({ parts }) => {\n let last: Result = ok(!stopAt);\n for (const part of parts) {\n last = part.evaluate();\n if (!last.ok) return last;\n const truth = truthy(last.value);\n if (truth === undefined) return noTruth(what);\n if (truth === stopAt) return profile.logic === \"value\" ? last : ok(stopAt);\n }\n return profile.logic === \"value\" ? last : ok(!stopAt);\n };\n\n const op: EvalFn = ({ typePath, parts }) => {\n const name = typePath.slice(1).join(\".\");\n const lazy = own(profile.lazy, name);\n if (lazy !== undefined) {\n try {\n return lazy(parts.map((part) => () => part.evaluate()));\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n }\n const apply = opOf(name) as ((...args: unknown[]) => unknown) | undefined;\n if (apply === undefined) return fail(\"#NAME?\", `The language has no operation ${name}.`);\n const all = valuesOf(parts);\n if (!(\"values\" in all)) return all;\n try {\n const out = apply(...all.values);\n return profile.check?.(out, name) ?? ok(out);\n } catch (error) {\n return thrown(error, `the operation ${name}`);\n }\n };\n\n const ext: EvalFn = ({ typePath, doc, context }) => {\n const name = typePath.slice(1).join(\".\");\n const handler = own(profile.ext, name) ?? own(STD_EXT, name);\n if (handler === undefined) return fail(\"#NAME?\", `The language has no extension ${name}.`);\n try {\n return handler(doc.value, context);\n } catch (error) {\n return thrown(error, `the extension ${name}`);\n }\n };\n\n return {\n evaluators: {\n \"formula.lit\": lit,\n \"formula.ref\": ref,\n \"formula.step\": step,\n \"formula.record\": record,\n \"formula.list\": list,\n \"formula.let\": letIn,\n \"formula.fn\": fn,\n \"formula.call\": call,\n \"formula.if\": choice,\n \"formula.and\": logic(false, \"term of and\"),\n \"formula.or\": logic(true, \"term of or\"),\n \"formula.op\": op,\n \"formula.ext\": ext,\n },\n };\n}\n\n/** The mark of a field that the profile leaves out of a record (FORMULA.RECORD). */\nconst SKIP: unique symbol = Symbol(\"skip\");\n\n/** The values of parts in order. The first error stops them, also with `combine` (FORMULA.STEPS, FORMULA.FN). */\nfunction valuesOfStrict(parts: readonly Part[]): { readonly values: readonly unknown[] } | Failed {\n const values: unknown[] = [];\n for (const part of parts) {\n const result = part.evaluate();\n if (!result.ok) return result;\n values.push(result.value);\n }\n return { values };\n}\n","import { type Key, docEquals, isRecord } from \"./doc.ts\";\nimport type { Context } from \"./deref.ts\";\nimport { type EvalError, type Result, isStackOverflow, thrown } from \"./errors.ts\";\nimport { type Effect, type Machine, evaluate, makeContext, prepare } from \"./evaluate.ts\";\nimport { Held, isClosure } from \"./formula.ts\";\nimport { type Definitions, reference } from \"./reference.ts\";\n\n/**\n * A tier that `agree` compares with the plan.\n *\n * - `reference`: the reference interpreter, which compiles nothing.\n * - `traced`: the traced evaluation, `evaluate`.\n * - `again`: a second evaluation of the same plan.\n * - `other`: the second tier of a language, from the option `other`.\n */\nexport type Tier = \"reference\" | \"traced\" | \"again\" | \"other\";\n\n/** What a second tier gives: its result, and its effects when it records them. */\nexport interface TierResult {\n readonly result: Result;\n readonly effects?: readonly Effect[];\n}\n\n/** The options of `agree`. */\nexport interface AgreeOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The definitional code of the compiled evaluators of the machine, for the reference. */\n readonly definitions?: Definitions;\n /** The tiers to compare with the plan. The default is the reference, the traced evaluation and a second evaluation. */\n readonly tiers?: readonly Exclude<Tier, \"other\">[];\n /**\n * This function gives the result of the second tier of a language, for example a compiler to loops.\n *\n * @param doc - The document.\n * @param context - The context.\n * @returns The result, or the result with the effects.\n */\n readonly other?: (doc: unknown, context: Context) => Result | TierResult;\n /**\n * This function compares two values that the rules of `sameValue` do not know, for example two dates.\n *\n * @param a - The value of the plan.\n * @param b - The value of the other tier.\n * @returns `true` or `false`, or `undefined` to use the rules of `sameValue`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n /** `true`: two errors must also have the same reason, and each error must have a place. */\n readonly strict?: boolean;\n /**\n * This function gives what the host saw since its last call, for example the calls of an operation. `agree` uses\n * it before the plan and after each tier, and compares the results. Thus a tier that evaluates a part that the plan\n * does not evaluate fails.\n *\n * @returns What the host saw.\n */\n readonly observe?: () => unknown;\n}\n\n/** The outcome of `agree`: the result of the plan, or the first tier that disagrees with it. */\nexport type Agreement =\n | { readonly ok: true; readonly result: Result; readonly effects: readonly Effect[] }\n | {\n readonly ok: false;\n readonly tier: Tier;\n /** The result of the plan. */\n readonly plan: Result;\n /** The result of the tier that disagrees. */\n readonly other: Result;\n /** One sentence that tells the difference. */\n readonly reason: string;\n };\n\n/**\n * This function tells if two values are the same for `agree`. Lists and plain records compare item by item and field\n * by field, and the order of the fields does not matter. Each other leaf compares with `Object.is`, thus `-0` is not\n * `0`, and `NaN` is `NaN`. The identity of a list or of a plain record is not compared.\n *\n * Two closures of `fn` are the same when they have the same parameters. Two `Held` values are the same when their\n * errors have the same code and place. Each other object is the same only as itself, unless the rule of the caller\n * tells otherwise.\n *\n * `docEquals` uses the same rules for lists, plain records and the other objects. It has no rules for closures, for\n * `Held` values and for a rule of the caller. Thus two closures are equal there only when they are the same function.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param equal - The rule of the caller for other values. It answers first, and `undefined` gives the rules above.\n * @returns `true` when the values are the same.\n */\nexport function sameValue(a: unknown, b: unknown, equal?: (a: unknown, b: unknown) => boolean | undefined): boolean {\n const stack: (readonly [unknown, unknown])[] = [[a, b]];\n const seen = new Map<object, Set<object>>();\n while (stack.length > 0) {\n const [x, y] = stack.pop() as readonly [unknown, unknown];\n if (Object.is(x, y)) continue;\n const told = equal?.(x, y);\n if (told !== undefined) {\n if (told) continue;\n return false;\n }\n if (typeof x !== \"object\" && typeof x !== \"function\") return false;\n if (typeof y !== \"object\" && typeof y !== \"function\") return false;\n if (x === null || y === null) return false;\n // A pair that the comparison already visits is the same, unless another pair shows a difference.\n const pairs = seen.get(x) ?? new Set<object>();\n if (pairs.has(y)) continue;\n pairs.add(y);\n seen.set(x, pairs);\n if (isClosure(x) || isClosure(y)) {\n if (!(isClosure(x) && isClosure(y))) return false;\n stack.push([closureParams(x), closureParams(y)]);\n continue;\n }\n if (x instanceof Held || y instanceof Held) {\n if (!(x instanceof Held && y instanceof Held) || errorDiffers(x.error, y.error, false) !== undefined) return false;\n continue;\n }\n if (Array.isArray(x) || Array.isArray(y)) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) return false;\n for (let index = 0; index < x.length; index += 1) stack.push([x[index], y[index]]);\n continue;\n }\n if (!isRecord(x) || !isRecord(y)) return false;\n const keys = Object.keys(x);\n if (keys.length !== Object.keys(y).length) return false;\n for (const key of keys) {\n if (!Object.hasOwn(y, key)) return false;\n stack.push([x[key], y[key]]);\n }\n }\n return true;\n}\n\nconst CLOSURE = Symbol.for(\"coeval.closure\");\n\nfunction closureParams(fn: object): unknown {\n return (fn as { readonly [CLOSURE]?: { readonly params: readonly string[] } })[CLOSURE]?.params;\n}\n\nfunction codeAndPlace(error: EvalError): string {\n return error.place === undefined ? error.code : `${error.code} at [${error.place.join(\", \")}]`;\n}\n\n/** This function gives the difference of two errors, or `undefined` when they agree. */\nfunction errorDiffers(a: EvalError, b: EvalError, strict: boolean): string | undefined {\n if (a.code !== b.code) return `The plan gives ${codeAndPlace(a)}, and the tier gives ${codeAndPlace(b)}.`;\n if (strict && (a.place === undefined || b.place === undefined)) return `An error ${a.code} has no place.`;\n if (a.place !== undefined && b.place !== undefined && !docEquals(a.place as readonly Key[], b.place as readonly Key[])) {\n return `The error ${a.code} has the place [${a.place.join(\", \")}] in the plan, and [${b.place.join(\", \")}] in the tier.`;\n }\n if (strict && a.reason !== b.reason) return `The error ${a.code} has another reason in the tier: \"${b.reason}\" for \"${a.reason}\".`;\n return undefined;\n}\n\n/** A host stack overflow is the one permitted difference (VALUE.DEPTH): the tiers use different numbers of frames. */\nfunction overflowed(result: Result): boolean {\n return !result.ok && result.error.code === \"#DEPTH!\" && isStackOverflow(result.error.cause);\n}\n\n/** This function gives the difference of two results, or `undefined` when they agree. */\nfunction resultDiffers(a: Result, b: Result, options: AgreeOptions): string | undefined {\n if (a.ok && b.ok) return sameValue(a.value, b.value, options.equal) ? undefined : \"The plan and the tier give different values.\";\n if (!a.ok && !b.ok) return errorDiffers(a.error, b.error, options.strict === true);\n return a.ok ? `The plan gives a value, and the tier gives ${codeAndPlace((b as { readonly error: EvalError }).error)}.` : `The plan gives ${codeAndPlace(a.error)}, and the tier gives a value.`;\n}\n\n/** This function gives the difference of two lists of effects, or `undefined` when they agree (EFFECT.ORDER). */\nfunction effectsDiffer(a: readonly Effect[], b: readonly Effect[], options: AgreeOptions): string | undefined {\n if (a.length !== b.length) return `The plan causes ${a.length} effects, and the tier causes ${b.length}.`;\n for (let index = 0; index < a.length; index += 1) {\n const x = a[index] as Effect;\n const y = b[index] as Effect;\n if (x.kind !== y.kind || !docEquals(x.place as readonly Key[], y.place as readonly Key[]) || !sameValue(x.payload, y.payload, options.equal)) {\n return `The effect ${index} differs: ${x.kind} at [${x.place.join(\", \")}] in the plan, and ${y.kind} at [${y.place.join(\", \")}] in the tier.`;\n }\n }\n return undefined;\n}\n\n/**\n * This function evaluates a document with a plan and with other tiers, and compares the results (PLAN.AGREES). Two\n * results agree when they have the same value by `sameValue`, or errors with the same code, and the same place when\n * both have one. The effects must have the same kinds, places and payloads, in the same order. A language gives its\n * own tier with the option `other`.\n *\n * @param machine - The world and the code of the evaluators.\n * @param doc - The document.\n * @param context - The names and the capabilities at the root.\n * @param options - The tiers, the definitions for the reference, the rules of the comparison and the second tier.\n * @returns The result of the plan, or the first tier that disagrees and the reason.\n */\nexport function agree(machine: Machine, doc: unknown, context: Context = makeContext(), options: AgreeOptions = {}): Agreement {\n const declared = options.declaredType === undefined ? {} : { declaredType: options.declaredType };\n const observe = options.observe;\n observe?.();\n const plan = prepare(machine, doc, declared);\n const effects: Effect[] = [];\n const result = plan.evaluate(context, { effects });\n const saw = observe?.();\n\n const differs = (other: Result, otherEffects: readonly Effect[] | undefined): string | undefined => {\n if (overflowed(result) || overflowed(other)) return undefined;\n const why = resultDiffers(result, other, options) ?? (otherEffects === undefined ? undefined : effectsDiffer(effects, otherEffects, options));\n if (why !== undefined || observe === undefined) return why;\n return sameValue(saw, observe(), options.equal) ? undefined : \"The host saw other calls in the tier.\";\n };\n\n for (const tier of options.tiers ?? [\"reference\", \"traced\", \"again\"]) {\n let other: Result;\n let otherEffects: Effect[] = [];\n if (tier === \"reference\") {\n other = reference(machine, doc, context, { ...declared, effects: otherEffects, ...(options.definitions === undefined ? {} : { definitions: options.definitions }) });\n } else if (tier === \"traced\") {\n const traced = evaluate(machine, doc, context, options.declaredType);\n other = traced.result;\n otherEffects = [...traced.effects];\n } else {\n other = plan.evaluate(context, { effects: otherEffects });\n }\n const why = differs(other, otherEffects);\n if (why !== undefined) return { ok: false, tier, plan: result, other, reason: why };\n }\n\n if (options.other !== undefined) {\n let given: Result | TierResult;\n try {\n given = options.other(doc, context);\n } catch (error) {\n given = thrown(error, \"the tier\");\n }\n const other = \"result\" in given ? given.result : given;\n const why = differs(other, \"result\" in given ? given.effects : undefined);\n if (why !== undefined) return { ok: false, tier: \"other\", plan: result, other, reason: why };\n }\n return { ok: true, result, effects };\n}\n","import { type Json, type Key, docEquals, isEnvelope, typePath } from \"./doc.ts\";\nimport { type Kind, type ScopeRule, type Shape, type World, type WorldEntry, isAlias, isKind, isNamespace, lookupKind } from \"./world.ts\";\nimport { pathMatches } from \"./parts.ts\";\nimport { ROOTS, type Root } from \"./deref.ts\";\n\n/** A source of random numbers with a seed. The same seed gives the same numbers. */\nexport interface Random {\n /** This function gives a number from 0 up to 1, without 1. */\n next(): number;\n /** This function gives a whole number from 0 up to `below`, without `below`. */\n int(below: number): number;\n /** This function gives `true` with the chance `p`. */\n chance(p: number): boolean;\n /** This function gives one item of a list that is not empty. */\n pick<T>(items: readonly T[]): T;\n}\n\n/**\n * This function makes a source of random numbers with a seed (the algorithm mulberry32). It needs no package.\n *\n * @param seed - The seed: a whole number.\n * @returns The source.\n */\nexport function random(seed: number): Random {\n let state = seed >>> 0;\n const next = (): number => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n const int = (below: number): number => Math.floor(next() * below);\n return { next, int, chance: (p) => next() < p, pick: (items) => items[int(items.length)] as never };\n}\n\n/** The options of `generate`. */\nexport interface GenerateOptions {\n /** The seed. The same seed and the same options give the same document. */\n readonly seed: number;\n /** The types that a document can have. The default is `typesOf(world)`. A namespace with a fallback needs its keys here. */\n readonly types?: readonly (readonly Key[])[];\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 deepest nesting of documents. The default is 4. */\n readonly maxDepth?: number;\n /** The most documents in one document. The default is 24. */\n readonly maxSize?: number;\n /** The chance of a malformed choice at each document. The default is 0.05. */\n readonly malformed?: number;\n /**\n * This function gives the data of a document of a type without parts, for example a number for the kind `number`.\n *\n * @param type - The keys of the type.\n * @param random - The source of random numbers.\n * @returns The data, or `undefined` for a random JSON value.\n */\n readonly data?: (type: readonly Key[], random: Random) => Json | undefined;\n /**\n * This function gives the types to prefer for a part, for example a function for the field `fn` of `call`.\n *\n * @param type - The keys of the type of the parent.\n * @param path - The path of the part in the value of the parent.\n * @returns The types, or `undefined` for no preference.\n */\n readonly hints?: (type: readonly Key[], path: readonly Key[]) => readonly (readonly Key[])[] | undefined;\n /** The evaluator names for own entries. The default is none. */\n readonly own?: readonly string[];\n /** The keys for the steps of a path after its root and its name. */\n readonly keys?: readonly Key[];\n /** The roots that a path can start at. The default is each root. */\n readonly roots?: readonly Root[];\n /** The most steps of a path after its root and its name. The default is 2. */\n readonly steps?: number;\n}\n\n/**\n * This function lists the types of a world: each kind and each alias, also in a namespace. A namespace with a\n * fallback gives no types, because each key names a kind.\n *\n * @param world - The world.\n * @returns The keys of each type.\n */\nexport function typesOf(world: World): readonly (readonly Key[])[] {\n const out: (readonly Key[])[] = [];\n const visit = (entries: Readonly<Record<string, WorldEntry>>, prefix: readonly Key[]): void => {\n for (const key of Object.keys(entries)) {\n const entry = entries[key];\n if (isKind(entry) || isAlias(entry)) out.push([...prefix, key]);\n else if (isNamespace(entry)) visit(entry.kinds, [...prefix, key]);\n }\n };\n visit(world.kinds, []);\n return out;\n}\n\nconst NAMES = [\"a\", \"b\", \"x\", \"n\", \"last\", \"__proto__\"] as const;\nconst FIELDS = [\"a\", \"b\", \"c\", \"1\", \"__proto__\"] as const;\nconst KEYS: readonly Key[] = [\"a\", \"b\", \"x\", 0, 1, \"0\", \"length\", \"type\", \"value\", \"parent\"];\n\n/** This function tells if a kind can be a leaf: it needs no part. */\nfunction leafKind(kind: Kind | undefined): boolean {\n const shape = kind?.parts;\n return shape === undefined || shape.shape === \"none\" || shape.shape === \"list\" || shape.shape === \"map\" || shape.shape === \"text\" || shape.shape === \"number\" || shape.shape === \"one\";\n}\n\n/** A position of a document: the type that it declares, the kinds that it permits, the names that it sees and its depth. */\ninterface Position {\n readonly declared: string | undefined;\n readonly kinds: readonly (readonly Key[])[] | undefined;\n readonly names: readonly string[];\n readonly depth: number;\n readonly hint: readonly (readonly Key[])[] | undefined;\n}\n\n/** The names that the scope rules of one document bind, and the parts that see them. */\ninterface Scope {\n readonly rules: readonly ScopeRule[];\n /** The names of each rule, or the names of the headers so far for a rule `headers`. */\n readonly names: string[][];\n /** The number of parts that each rule covered so far. */\n readonly covered: number[];\n /** The data of a source of names, by its path as one text. */\n readonly sources: Map<string, { readonly keys: readonly string[] } | { readonly list: readonly string[] } | { readonly text: string }>;\n}\n\n/**\n * This function builds a random document for a world from the contracts of its kinds. It reads the shapes of the\n * parts, the declared types, the permitted kinds and the names that the scope rules bind. Some choices are malformed\n * on purpose, for example an unknown kind or an unknown name under a namespace with a fallback. Other examples are a\n * value without its shape, a bare value without a type and a name that nothing binds. The depth and the size have\n * limits.\n *\n * @param world - The world.\n * @param options - The seed, the types, the limits and the data of the leaves.\n * @returns The document, as JSON.\n */\nexport function generate(world: World, options: GenerateOptions): unknown {\n const rng = random(options.seed);\n const types = options.types ?? typesOf(world);\n const maxDepth = options.maxDepth ?? 4;\n const maxSize = options.maxSize ?? 24;\n const malformed = options.malformed ?? 0.05;\n const keys = options.keys ?? KEYS;\n const steps = options.steps ?? 2;\n const roots: readonly Root[] = options.roots ?? ROOTS;\n const stepTypes = types.filter((type) => {\n const found = lookupKind(world, type);\n return found.ok && Object.hasOwn(found.kind.verbs, \"step\");\n });\n // A name under each namespace with a fallback that no evaluator knows, for example [\"ops\", \"nope\"].\n const unknownNames: readonly (readonly Key[])[] = Object.keys(world.kinds)\n .filter((key) => {\n const entry = world.kinds[key];\n return isNamespace(entry) && entry.fallback !== undefined;\n })\n .map((key) => [key, \"nope\"]);\n let size = 0;\n\n const kindOf = (type: readonly Key[]): Kind | undefined => {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : undefined;\n };\n\n const anyJson = (depth = 0): Json => {\n const roll = rng.int(depth > 1 ? 6 : 8);\n if (roll === 0) return null;\n if (roll === 1) return rng.chance(0.5);\n if (roll === 2) return rng.pick([0, 1, 2, -1, 0.5, 1e21]);\n if (roll === 3) return rng.pick([\"\", \"a\", \"text\", \"0\"]);\n if (roll === 4) return rng.int(10);\n if (roll === 5) return rng.pick(NAMES);\n if (roll === 6) return Array.from({ length: rng.int(3) }, () => anyJson(depth + 1));\n const out: Record<string, Json> = {};\n for (let index = rng.int(3); index > 0; index -= 1) Object.defineProperty(out, rng.pick(FIELDS), { value: anyJson(depth + 1), enumerable: true, writable: true, configurable: true });\n return out;\n };\n\n const dataOf = (type: readonly Key[]): Json => options.data?.(type, rng) ?? anyJson();\n\n const renderType = (type: readonly Key[]): Json => {\n const roll = rng.next();\n if (roll < 0.06) return { type: \"ref\", value: [\"world\", ...type] };\n if (type.length === 1 && roll < 0.8) return type[0] as Json;\n return [...type];\n };\n\n const permitted = (type: readonly Key[], kinds: readonly (readonly Key[])[] | undefined): boolean =>\n kinds === undefined || kinds.some((kind) => kind.length <= type.length && kind.every((key, index) => String(key) === String(type[index])));\n\n const pickName = (names: readonly string[]): string => (names.length === 0 || rng.chance(malformed) ? rng.pick([\"unbound\", \"zz\"]) : rng.pick(names));\n\n const someNames = (): string[] => {\n const out = new Set<string>();\n for (let index = 1 + rng.int(2); index > 0; index -= 1) out.add(rng.pick(NAMES));\n return [...out];\n };\n\n const envelope = (type: readonly Key[], value: Json, header?: string): Json => {\n const out: Record<string, Json> = { type: renderType(type), value };\n if (header !== undefined) out[\"name\"] = header;\n if (options.own !== undefined && options.own.length > 0 && rng.chance(0.03)) out[\"own\"] = { eval: rng.pick(options.own) };\n return out;\n };\n\n /** A path from a root (D10). It uses the names in scope, and sometimes a step document. */\n const pathFor = (pos: Position, refKind: Kind | undefined): Json => {\n if (rng.chance(malformed)) return rng.pick<Json>([\"names\", [], { names: \"a\" }, [\"nowhere\", \"a\"]]);\n const others = roots.filter((name) => name !== \"names\");\n const named = roots.includes(\"names\") && pos.names.length > 0 && (others.length === 0 || rng.chance(0.75));\n const root = named || others.length === 0 ? \"names\" : rng.pick(others);\n const path: Json[] = [root];\n if (root === \"names\") path.push(pickName(pos.names));\n if (root === \"world\") path.push(String(rng.pick(types)[0]));\n for (let index = rng.int(steps + 1); index > 0; index -= 1) {\n if (stepTypes.length > 0 && rng.chance(0.2)) {\n const type = rng.pick(stepTypes);\n const kind = kindOf(type);\n // With a deep shape of the kind ref, the value of a step document can hold parts.\n const value = refKind?.parts?.shape === \"deep\" && kind?.parts !== undefined ? valueOf(kind.parts, [], { ...pos, depth: pos.depth + 1 }, emptyScope()) : dataOf(type);\n path.push({ type: renderType(type), value });\n } else {\n path.push(rng.pick(keys) as Json);\n }\n }\n return path;\n };\n\n const emptyScope = (): Scope => ({ rules: [], names: [], covered: [], sources: new Map() });\n\n /** This function decides the names of the scope rules before the parts, so that each part knows what it sees. */\n const scopeOf = (kind: Kind): Scope => {\n const rules = kind.scope ?? [];\n const scope: Scope = { rules, names: [], covered: rules.map(() => 0), sources: new Map() };\n for (const rule of rules) {\n const source = rule.names;\n let names: string[] = [];\n if (\"fixed\" in source) names = [...source.fixed];\n else if (\"keysAt\" in source) {\n names = someNames();\n scope.sources.set(source.keysAt.join(\".\"), { keys: names });\n } else if (\"listAt\" in source) {\n names = someNames();\n scope.sources.set(source.listAt.join(\".\"), { list: rng.chance(malformed) ? [...names, ...names] : names });\n } else if (\"textAt\" in source) {\n names = [rng.pick(NAMES)];\n scope.sources.set(source.textAt.join(\".\"), { text: names[0] as string });\n }\n scope.names.push(names);\n }\n return scope;\n };\n\n /** The names that a part sees from the scope rules of its parent. A rule `sequential` shows only earlier names. */\n const seenBy = (scope: Scope, path: readonly Key[]): { readonly names: readonly string[]; readonly headers: boolean } => {\n const names: string[] = [];\n let headers = false;\n scope.rules.forEach((rule, index) => {\n if (!rule.in.some((pattern) => pathMatches(path, pattern))) return;\n const ruleNames = scope.names[index] ?? [];\n if (\"headers\" in rule.names) headers = true;\n if (rule.sequential !== true || \"headers\" in rule.names || (scope.covered[index] ?? 0) > 0) names.push(...ruleNames);\n });\n return { names, headers };\n };\n\n /** This function records the part at a path, and the header name that it got, for the rules that cover it. */\n const saw = (scope: Scope, path: readonly Key[], part: Json): void => {\n const header = isEnvelope(part) && typeof (part as { readonly name?: unknown }).name === \"string\" ? (part as { readonly name: string }).name : undefined;\n scope.rules.forEach((rule, index) => {\n if (!rule.in.some((pattern) => pathMatches(path, pattern))) return;\n scope.covered[index] = (scope.covered[index] ?? 0) + 1;\n if (\"headers\" in rule.names && header !== undefined) scope.names[index]?.push(header);\n });\n };\n\n const partAt = (pos: Position, scope: Scope, path: readonly Key[], spec: Extract<Shape, { readonly shape: \"term\" }> | { readonly shape: \"term\"; readonly of?: string }, parentType: readonly Key[] | undefined): Json => {\n const seen = seenBy(scope, path);\n const header = seen.headers && rng.chance(0.5) ? rng.pick(NAMES) : undefined;\n const part = docAt(\n {\n declared: spec.of,\n kinds: \"kinds\" in spec ? spec.kinds : undefined,\n names: seen.names.length === 0 ? pos.names : [...pos.names, ...seen.names],\n depth: pos.depth + 1,\n hint: parentType === undefined ? undefined : options.hints?.(parentType, path),\n },\n header,\n );\n saw(scope, path, part);\n return part;\n };\n\n /** This function builds a value of a shape (SHAPE.*). A part is a document at the next depth. */\n const valueOf = (shape: Shape | undefined, path: readonly Key[], pos: Position, scope: Scope, type?: readonly Key[]): Json => {\n const source = scope.sources.get(path.join(\".\"));\n if (source !== undefined && \"list\" in source) return [...source.list];\n if (source !== undefined && \"text\" in source) return source.text;\n const term = (of: string | undefined): { readonly shape: \"term\"; readonly of?: string } => (of === undefined ? { shape: \"term\" } : { shape: \"term\", of });\n const small = (): number => (pos.depth >= maxDepth ? 0 : size >= maxSize ? rng.int(2) : rng.int(4));\n if (shape === undefined || shape.shape === \"none\") return path.length === 0 && type !== undefined ? dataOf(type) : anyJson();\n switch (shape.shape) {\n case \"term\":\n return partAt(pos, scope, path, shape, type);\n case \"list\": {\n const items = Array.from({ length: small() }, (_, index) => valueOf(shape.item ?? term(shape.of), [...path, index], pos, scope, type));\n if (shape.distinct !== true || rng.chance(malformed)) return items;\n return items.filter((item, index) => !items.slice(0, index).some((before) => docEquals(before, item)));\n }\n case \"map\": {\n const out: Record<string, Json> = {};\n const names = source !== undefined && \"keys\" in source ? source.keys : Array.from({ length: small() }, () => rng.pick(FIELDS));\n for (const key of names) Object.defineProperty(out, key, { value: valueOf(shape.item ?? term(shape.of), [...path, key], pos, scope, type), enumerable: true, writable: true, configurable: true });\n return out;\n }\n case \"record\": {\n const named: Readonly<Record<string, Shape>> = Array.isArray(shape.fields)\n ? Object.fromEntries((shape.fields as readonly string[]).map((name) => [name, term(shape.of)]))\n : (shape.fields as Readonly<Record<string, Shape>>);\n const fieldKeys = new Set<string>([...(shape.required ?? []), ...Object.keys(named).filter(() => rng.chance(0.75))]);\n if (shape.closed !== true && shape.rest === undefined && rng.chance(0.15)) fieldKeys.add(\"extra\");\n const ordered = rng.chance(0.2) ? [...fieldKeys].reverse() : [...fieldKeys];\n const out: Record<string, Json> = {};\n for (const key of ordered) {\n if (rng.chance(malformed / 2) && (shape.required ?? []).includes(key)) continue;\n const fieldShape = Object.hasOwn(named, key) ? named[key] : shape.rest;\n Object.defineProperty(out, key, { value: valueOf(fieldShape, [...path, key], pos, scope, type), enumerable: true, writable: true, configurable: true });\n }\n if (shape.closed === true && rng.chance(malformed)) out[\"stray\"] = 1;\n return out;\n }\n case \"deep\":\n return rng.chance(0.5)\n ? [partAt(pos, scope, [...path, 0], term(shape.of), type), anyJson()]\n : { at: partAt(pos, scope, [...path, \"at\"], term(shape.of), type), data: anyJson() };\n case \"text\":\n return rng.chance(malformed) ? 1 : rng.pick([\"\", \"a\", \"label\"]);\n case \"number\": {\n if (rng.chance(malformed)) return \"1\";\n const low = shape.min ?? -2;\n const value = low + rng.int(5) + (shape.whole === true ? 0 : rng.pick([0, 0.5]));\n return shape.max !== undefined && value > shape.max ? shape.max : value;\n }\n case \"one\":\n return rng.chance(malformed) ? \"other\" : (rng.pick(shape.values) as Json);\n }\n };\n\n /**\n * A malformed document: an unknown kind, or an unknown name under a namespace with a fallback. It can also be a\n * bad shape, a bare value without a type, or a bad reference.\n */\n const brokenAt = (pos: Position): Json => {\n const roll = rng.int(5);\n if (roll === 0 && unknownNames.length > 0 && rng.chance(0.5)) {\n // The fallback kind answers the name, and its evaluator does not know it, for example an unknown operation.\n const type = rng.pick(unknownNames);\n const kind = kindOf(type);\n return envelope(type, kind?.parts === undefined ? dataOf(type) : valueOf(kind.parts, [], pos, scopeOf(kind), type));\n }\n if (roll === 0) return { type: rng.pick<Json>([\"nothing\", [\"no\", \"such\"]]), value: 1 };\n if (roll === 1) return pos.declared === undefined ? rng.pick<Json>([7, \"bare\", [1]]) : { type: \"ref\", value: [\"names\", \"unbound\"] };\n if (roll === 2) {\n const shaped = types.filter((type) => kindOf(type)?.parts !== undefined);\n if (shaped.length > 0) return envelope(rng.pick(shaped), rng.pick<Json>([7, \"x\", null]));\n }\n if (roll === 3) return { type: \"ref\", value: rng.pick<Json>([[\"names\", \"unbound\"], [\"nowhere\"], \"names\"]) };\n return { type: rng.pick(types) as Json, value: anyJson() };\n };\n\n const docAt = (pos: Position, header?: string): Json => {\n size += 1;\n const leaf = pos.depth >= maxDepth || size >= maxSize;\n if (rng.chance(malformed)) return brokenAt(pos);\n if (pos.declared !== undefined && rng.chance(leaf ? 0.7 : 0.3)) {\n const bare = dataOf([pos.declared]);\n // A bare value with the form of an envelope is a document of its own type, and the position must permit that type.\n if (!isEnvelope(bare) || permitted(typePath(bare.type) ?? [], pos.kinds)) return bare;\n }\n let candidates = types.filter((type) => permitted(type, pos.kinds) && (!leaf || leafKind(kindOf(type))));\n if (pos.hint !== undefined && rng.chance(0.6)) {\n const hinted = candidates.filter((type) => pos.hint?.some((hint) => hint.length === type.length && hint.every((key, index) => key === type[index])));\n if (hinted.length > 0) candidates = hinted;\n }\n if (candidates.length === 0) candidates = [...types];\n const type = rng.pick(candidates);\n const kind = kindOf(type);\n if (type.length === 1 && type[0] === \"ref\") return envelope(type, pathFor(pos, kind), header);\n const value = kind === undefined ? dataOf(type) : valueOf(kind.parts, [], pos, scopeOf(kind), type);\n return envelope(type, value, header);\n };\n\n return docAt({ declared: options.declaredType, kinds: undefined, names: options.names ?? [], depth: 0, hint: undefined });\n}\n"],"mappings":";;AAqCA,MAAa,gBAAgB;CAAC;CAAQ;CAAS;CAAQ;AAAK;;;;;;;;AAS5D,SAAgB,SAAS,OAAqC;CAC5D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG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