@mark1russell7/coeval 0.10.0 → 0.11.0

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":["termOf","setOwn","unionOf","valueText","NONE","setOwn","own","entryOf","nodeAt","NO_HOPS","resolveFully","setOwn","makeRootContext","NO_CAPS","drive","ABORTED","finish","NO_CAPS","NO_NAMES","contractOf","NONE","EACH","EACH","setOwn","CLOSURE","setOwn","partsOf","own","examine","drive","CLOSURE","setField","NAMES","contextOf"],"sources":["../src/doc.ts","../src/errors.ts","../src/world.ts","../src/types.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/typing.ts","../src/static.ts","../src/facts.ts","../src/effects.ts","../src/codec.ts","../src/formula.ts","../src/syntax.ts","../src/reference.ts","../src/agree.ts","../src/generate.ts","../src/conform.ts","../src/same.ts","../src/reads.ts","../src/durable.ts","../src/graph.ts","../src/schedule.ts","../src/replay.ts","../src/providers.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 envelope\n * does not change the value 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` and `sameResult` use the same walk, and each adds its rules\n * for other values (D20).\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 return equalWith(a, b, undefined);\n}\n\n/** A rule for two values that are not the same by `Object.is`: `true`, `false`, or `undefined` for the next rule. */\nexport type SameRule = (a: unknown, b: unknown) => boolean | undefined;\n\n/**\n * This function is the one walk of `docEquals`, `sameValue` and `sameResult` (D20). It compares two values by the\n * rules of `docEquals`. A rule of the caller answers first for each pair that is not the same by `Object.is`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param rule - The rule of the caller. Its `undefined` gives the rules of `docEquals`.\n * @returns `true` when the values are equal.\n */\nexport function equalWith(a: unknown, b: unknown, rule: SameRule | undefined): 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 told = rule?.(x, y);\n if (told !== undefined) {\n if (told) continue;\n return false;\n }\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 | \"#REPLAY!\"\n | \"#TYPE!\";\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, Root } from \"./deref.ts\";\nimport type { ValueType } from \"./types.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 *\n * `expect` is the value type that a part must have, as `of` is its type (TYPE.CHECK). A shape with parts gives it to\n * each part that `of` covers. Only a check of types reads it, and it describes the verb `eval`.\n */\nexport type Shape =\n | { readonly shape: \"none\" }\n | { readonly shape: \"term\"; readonly of?: string; readonly address?: boolean; readonly kinds?: readonly (readonly Key[])[]; readonly expect?: ValueType }\n | { readonly shape: \"list\"; readonly of?: string; readonly item?: Shape; readonly distinct?: boolean; readonly expect?: ValueType }\n | { readonly shape: \"map\"; readonly of?: string; readonly item?: Shape; readonly expect?: ValueType }\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 readonly expect?: ValueType;\n }\n | { readonly shape: \"deep\"; readonly of?: string; readonly expect?: ValueType }\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/**\n * A lazy rule of a kind names the parts that an evaluation can skip and still give a value. An example is the\n * branches of `if`. The static facts mark each read under such a part (D24).\n *\n * `in` names the parts, as patterns of their paths in the value. The key `\"*\"` matches each key. A rule without `in`\n * covers each part. With `after: n`, the rule covers only the parts after the first `n` parts that its patterns\n * match. Thus `{ after: 1 }` makes each part lazy except the first part, as in `and`.\n */\nexport interface LazyRule {\n readonly in?: readonly (readonly Key[])[];\n readonly after?: number;\n}\n\n/**\n * The static facts that a kind declares for its code (D24). The contract of a kind holds them, and the hook `facts`\n * of a machine can give them for a name under a fallback kind. The facts describe the code of `eval`, and of `step`\n * for a step document.\n *\n * - `pure`: `true` when the code of the kind causes no effect. Its result depends only on its data, the results\n * of its parts and what its paths reach. A kind that reads the context in another way does not declare it,\n * because the static facts do not see that read.\n * - `volatile`: `true` when its result can change while each read gives the same thing, for example a clock.\n * - `lazy`: the parts that an evaluation can skip and still give a value.\n * - `reads`: the roots that the code of the kind resolves as a whole, with the path of one root. The static facts\n * give a read of each root at each document of the kind (D44). The tree node reads `self` this way.\n */\nexport interface KindFacts {\n readonly pure?: boolean;\n readonly volatile?: boolean;\n readonly lazy?: readonly LazyRule[];\n readonly reads?: readonly Root[];\n}\n\n/**\n * The declaration of one attribute of the nodes of a kind (D42). The last two rungs of the ladder of an attribute\n * read it (TREE.LADDER). Each term is a document. A bare term gets the type `of` of the parts of the kind.\n *\n * - `copy`: `true` gives a node without an answer of the first three rungs the same attribute of its parent\n * (TREE.COPY).\n * - `fold`: the value of a node without an answer of the first four rungs. The fold starts with the term `unit`.\n * Then the term `combine` adds the attribute of each node in the list `children`, one at a time (TREE.FOLD).\n * `combine` sees the names `acc` and `item`.\n * - `default`: the term that gives the value when no rung before it answers and the declaration has no fold.\n */\nexport interface AttributeDeclaration {\n readonly copy?: boolean;\n readonly fold?: { readonly unit: Json; readonly combine: Json };\n readonly default?: Json;\n}\n\n/**\n * The tree contract of a kind (D42): the equations of the attributes of its nodes. Each equation is a document that\n * evaluates with the node as `self` and without capabilities. A bare equation gets the type `of` of the parts of the\n * kind.\n *\n * - `equations`: the attributes of the node itself. An equation sees no names.\n * - `down`: the attributes of each child of the node. `self` is this node. An equation sees the names `child`,\n * `index` and `prev` (TREE.DOWN).\n * - `attributes`: the declarations of the attributes of the node, for the rungs `copy` and `default`.\n */\nexport interface TreeContract {\n readonly equations?: Readonly<Record<string, Json>>;\n readonly down?: Readonly<Record<string, Json>>;\n readonly attributes?: Readonly<Record<string, AttributeDeclaration>>;\n}\n\n/**\n * This function gives the type of a bare equation of a kind (D42). It is the type `of` of the shape of its parts, or\n * else the type `of` of the shape `rest` of a record. The plan, the reference and `check` read it with this one function.\n *\n * @param kind - The kind.\n * @returns The type, or `undefined` when the shape declares none.\n */\nexport function equationType(kind: Kind): string | undefined {\n const parts = kind.parts as { readonly of?: string; readonly rest?: { readonly of?: string } } | undefined;\n return parts?.of ?? parts?.rest?.of;\n}\n\n/**\n * A kind gives the name of an evaluator for each verb, and the contract of its value. The contract serves each verb.\n * For each verb, the kernel splits the parts and narrows their capabilities by it, and `check` reads its scope rules.\n * `side` and `effects` tell what the verb `eval` does (VERB.CONTRACT). `verbEffects` tells the effects of the other\n * verbs (VERB.EFFECTS).\n */\nexport interface Kind extends KindFacts {\n /**\n * The evaluator names, by verb. `eval` evaluates a document, `deref` answers a step on it, and `step` names the\n * walker of a step document. A language adds its own verbs, for example `view` or `format`.\n */\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 verb `eval` of the kind. A kind of the run side causes effects. The default is `derive`. */\n readonly side?: Side;\n /**\n * The effects that the verb `eval` of a document of this kind can cause. It is a list of the kinds of the effects.\n * The text `\"type\"` means that the kind of the effect is the type of the document itself, as for a call. For a\n * procedure entry, the list holds the latent effects of the procedure, and `checkLatent` compares them with its body\n * (CAP.LATENT).\n */\n readonly effects?: \"type\" | readonly string[];\n /**\n * The effects that the other verbs of a document of this kind can cause, by verb, in the form of `effects`\n * (VERB.EFFECTS, D49). An entry `view: []` declares no effect for `view`. A verb without an entry has no\n * declaration, thus `check` does not test its effects. The field `effects` declares `eval`, thus this field has no\n * entry `eval`.\n */\n readonly verbEffects?: VerbEffects;\n /**\n * The value type of the result of the verb `eval`, when it is fixed (TYPE.SYNTH). A check of types gives it to each\n * document of the kind, in the place of the type that the rule of the evaluator synthesizes.\n */\n readonly result?: ValueType;\n /**\n * The equations and the declarations of the attributes of a node of the decorated tree (D42). Only the evaluator\n * `tree.node` reads them, and `check` checks each equation one time (TREE.LADDER).\n */\n readonly tree?: TreeContract;\n /** One sentence that tells what the kind is. */\n readonly summary?: string;\n}\n\n/**\n * The effects that a contract declares for the verbs other than `eval`, by verb (D49). Each entry has the form of the\n * field `effects` of a kind. The type has no entry `eval`, because the field `effects` declares `eval`.\n */\nexport type VerbEffects = Readonly<Record<string, \"type\" | readonly string[]>> & { readonly eval?: never };\n\n/**\n * This function gives the effects that the contract of a kind declares for a verb (VERB.EFFECTS, D49). For `eval`,\n * the field `effects` declares them, and a kind without the field declares no effect. For another verb, the entry of\n * `verbEffects` declares them. `check` and `conforms` read the declarations with this one function.\n *\n * @param kind - The kind.\n * @param verb - The verb.\n * @returns The declaration in the form of `effects`, or `undefined` when the contract does not declare the effects of\n * the verb.\n */\nexport function effectsOfVerb(kind: Kind, verb: string): \"type\" | readonly string[] | undefined {\n if (verb === \"eval\") return kind.effects ?? [];\n const table = kind.verbEffects as Readonly<Record<string, \"type\" | readonly string[]>> | undefined;\n return table !== undefined && Object.hasOwn(table, verb) ? table[verb] : undefined;\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 /**\n * The default evaluator of each verb: the last rung of the ladder (LADDER.DEFAULT). It serves each verb, also\n * `deref` and `step`. Without a default of `deref`, a step goes into the value of a document (VERB.LADDER).\n */\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 Json, type Key, docEquals, isEnvelope, isRecord } from \"./doc.ts\";\n\n/*\n * Value types and value domains (R5 P2, D22). A value type is a set of values that a result can have. It is a JSON\n * term that only a check reads. It is not a kind, and it does not go into an envelope (D2, D6). A text names a base\n * type. The set of base types is open: a language adds its own domains, each with a membership test.\n */\n\n/**\n * A value type: a set of values that a result can have, as a JSON term.\n *\n * - A text names a base type: `unknown`, `never`, a domain of the kernel (`null`, `undefined`, `bool`, `number`,\n * `text`), or a domain of a language.\n * - `list`: a list whose items have the type.\n * - `record`: a plain record with the named fields. `optional` names the fields that can be absent. A `closed`\n * record has no other fields. The other fields of an open record can hold each value.\n * - `fn`: a function with the types of its parameters, and the type of its result (`to`).\n * - `union`: a value of one of the types. An empty union holds no value.\n * - `one`: one of the JSON values of the list.\n *\n * A term that is not in this list reads as `unknown` (TYPE.UNKNOWN). Thus a later version can add a term.\n */\nexport type ValueType =\n | string\n | { readonly list: ValueType }\n | { readonly record: Readonly<Record<string, ValueType>>; readonly optional?: readonly string[]; readonly closed?: boolean }\n | { readonly fn: readonly ValueType[]; readonly to: ValueType }\n | { readonly union: readonly ValueType[] }\n | { readonly one: readonly Json[] };\n\n/**\n * A value domain: a base type of a language, with its membership test. A machine holds its domains by their names\n * (`Machine.domains`). A value is a member of a domain only when the test of the domain and the test of each parent\n * accept it (TYPE.MEMBER).\n *\n * A path does not follow a member of a domain as a reference (DEREF.COLLAPSE). Thus the test `is` must refuse each\n * reference document.\n */\nexport interface Domain {\n /**\n * This function tells if a value is a member of the domain. It must be pure. A test that throws gives `false`.\n *\n * @param value - The value.\n * @returns `true` for a member.\n */\n readonly is: (value: unknown) => boolean;\n /** The names of the parents: the base types that hold each member of the domain. A base type fits each parent. */\n readonly under?: readonly string[];\n /** One sentence that tells what the domain holds. */\n readonly summary?: string;\n /**\n * The value type of each step into a member, by its key, for example the field `x` of a point (TYPE.STEPS). The\n * check of a path reads the steps of the domain first, then the steps of each parent. The language keeps them true:\n * a step with the key into a member reaches a member of the type. A key without a type gives `unknown`.\n */\n readonly steps?: Readonly<Record<string, ValueType>>;\n /**\n * The codec of the members: it writes a member as JSON and reads it again (D40). A document holds a member as the\n * standard extension `ext.domain`. A domain without a codec has no such document.\n */\n readonly codec?: DomainCodec;\n}\n\n/**\n * The codec of a domain: it writes a member of the domain as JSON, and it reads the JSON again (D40). Both functions\n * must be pure. `decode(encode(v))` must equal `v` by `sameValue` (EXT.ROUNDTRIP). The codec must give one JSON\n * value for each member, thus the same value has the same document in each language (D12).\n */\nexport interface DomainCodec {\n /**\n * This function writes a member of the domain as JSON.\n *\n * @param value - A member of the domain.\n * @returns The JSON of the member.\n */\n readonly encode: (value: unknown) => Json;\n /**\n * This function reads the JSON of a member again. It throws for JSON that does not write a member.\n *\n * @param data - The JSON that `encode` gave.\n * @returns The member.\n */\n readonly decode: (data: Json) => unknown;\n}\n\n/** A problem of a value type: the keys from the root of the term to the problem, and the reason. */\nexport interface TypeIssue {\n readonly at: readonly Key[];\n readonly reason: string;\n}\n\n/**\n * The domains of the kernel. `unknown` and `never` are not domains: they are the top and the bottom of the types.\n * A machine that does not name one of these domains gets it from this table.\n */\nexport const STD_DOMAINS: Readonly<Record<string, Domain>> = {\n null: { is: (value) => value === null, summary: \"The value null.\" },\n // JSON has no undefined, thus a document holds it as ext.undefined (D48). The domain has no codec: the codec of values writes undefined first.\n undefined: { is: (value) => value === undefined, summary: \"The value undefined. A document holds it as the extension ext.undefined.\" },\n bool: { is: (value) => typeof value === \"boolean\", summary: \"A truth value: true or false.\" },\n number: { is: (value) => typeof value === \"number\", summary: \"A number of the host, also NaN, an infinity and -0.\" },\n text: { is: (value) => typeof value === \"string\", summary: \"A text.\" },\n};\n\n/** The deepest term that a value type can have. A deeper term reads as `unknown`, thus a check stays total. */\nconst MAX_TYPE_DEPTH = 256;\n\n/** The keys that each term permits beside its own key. */\nconst TERM_KEYS: Readonly<Record<string, readonly string[]>> = {\n list: [\"list\"],\n record: [\"record\", \"optional\", \"closed\"],\n fn: [\"fn\", \"to\"],\n union: [\"union\"],\n one: [\"one\"],\n};\n\nconst TERMS = /* @__PURE__ */ Object.keys(TERM_KEYS);\n\n/** The form of a value type that the rules read. `top` is `unknown`, and also each term that is not a value type. */\ntype Form =\n | { readonly t: \"top\" }\n | { readonly t: \"bottom\" }\n | { readonly t: \"base\"; readonly name: string }\n | { readonly t: \"list\"; readonly item: ValueType }\n | { readonly t: \"record\"; readonly fields: Readonly<Record<string, ValueType>>; readonly optional: ReadonlySet<string>; readonly closed: boolean }\n | { readonly t: \"fn\"; readonly params: readonly ValueType[]; readonly to: ValueType }\n | { readonly t: \"union\"; readonly members: readonly ValueType[] }\n | { readonly t: \"one\"; readonly values: readonly Json[] };\n\nconst TOP: Form = { t: \"top\" };\nconst BOTTOM: Form = { t: \"bottom\" };\n\n/** This function gives the domain of a base type: the domain of the machine, or else the domain of the kernel. */\nexport function domainOf(name: string, domains: Readonly<Record<string, Domain>> | undefined): Domain | undefined {\n // The top and the bottom are not domains. A table entry with their names has no effect.\n if (name === \"unknown\" || name === \"never\") return undefined;\n const found = domains !== undefined && Object.hasOwn(domains, name) ? domains[name] : Object.hasOwn(STD_DOMAINS, name) ? STD_DOMAINS[name] : undefined;\n // A domain can be an instance of a class, thus the test reads only its function `is`.\n return typeof found === \"object\" && found !== null && typeof found.is === \"function\" ? found : undefined;\n}\n\n/** This function gives the term key of a record, when the record has exactly one term key and no other key. */\nfunction termOf(term: Readonly<Record<string, unknown>>): string | undefined {\n const keys = Object.keys(term);\n const own = keys.filter((key) => TERMS.includes(key));\n if (own.length !== 1) return undefined;\n const allowed = TERM_KEYS[own[0] as string] as readonly string[];\n return keys.every((key) => allowed.includes(key)) ? own[0] : undefined;\n}\n\n/** This function reads one level of a value type. A part of a term reads only when a rule asks for it. */\nfunction formOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): Form {\n if (typeof type === \"string\") {\n if (type === \"unknown\") return TOP;\n if (type === \"never\") return BOTTOM;\n return domainOf(type, domains) === undefined ? TOP : { t: \"base\", name: type };\n }\n if (!isRecord(type)) return TOP;\n const term = termOf(type);\n if (term === \"list\") return { t: \"list\", item: type[\"list\"] as ValueType };\n if (term === \"fn\") {\n const params = type[\"fn\"];\n return Array.isArray(params) && Object.hasOwn(type, \"to\") ? { t: \"fn\", params: params as readonly ValueType[], to: type[\"to\"] as ValueType } : TOP;\n }\n if (term === \"union\") return Array.isArray(type[\"union\"]) ? { t: \"union\", members: type[\"union\"] as readonly ValueType[] } : TOP;\n if (term === \"one\") return Array.isArray(type[\"one\"]) ? { t: \"one\", values: type[\"one\"] as readonly Json[] } : TOP;\n if (term !== \"record\") return TOP;\n const fields = type[\"record\"];\n const optional = type[\"optional\"] ?? [];\n const closed = type[\"closed\"] ?? false;\n if (!isRecord(fields) || !Array.isArray(optional) || typeof closed !== \"boolean\") return TOP;\n const names = (optional as readonly unknown[]).filter((name): name is string => typeof name === \"string\" && Object.hasOwn(fields, name));\n return { t: \"record\", fields: fields as Readonly<Record<string, ValueType>>, optional: new Set(names), closed };\n}\n\n/** This function gives each base type that holds the members of a base type: the type itself and each parent, through each level. */\nfunction lineOf(name: string, domains: Readonly<Record<string, Domain>> | undefined): ReadonlySet<string> {\n const seen = new Set<string>([name]);\n const queue = [name];\n while (queue.length > 0) {\n const under = domainOf(queue.pop() as string, domains)?.under;\n if (!Array.isArray(under)) continue;\n for (const parent of under) {\n if (typeof parent !== \"string\" || seen.has(parent)) continue;\n seen.add(parent);\n queue.push(parent);\n }\n }\n return seen;\n}\n\n/** This function tells if a value is a member of a base type: each test of the type and of its parents accepts it. */\nfunction inDomain(value: unknown, name: string, domains: Readonly<Record<string, Domain>> | undefined): boolean {\n for (const each of lineOf(name, domains)) {\n if (each === \"never\") return false;\n const domain = domainOf(each, domains);\n if (domain === undefined) continue;\n try {\n if (domain.is(value) !== true) return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\n/** This function is the membership test at one depth of a type. Below the deepest term, each value is a member. */\nfunction memberAt(value: unknown, type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n const next = depth + 1;\n switch (form.t) {\n case \"top\":\n return true;\n case \"bottom\":\n return false;\n case \"base\":\n return inDomain(value, form.name, domains);\n case \"list\": {\n if (!Array.isArray(value)) return false;\n // A hole of a list holds undefined, thus a loop by index tests it too.\n for (let index = 0; index < value.length; index += 1) if (!memberAt(value[index], form.item, domains, next)) return false;\n return true;\n }\n case \"record\": {\n if (!isRecord(value)) return false;\n for (const key of Object.keys(form.fields)) {\n if (Object.hasOwn(value, key)) {\n if (!memberAt(value[key], form.fields[key], domains, next)) return false;\n } else if (!form.optional.has(key)) {\n return false;\n }\n }\n return !form.closed || Object.keys(value).every((key) => Object.hasOwn(form.fields, key));\n }\n case \"fn\":\n return typeof value === \"function\";\n case \"union\":\n return form.members.some((item) => memberAt(value, item, domains, next));\n case \"one\":\n return form.values.some((item) => docEquals(item, value));\n }\n}\n\n/**\n * This function tells if a value is a member of a value type (TYPE.MEMBER). It is the membership test that a cast\n * at run time uses.\n *\n * - Each value is a member of `unknown`, and no value is a member of `never`.\n * - A value is a member of a domain when the test `is` of the domain and of each parent accepts it.\n * - A list, a record, a union and `one` test their values at each depth.\n * - A function type tests only that the value is a function. Its parameters need a test at each call.\n *\n * The function does not throw. A term that is not a value type, or a base type without a domain, holds each value.\n *\n * @param value - The value.\n * @param type - The value type.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns `true` when the value is a member of the type.\n */\nexport function member(value: unknown, type: ValueType, domains?: Readonly<Record<string, Domain>>): boolean {\n return memberAt(value, type, domains, 0);\n}\n\n/** This function tells if the record type `a` fits the record type `b`: width, closed records and optional fields. */\nfunction recordFits(\n a: Extract<Form, { readonly t: \"record\" }>,\n b: Extract<Form, { readonly t: \"record\" }>,\n domains: Readonly<Record<string, Domain>> | undefined,\n depth: number,\n gradual: boolean,\n): boolean {\n if (b.closed && (!a.closed || Object.keys(a.fields).some((key) => !Object.hasOwn(b.fields, key)))) return false;\n for (const key of Object.keys(b.fields)) {\n const want = b.fields[key];\n const needed = !b.optional.has(key);\n if (Object.hasOwn(a.fields, key)) {\n if (needed && a.optional.has(key)) return false;\n if (!fitsAt(a.fields[key], want, domains, depth, gradual)) return false;\n } else if (needed) {\n return false;\n } else if (!a.closed && formOf(want, domains).t !== \"top\") {\n // The other fields of an open record can hold each value, thus only `unknown` accepts such a field.\n return false;\n }\n }\n return true;\n}\n\n/**\n * This function is the relation `fits` at one depth of two types. The order of its tests is the order of the rules of\n * `fits`. Without `gradual`, `unknown` is only the top: it fits only `unknown`. The join uses this strict form.\n */\nfunction fitsAt(found: unknown, expected: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number, gradual = true): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const a = formOf(found, domains);\n const b = formOf(expected, domains);\n const next = depth + 1;\n if (b.t === \"top\" || a.t === \"bottom\") return true;\n if (a.t === \"top\") return gradual;\n if (a.t === \"union\") return a.members.every((item) => fitsAt(item, expected, domains, next, gradual));\n if (a.t === \"one\") return a.values.every((item) => memberAt(item, expected, domains, next));\n if (b.t === \"bottom\") return false;\n if (b.t === \"union\") return b.members.some((item) => fitsAt(found, item, domains, next, gradual));\n if (a.t === \"base\") return b.t === \"base\" && lineOf(a.name, domains).has(b.name);\n if (a.t === \"list\") return b.t === \"list\" && fitsAt(a.item, b.item, domains, next, gradual);\n if (a.t === \"record\") return b.t === \"record\" && recordFits(a, b, domains, next, gradual);\n if (b.t !== \"fn\" || a.params.length > b.params.length) return false;\n // A function fits when it accepts each argument of the expected type, and when its result fits.\n return a.params.every((param, index) => fitsAt(b.params[index], param, domains, next, gradual)) && fitsAt(a.to, b.to, domains, next, gradual);\n}\n\n/**\n * This function tells if each value of the type `found` can be where the type `expected` must be (TYPE.FITS). Each\n * check of a type uses it.\n *\n * - `unknown` fits each type, and each type fits `unknown` (TYPE.UNKNOWN). This is the gradual top.\n * - `never` fits each type. Only `never`, an empty union and an empty `one` fit `never`.\n * - A union fits when each of its types fits. A type fits a union when it fits one of its types.\n * - `one` fits when each of its values is a member of `expected`.\n * - A base type fits itself and each parent of its domain, through each level (TYPE.DOMAIN).\n * - A list fits a list when its items fit.\n * - A record fits a record with fewer fields. A field that `expected` needs is not optional in `found`, and each field\n * fits. Only a closed record fits a closed record. An open record without an optional field fits only when that\n * field is `unknown`.\n * - A function fits when it has the same or fewer parameters, each expected parameter fits its parameter, and its\n * result fits.\n *\n * The relation is sound: a member of `found` is a member of `expected` when no `unknown` is in the types. It is not\n * complete. For example, `bool` does not fit `{ \"one\": [true, false] }`. The function does not throw.\n *\n * @param found - The type that a part has.\n * @param expected - The type that the position needs.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns `true` when `found` fits `expected`.\n */\nexport function fits(found: ValueType, expected: ValueType, domains?: Readonly<Record<string, Domain>>): boolean {\n return fitsAt(found, expected, domains, 0);\n}\n\n/** This function sets an own field of a new record. 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\n/** This function is the join of two record types. A field that only one record has is optional, or absent from an open record. */\nfunction joinRecords(\n a: Extract<Form, { readonly t: \"record\" }>,\n b: Extract<Form, { readonly t: \"record\" }>,\n domains: Readonly<Record<string, Domain>> | undefined,\n depth: number,\n): ValueType {\n const closed = a.closed && b.closed;\n const fields: Record<string, ValueType> = {};\n const optional: string[] = [];\n const keys = [...Object.keys(a.fields), ...Object.keys(b.fields).filter((key) => !Object.hasOwn(a.fields, key))];\n for (const key of keys) {\n const inA = Object.hasOwn(a.fields, key);\n const inB = Object.hasOwn(b.fields, key);\n if (inA && inB) {\n setOwn(fields, key, joinAt(a.fields[key], b.fields[key], domains, depth));\n if (a.optional.has(key) || b.optional.has(key)) optional.push(key);\n } else if (closed) {\n // The other record is closed, thus the field can be absent.\n setOwn(fields, key, inA ? a.fields[key] : b.fields[key]);\n optional.push(key);\n }\n // In an open record, a field of one side can hold each value on the other side. The open join leaves it out.\n }\n return { record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) };\n}\n\n/**\n * This function makes a union of types. It puts the members of each inner union and each value of `one` together. It\n * leaves out each member that fits another member, by the strict form of `fits`.\n */\nfunction unionOf(types: readonly unknown[], domains: Readonly<Record<string, Domain>> | undefined, depth: number): ValueType {\n const members: unknown[] = [];\n const values: Json[] = [];\n let valuesAt = -1;\n const add = (type: unknown, level: number): void => {\n const form = formOf(type, domains);\n if (form.t === \"bottom\") return;\n if (form.t === \"union\" && level <= MAX_TYPE_DEPTH) {\n for (const item of form.members) add(item, level + 1);\n return;\n }\n if (form.t === \"one\") {\n if (valuesAt === -1) {\n valuesAt = members.length;\n members.push(undefined);\n }\n for (const value of form.values) if (!values.some((item) => docEquals(item, value))) values.push(value);\n return;\n }\n members.push(type);\n };\n for (const type of types) add(type, depth);\n if (valuesAt !== -1) members[valuesAt] = { one: values };\n const kept: unknown[] = [];\n for (const member of members) {\n if (kept.some((item) => fitsAt(member, item, domains, depth, false))) continue;\n for (let index = kept.length - 1; index >= 0; index -= 1) if (fitsAt(kept[index], member, domains, depth, false)) kept.splice(index, 1);\n kept.push(member);\n }\n if (kept.length === 0) return \"never\";\n return kept.length === 1 ? (kept[0] as ValueType) : { union: kept as ValueType[] };\n}\n\n/** This function is the join at one depth of two types. */\nfunction joinAt(a: unknown, b: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number): ValueType {\n if (depth > MAX_TYPE_DEPTH) return \"unknown\";\n const fa = formOf(a, domains);\n const fb = formOf(b, domains);\n if (fa.t === \"top\" || fb.t === \"top\") return \"unknown\";\n if (fa.t === \"bottom\") return b as ValueType;\n if (fb.t === \"bottom\") return a as ValueType;\n // The strict form keeps the join sound: a type with `unknown` inside is not under a type without it.\n if (fitsAt(a, b, domains, depth, false)) return b as ValueType;\n if (fitsAt(b, a, domains, depth, false)) return a as ValueType;\n const next = depth + 1;\n if (fa.t === \"list\" && fb.t === \"list\") return { list: joinAt(fa.item, fb.item, domains, next) };\n if (fa.t === \"record\" && fb.t === \"record\") return joinRecords(fa, fb, domains, next);\n return unionOf([a, b], domains, next);\n}\n\n/**\n * This function gives the join of two value types (TYPE.JOIN): a type that holds each member of both types. The check\n * of a type uses it for the branches of an `if` and for the items of a list.\n *\n * - `unknown` with each type gives `unknown`, and `never` with a type gives that type.\n * - When one type fits the other by the strict form of `fits`, the join is the wider type. The strict form reads\n * `unknown` only as the top.\n * - Two lists give a list of the join of their items.\n * - Two records give a record of the join of their common fields. A field of one closed record is optional in the\n * join of two closed records. The join of an open record leaves out the fields that only one record has.\n * - Each other pair gives a union. The union puts the values of `one` together and leaves out each member that fits\n * another member.\n *\n * The join is sound: a member of `a` or of `b` is a member of the join. It is not always the least such type. The\n * function does not throw.\n *\n * @param a - The first type.\n * @param b - The second type.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns The join.\n */\nexport function join(a: ValueType, b: ValueType, domains?: Readonly<Record<string, Domain>>): ValueType {\n return joinAt(a, b, domains, 0);\n}\n\n/** The most values of `one` that the text of a type shows. */\nconst MAX_TEXT_VALUES = 8;\n/** The most characters of one JSON value in the text of a type. */\nconst MAX_TEXT_VALUE = 40;\n\n/** This function gives a short text of a JSON value for the text of a type. */\nfunction valueText(value: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = String(value);\n }\n return text.length > MAX_TEXT_VALUE ? `${text.slice(0, MAX_TEXT_VALUE - 1)}…` : text;\n}\n\n/** This function gives the text of a type at one depth. `wrap` puts a union or a function type in brackets. */\nfunction textAt(type: unknown, depth: number, wrap: boolean): string {\n if (depth > MAX_TYPE_DEPTH) return \"unknown\";\n if (typeof type === \"string\") return type;\n const term = isRecord(type) ? termOf(type) : undefined;\n if (!isRecord(type) || term === undefined) return \"unknown\";\n const next = depth + 1;\n const group = (items: readonly string[]): string => (items.length === 0 ? \"never\" : items.length > 1 && wrap ? `(${items.join(\" | \")})` : items.join(\" | \"));\n if (term === \"list\") return `list<${textAt(type[\"list\"], next, false)}>`;\n if (term === \"union\") return Array.isArray(type[\"union\"]) ? group((type[\"union\"] as readonly unknown[]).map((item) => textAt(item, next, true))) : \"unknown\";\n if (term === \"one\") {\n if (!Array.isArray(type[\"one\"])) return \"unknown\";\n const values = type[\"one\"] as readonly unknown[];\n const shown = values.slice(0, MAX_TEXT_VALUES).map(valueText);\n return group(values.length > MAX_TEXT_VALUES ? [...shown, `… ${values.length - MAX_TEXT_VALUES} more`] : shown);\n }\n if (term === \"fn\") {\n if (!Array.isArray(type[\"fn\"])) return \"unknown\";\n const text = `(${(type[\"fn\"] as readonly unknown[]).map((item) => textAt(item, next, false)).join(\", \")}) => ${textAt(type[\"to\"], next, true)}`;\n return wrap ? `(${text})` : text;\n }\n const fields = type[\"record\"];\n if (!isRecord(fields)) return \"unknown\";\n const optional = Array.isArray(type[\"optional\"]) ? (type[\"optional\"] as readonly unknown[]) : [];\n const items = Object.keys(fields).map((key) => {\n const name = /^[A-Za-z_$][\\w$]*$/.test(key) ? key : JSON.stringify(key);\n return `${name}${optional.includes(key) ? \"?\" : \"\"}: ${textAt(fields[key], next, false)}`;\n });\n if (type[\"closed\"] !== true) items.push(\"...\");\n return `{${items.join(\", \")}}`;\n}\n\n/**\n * This function gives the text of a value type (TYPE.TEXT), for the reason of an issue. The function does not throw.\n *\n * - A base type gives its name.\n * - `list<T>` is a list, `{a: T, b?: U}` is a closed record, and `{a: T, ...}` is an open record.\n * - `(T, U) => V` is a function, and `T | U` is a union.\n * - `one` gives its values as JSON, and an empty union gives `never`.\n * - A term that is not a value type gives `unknown`.\n *\n * The text shows at most 8 values of `one`, and it cuts a long value.\n *\n * @param type - The value type.\n * @returns The text.\n */\nexport function typeText(type: ValueType): string {\n return textAt(type, 0, false);\n}\n\n/*\n * The functions below read one level of a type for the type rules of the kit. The package does not export them.\n */\n\n/** This function tells if a type reads as `unknown`. Such a type is the top, a term that is not a value type, or a base type without a domain. */\nexport function isUnknown(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): boolean {\n return formOf(type, domains).t === \"top\";\n}\n\n/** This function gives the type of the items of a list type, or `undefined` for each other type. */\nexport function itemOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): ValueType | undefined {\n const form = formOf(type, domains);\n return form.t === \"list\" ? form.item : undefined;\n}\n\n/** This function gives the type of a field of a record type, or `undefined` when the type is not a record with the field. */\nexport function fieldOf(type: unknown, key: string, domains: Readonly<Record<string, Domain>> | undefined): ValueType | undefined {\n const form = formOf(type, domains);\n return form.t === \"record\" && Object.hasOwn(form.fields, key) ? form.fields[key] : undefined;\n}\n\n/** This function gives the parameters and the result of a function type, or `undefined` for each other type. */\nexport function fnOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): { readonly params: readonly ValueType[]; readonly to: ValueType } | undefined {\n const form = formOf(type, domains);\n return form.t === \"fn\" ? { params: form.params, to: form.to } : undefined;\n}\n\n/** This function tells if each value of a type can be a function. Such a type is the top, the bottom, a function type, or a union of them. */\nexport function callable(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n if (form.t === \"top\" || form.t === \"bottom\" || form.t === \"fn\") return true;\n if (form.t === \"union\") return form.members.every((item) => callable(item, domains, depth + 1));\n return form.t === \"one\" && form.values.length === 0;\n}\n\n/** This function tells if a type has no `unknown` at any depth. Then `fits` decides it without the gradual rule. */\nexport function isPrecise(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return false;\n const form = formOf(type, domains);\n const next = depth + 1;\n switch (form.t) {\n case \"top\":\n return false;\n case \"list\":\n return isPrecise(form.item, domains, next);\n case \"record\":\n return Object.keys(form.fields).every((key) => isPrecise(form.fields[key], domains, next));\n case \"fn\":\n return form.params.every((item) => isPrecise(item, domains, next)) && isPrecise(form.to, domains, next);\n case \"union\":\n return form.members.every((item) => isPrecise(item, domains, next));\n default:\n return true;\n }\n}\n\n/** The keys of the header of an envelope. A record with only these keys can have the form of an envelope. */\nexport const HEADER_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set([\"type\", \"value\", \"name\", \"own\"]);\n\n/**\n * This function tells if a member of a type can have the form of an envelope. A path asks the ladder for each step\n * into an envelope, and it follows a reference document (DEREF.COLLAPSE). Thus the type of such a member does not\n * tell what a path reaches.\n *\n * The test is conservative. A record that needs a key outside the header is not an\n * envelope. A closed record without the fields `type` and `value` is not an envelope either. A domain refuses each\n * reference document (`Domain`), and its steps tell what a step reaches.\n */\nexport function holdsEnvelope(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n switch (form.t) {\n case \"top\":\n return true;\n case \"union\":\n return form.members.some((item) => holdsEnvelope(item, domains, depth + 1));\n case \"one\":\n return form.values.some((value) => isEnvelope(value));\n case \"record\":\n if (Object.keys(form.fields).some((key) => !form.optional.has(key) && !HEADER_KEYS.has(key))) return false;\n return !form.closed || (Object.hasOwn(form.fields, \"type\") && Object.hasOwn(form.fields, \"value\"));\n default:\n return false;\n }\n}\n\n/**\n * What one step reaches from a member of a type: its type, or the fields of the type when no member has the step.\n * The field list is empty when the type is not a record.\n */\nexport type StepType = { readonly type: ValueType } | { readonly missing: readonly string[] };\n\n/** This function gives the index of a key into a list, as a step into the value finds it, or -1. */\nfunction indexOf(key: Key): number {\n if (typeof key === \"number\") return Number.isInteger(key) && key >= 0 ? key : -1;\n return /^\\d+$/.test(key) ? Number(key) : -1;\n}\n\n/** This function adds the keys of a list to another list, without the keys that it has. */\nfunction addKeys(into: string[], keys: readonly string[]): void {\n for (const key of keys) if (!into.includes(key)) into.push(key);\n}\n\n/** This function gives the step of a key into one JSON value of `one`: the value that it reaches, or the fields of the value. */\nfunction valueStep(value: unknown, key: Key): { readonly found: unknown } | { readonly fields: readonly string[] } {\n if (Array.isArray(value)) {\n if (key === \"length\") return { found: value.length };\n const index = indexOf(key);\n return index >= 0 && index < value.length ? { found: value[index] } : { fields: [] };\n }\n if (isRecord(value)) return Object.hasOwn(value, String(key)) ? { found: value[String(key)] } : { fields: Object.keys(value) };\n return { fields: [] };\n}\n\n/**\n * This function gives the type that a step with a key reaches from a member of a type (TYPE.PATH). The caller tests\n * first that no member can be an envelope (`holdsEnvelope`).\n *\n * - A record gives the type of its field. A closed record without the field has no such step. An open record gives\n * `unknown`.\n * - A list gives the type of its items for an index, and `number` for `length`.\n * - A base type reads the steps of its domain, then of each parent (`Domain.steps`).\n * - A union joins the steps of its types. `one` gives the values that the step reaches.\n * - Each other step gives `unknown`, and `never` gives `never`.\n *\n * @param examine - The function that examines a type of the steps of a domain, one time in a check.\n */\nexport function stepType(\n type: unknown,\n key: Key,\n domains: Readonly<Record<string, Domain>> | undefined,\n examine?: (type: ValueType, what: string) => ValueType,\n depth = 0,\n): StepType {\n if (depth > MAX_TYPE_DEPTH) return { type: \"unknown\" };\n const form = formOf(type, domains);\n const name = String(key);\n switch (form.t) {\n case \"bottom\":\n return { type: \"never\" };\n case \"base\":\n for (const each of lineOf(form.name, domains)) {\n const steps = domainOf(each, domains)?.steps;\n if (typeof steps !== \"object\" || steps === null || !Object.hasOwn(steps, name)) continue;\n const found = steps[name] as ValueType;\n return { type: examine === undefined ? found : examine(found, `type of the step ${name} of the domain ${each}`) };\n }\n return { type: \"unknown\" };\n case \"list\":\n if (key === \"length\") return { type: \"number\" };\n return { type: indexOf(key) >= 0 ? form.item : \"unknown\" };\n case \"record\":\n if (Object.hasOwn(form.fields, name)) return { type: form.fields[name] as ValueType };\n return form.closed ? { missing: Object.keys(form.fields) } : { type: \"unknown\" };\n case \"union\": {\n let joined: ValueType | undefined;\n const fields: string[] = [];\n for (const item of form.members) {\n const step = stepType(item, key, domains, examine, depth + 1);\n if (\"missing\" in step) addKeys(fields, step.missing);\n else joined = joined === undefined ? step.type : join(joined, step.type, domains);\n }\n // A member without the step makes the path fail, thus only the other members give a type.\n return joined === undefined ? { missing: fields } : { type: joined };\n }\n case \"one\": {\n const found: Json[] = [];\n const fields: string[] = [];\n for (const value of form.values) {\n const step = valueStep(value, key);\n if (\"fields\" in step) addKeys(fields, step.fields);\n else if (!found.some((item) => docEquals(item, step.found))) found.push(step.found as Json);\n }\n return found.length === 0 ? { missing: fields } : { type: { one: found } };\n }\n default:\n return { type: \"unknown\" };\n }\n}\n\n/** A term that `typeIssues` reads later: the term, its keys from the root and its depth. */\ninterface Pending {\n readonly type: unknown;\n readonly at: readonly Key[];\n readonly depth: number;\n}\n\n/**\n * This function lists the problems of a value type (TYPE.ISSUES). A problem is a term that is not a value type, a\n * base type without a domain, or a term that is too deep. `fits` and `member` read each such term as `unknown`.\n * Thus a check that reads a type from a contract can report it first.\n *\n * @param type - The value type, as JSON.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns The problems. A term comes before its parts, and the parts keep their order.\n */\nexport function typeIssues(type: unknown, domains?: Readonly<Record<string, Domain>>): readonly TypeIssue[] {\n const issues: TypeIssue[] = [];\n const stack: Pending[] = [{ type, at: [], depth: 0 }];\n while (stack.length > 0) {\n const { type: here, at, depth } = stack.pop() as Pending;\n const issue = (reason: string, where: readonly Key[] = at): void => {\n issues.push({ at: where, reason });\n };\n if (depth > MAX_TYPE_DEPTH) {\n issue(`The value type is deeper than ${MAX_TYPE_DEPTH} terms.`);\n continue;\n }\n if (typeof here === \"string\") {\n if (here !== \"unknown\" && here !== \"never\" && domainOf(here, domains) === undefined) issue(`The machine has no domain ${here}.`);\n continue;\n }\n const term = isRecord(here) ? termOf(here) : undefined;\n if (!isRecord(here) || term === undefined) {\n issue(`A value type is a text, or a record with one of the keys ${TERMS.join(\", \")} and the keys that go with it.`);\n continue;\n }\n // The parts go on the stack in the reverse order, thus the issues come in the order of the term.\n const parts: Pending[] = [];\n const part = (each: unknown, where: readonly Key[]): void => {\n parts.push({ type: each, at: where, depth: depth + 1 });\n };\n const list = (key: string, what: string): readonly unknown[] => {\n const items = here[key];\n if (Array.isArray(items)) return items;\n issue(`The value of ${key} is a list of ${what}.`, [...at, key]);\n return [];\n };\n if (term === \"list\") part(here[\"list\"], [...at, \"list\"]);\n if (term === \"union\") list(\"union\", \"value types\").forEach((each, index) => part(each, [...at, \"union\", index]));\n if (term === \"one\") list(\"one\", \"JSON values\");\n if (term === \"fn\") {\n list(\"fn\", \"value types\").forEach((each, index) => part(each, [...at, \"fn\", index]));\n if (Object.hasOwn(here, \"to\")) part(here[\"to\"], [...at, \"to\"]);\n else issue(\"A function type has the key to: the type of its result.\");\n }\n if (term === \"record\") {\n const fields = here[\"record\"];\n if (isRecord(fields)) for (const key of Object.keys(fields)) part(fields[key], [...at, \"record\", key]);\n else issue(\"The value of record is a record of value types.\", [...at, \"record\"]);\n if (Object.hasOwn(here, \"optional\")) {\n list(\"optional\", \"field names\").forEach((name, index) => {\n if (typeof name !== \"string\" || !isRecord(fields) || !Object.hasOwn(fields, name)) issue(`The optional field ${String(name)} is not a field of the record.`, [...at, \"optional\", index]);\n });\n }\n if (Object.hasOwn(here, \"closed\") && typeof here[\"closed\"] !== \"boolean\") issue(\"The value of closed is true or false.\", [...at, \"closed\"]);\n }\n for (let index = parts.length - 1; index >= 0; index -= 1) stack.push(parts[index] as Pending);\n }\n return issues;\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 Domain, type ValueType, STD_DOMAINS } from \"./types.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\"]>;\ntype Facts = NonNullable<Machine[\"facts\"]>;\n\nconst NONE: ReadonlySet<string> = /* @__PURE__ */ 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/**\n * Two domains are the same when they are one object. They are also the same when they have the same test `is`,\n * parents, summary and steps. Thus two languages that give one test under one name give one domain.\n */\nfunction sameDomain(a: Domain, b: Domain): boolean {\n return a === b || (a.is === b.is && same(a.under ?? [], b.under ?? []) && a.summary === b.summary && same(a.steps ?? {}, b.steps ?? {}));\n}\n\n/** What `extendDomain` adds to a domain: more parents, and the types of more steps. */\nexport interface DomainExtension {\n /** The names of the parents to add. A member of the domain then also passes the test of each new parent. */\n readonly under?: readonly string[];\n /** The types of the steps to add. A step with the key of an earlier step replaces its type. */\n readonly steps?: Readonly<Record<string, ValueType>>;\n}\n\n/**\n * This function makes a part of a merge that adds parents or steps to a domain of an earlier part (TYPE.PARENTS). An\n * example is a domain of another language. The part reads the domain from the merge before it (`prev`). It gives a\n * copy with the same test and summary, and it names `[\"domains\", name]` in `replaces` (D17). A domain of the kernel\n * that the earlier parts do not name comes from `STD_DOMAINS`.\n *\n * A new parent adds its test to the domain (TYPE.MEMBER). Thus `fits` stays sound, but a value that fails the test of\n * the parent is no longer a member. The language that adds the parent keeps the signatures of the other language\n * true. A name without a domain gives an empty part, and `typeIssues` reports each use of that name.\n *\n * @param name - The name of the domain.\n * @param more - The parents and the steps to add.\n * @returns The part, as a function of the merge before it.\n */\nexport function extendDomain(name: string, more: DomainExtension): (prev: Machine) => MachinePart {\n return (prev) => {\n const found = own(prev.domains, name) ?? own(STD_DOMAINS, name);\n if (typeof found !== \"object\" || found === null || typeof found.is !== \"function\") return {};\n // A domain can be an instance of a class, thus the copy reads each field by its name.\n const under = [...(found.under ?? [])];\n for (const parent of more.under ?? []) if (parent !== name && !under.includes(parent)) under.push(parent);\n const steps = { ...found.steps, ...more.steps };\n const domain: Domain = {\n is: found.is,\n ...(under.length === 0 ? {} : { under }),\n ...(found.summary === undefined ? {} : { summary: found.summary }),\n ...(Object.keys(steps).length === 0 ? {} : { steps }),\n };\n const domains: Record<string, Domain> = {};\n setOwn(domains, name, domain);\n return { domains, replaces: [[\"domains\", name]] };\n };\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 = /* @__PURE__ */ new Set([\"world\", \"evaluators\", \"runners\", \"derefs\", \"walkers\", \"domains\", \"known\", \"facts\", \"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 domains?: Record<string, Domain>;\n readonly hooks: { readonly part: number; readonly known: Known }[];\n readonly factHooks: { readonly part: number; readonly facts: Facts }[];\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\n/**\n * This function composes the hooks `facts` in the order of their parts. The first answer that is not `undefined`\n * wins. A hook does not answer for a name whose code a later part replaces (D24).\n */\nfunction composeFacts(hooks: readonly { readonly part: number; readonly facts: Facts }[], replaced: ReadonlyMap<string, number>): Facts | undefined {\n const first = hooks[0];\n if (first === undefined) return undefined;\n if (hooks.length === 1 && replaced.size === 0) return first.facts;\n const list = [...hooks];\n const last = new Map(replaced);\n return (path, code) => {\n const after = last.get(code);\n for (const hook of list) {\n if (after !== undefined && hook.part < after) continue;\n const answer = hook.facts(path, code);\n if (answer !== undefined) return answer;\n }\n return undefined;\n };\n}\n\nfunction machineOf(draft: MachineDraft): Machine {\n const known = composeKnown(draft.hooks, draft.replaced);\n const facts = composeFacts(draft.factHooks, 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 ...(draft.domains === undefined ? {} : { domains: { ...draft.domains } }),\n ...(known === undefined ? {} : { known }),\n ...(facts === undefined ? {} : { facts }),\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 table `domains` merges name by name. Two domains with the same test, parents and summary give one domain (D22).\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 * The hooks `facts` compose the same way, and the first answer that is not `undefined` wins.\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: [], factHooks: [], 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.domains !== undefined) {\n const domains = (draft.domains ??= {});\n for (const name of Object.keys(part.domains)) mergeLeaf(m, domains, name, part.domains[name], [\"domains\", name], index, replaces, sameDomain, \"Two parts give two different domains for this base type.\");\n }\n if (part.known !== undefined && !draft.hooks.some((hook) => hook.known === part.known)) draft.hooks.push({ part: index, known: part.known });\n if (part.facts !== undefined && !draft.factHooks.some((hook) => hook.facts === part.facts)) draft.factHooks.push({ part: index, facts: part.facts });\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\", \"domains\"] 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]`, `[\"walkers\", name]` and `[\"domains\", 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 domains: machine.domains === undefined ? undefined : { ...machine.domains },\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 ...(tables.domains === undefined ? {} : { domains: tables.domains as NonNullable<Machine[\"domains\"]> }),\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/** A test that passes each name. A rung of `answerOf` then answers with each entry that it has. */\nconst EACH_NAME = (): boolean => true;\n\n/** The evaluator that a rung gives, without the record of the other rungs. */\nexport interface QuickAnswer {\n readonly name: string;\n readonly rung: Rung;\n}\n\n/**\n * This function finds the evaluator of a verb without the record of the rungs. It visits the rungs of `ask` in the\n * same order: the own entry, then the kind, then the default of the world (VERB.LADDER). A plan without a trace,\n * `deref` and the walkers of steps use it, thus each verb has one ladder.\n *\n * @param world - The world, for its defaults.\n * @param own - The own entries of the document, when it has some.\n * @param kind - The kind of the document. `undefined` skips the kind rung, as for a value without a type. `null` is\n * a kind that the world does not have: the question stops there, as in `ask`.\n * @param verb - The verb, for example `eval`, `format`, `deref` or `step`.\n * @param has - The test of a name. A rung answers only with a name that passes it. The default passes each name.\n * @returns The evaluator name and its rung, or `undefined` when no rung answers.\n */\nexport function answerOf(\n world: World,\n own: Readonly<Record<string, string>> | undefined,\n kind: Kind | undefined | null,\n verb: string,\n has: (name: string) => boolean = EACH_NAME,\n): QuickAnswer | undefined {\n const ownName = entryOf(own, verb);\n if (ownName !== undefined && has(ownName)) return { name: ownName, rung: \"own\" };\n if (kind === null) return undefined;\n const kindName = kind === undefined ? undefined : entryOf(kind.verbs, verb);\n if (kindName !== undefined && has(kindName)) return { name: kindName, rung: \"kind\" };\n const fallback = entryOf(world.defaults, verb);\n return fallback !== undefined && has(fallback) ? { name: fallback, rung: \"default\" } : undefined;\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. Each verb has this ladder:\n * `eval`, `deref`, `step` and each verb of a language (VERB.LADDER).\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 Kind, type World, entriesAsJson, lookupKind } from \"./world.ts\";\nimport { answerOf } from \"./ladder.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 = /* @__PURE__ */ 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. A field that holds `undefined` also gives `undefined`. The function `has` tells\n * the two cases apart (DEREF.HOST-UNDEFINED).\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 optional function tells if the thing has a field for a key. The kernel asks it only when `deref` gives\n * `undefined`. Then `true` tells that the field holds `undefined`. A thing without `has` reads `undefined` as a\n * missing field.\n *\n * @param key - The key of the step.\n * @returns `true` when the thing has the field.\n */\n has?(key: Key): boolean;\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. `{ thing: undefined }` tells that the keys reach a field that holds `undefined`.\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\n/** This function gives the own entries of an envelope, when it has a record of them. */\nfunction ownEntries(envelope: Envelope): Readonly<Record<string, string>> | undefined {\n const own = field(envelope as JsonRecord, \"own\");\n return isRecord(own) ? (own as Readonly<Record<string, string>>) : undefined;\n}\n\n/** One node of the memo of the kinds of a world: the kind of the keys up to this node, and the longer keys. */\ninterface KindNode {\n /** The kind of the keys, `null` for a type without a kind, or `undefined` before the first lookup. */\n kind?: Kind | null;\n next?: Map<Key, KindNode>;\n}\n\n/** The memo of the kinds of one world, by the keys of a type. */\ninterface KindMemo {\n first: Map<Key, KindNode>;\n /** The number of kinds in the memo. */\n size: number;\n}\n\n/** The most kinds in the memo of one world. A larger memo starts again, thus the types of the data cannot fill the memory. */\nconst MAX_KINDS = 1000;\n\nconst kindMemos = /* @__PURE__ */ new WeakMap<World, KindMemo>();\n\n/**\n * This function gives the kind of a type for the ladder: `null` when the world does not have the kind. The result\n * depends only on the world and on the keys of the type, thus a memo for each world keeps it (PLAN.KIND-MEMO). A\n * world does not change after a plan or a resolution uses it, as for `worldThing`.\n */\nfunction kindFor(world: World, type: TypeRef): Kind | null {\n const keys = typeof type === \"string\" ? undefined : typePath(type);\n // A computed type has no keys, and `lookupKind` gives it no kind.\n if (typeof type !== \"string\" && (keys === undefined || keys.length === 0)) {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : null;\n }\n let memo = kindMemos.get(world);\n if (memo === undefined || memo.size >= MAX_KINDS) {\n memo = { first: new Map(), size: 0 };\n kindMemos.set(world, memo);\n }\n const node = keys === undefined ? nodeAt(memo.first, type as string) : nodeOf(memo.first, keys);\n if (node.kind === undefined) {\n const found = lookupKind(world, type);\n node.kind = found.ok ? found.kind : null;\n memo.size += 1;\n }\n return node.kind;\n}\n\n/** This function gives the node of one key in a level of the memo, and makes it when the level does not have it. */\nfunction nodeAt(level: Map<Key, KindNode>, key: Key): KindNode {\n let node = level.get(key);\n if (node === undefined) {\n node = {};\n level.set(key, node);\n }\n return node;\n}\n\n/** This function gives the node of the keys of a type in the memo. */\nfunction nodeOf(first: Map<Key, KindNode>, keys: readonly Key[]): KindNode {\n let node = nodeAt(first, keys[0] as Key);\n for (let index = 1; index < keys.length; index += 1) node = nodeAt((node.next ??= new Map()), keys[index] as Key);\n return node;\n}\n\n/** This function tells if a table of code has the name. An entry of a document can hold another value than a text. */\nfunction codeIn(table: Readonly<Record<string, unknown>>, name: unknown): boolean {\n return typeof name === \"string\" && Object.hasOwn(table, name);\n}\n\n/**\n * This function finds the walker of a step document through the ladder of the verb `step` (VERB.LADDER). The rungs\n * are the own entry, then the kind, then the default of the world. A rung answers only with a walker that the\n * navigator has. A resolution and `check` use this function, thus they agree on `#STEP?`.\n *\n * @param nav - The world and the walkers.\n * @param step - A step of a path that is not a key.\n * @returns The walker, or `undefined` when no rung answers.\n */\nexport function walkerOf(nav: Navigator, step: unknown): Walker | undefined {\n const walkers = nav.walkers;\n if (walkers === undefined || !isEnvelope(step)) return undefined;\n const answer = answerOf(nav.world, ownEntries(step), kindFor(nav.world, step.type), \"step\", (name) => codeIn(walkers, name));\n return answer === undefined ? undefined : walkers[answer.name];\n}\n\n/** The answer of `plainStep` for a field that the value does not have. A field can hold `undefined`. */\nconst NOTHING: unique symbol = /* @__PURE__ */ Symbol(\"nothing\") as never;\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): unknown {\n if (Array.isArray(thing)) {\n if (key === \"length\") return thing.length;\n const index = typeof key === \"number\" ? key : /^\\d+$/.test(key) ? Number(key) : -1;\n return index >= 0 && index < thing.length ? (thing as readonly unknown[])[index] : NOTHING;\n }\n if (typeof thing === \"object\" && thing !== null) {\n const name = String(key);\n return Object.hasOwn(thing, name) ? (thing as Readonly<Record<string, unknown>>)[name] : NOTHING;\n }\n return NOTHING;\n}\n\n/**\n * This function tells if a value can be an envelope by its field `type`. An envelope has its own field `type`, thus\n * a value without that field is not an envelope, and the full test is not necessary.\n */\nfunction mayBeEnvelope(thing: unknown): boolean {\n return typeof thing === \"object\" && thing !== null && (thing as { readonly type?: unknown }).type !== 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, then the default of the world\n * (VERB.LADDER). A rung answers only with a `deref` that the navigator has. When no rung answers, the step goes into\n * the value: an own field of an object, or an item of a list. A value without a type is data, thus the step goes\n * into it at once.\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 // DEREF.HOST-UNDEFINED: `has` tells a field that holds undefined from a missing field.\n return reached !== undefined || thing.has?.(key) === true ? { thing: reached, by: \"own\" } : undefined;\n }\n if (nav.plain !== true && mayBeEnvelope(thing) && isEnvelope(thing)) {\n const envelope = thing as JsonRecord & Envelope;\n const derefs = nav.derefs;\n // A navigator without the code of a deref needs no lookup of the kind: no rung can answer.\n const answer = derefs === undefined ? undefined : answerOf(nav.world, ownEntries(envelope), kindFor(nav.world, envelope.type), \"deref\", (name) => codeIn(derefs, name));\n if (answer !== undefined) {\n const reached = (derefs as Readonly<Record<string, DerefCode>>)[answer.name]?.(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: answer.rung };\n }\n const reached = plainStep(envelope.value, key);\n return reached === NOTHING ? undefined : { thing: reached, by: \"default\" };\n }\n const reached = plainStep(thing, key);\n return reached === NOTHING ? undefined : { thing: reached, 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 (typeof thing !== \"object\" || thing === null) return false;\n // A text type other than `ref` names another kind, thus the full test of the envelope is not necessary.\n const type = (thing as { readonly type?: unknown }).type;\n if (type === undefined || (typeof type === \"string\" && type !== \"ref\")) return false;\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 = /* @__PURE__ */ 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[] = /* @__PURE__ */ 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/** This function tells if a root has a value of its own for the short path: each root except `caps`. */\nfunction quickRoot(root: unknown): root is \"names\" | \"self\" | \"event\" | \"world\" {\n return root === \"names\" || root === \"self\" || root === \"event\" || root === \"world\";\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 (!quickRoot(root)) return undefined;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return undefined;\n if (nav.adopt !== undefined) return undefined;\n return walkQuick(ctx[root], path, nav.plain === true, false);\n}\n\n/**\n * This function walks the steps of the short path from the value of the root (DEREF.QUICK). `resolveQuick` and each\n * compiled path use it, thus the two cannot disagree. It gives `undefined` when the path needs the full algorithm.\n *\n * @param start - The value of the root.\n * @param path - The steps. The walk starts at the index 1.\n * @param plain - `true` for a plain navigation.\n * @param keyed - `true` when each step after the root is a key. The walk then does not test the steps again.\n */\nfunction walkQuick(start: unknown, path: readonly unknown[], plain: boolean, keyed: boolean): Resolution | undefined {\n let here = start;\n for (let index = 1; index < path.length; index += 1) {\n if (typeof here !== \"object\" || here === null) return undefined;\n // One read of the field `type` finds a reference document. Without the field, the value is not an envelope.\n const type = plain ? undefined : (here as { readonly type?: unknown }).type;\n if (type === \"ref\") return undefined;\n if ((here as Partial<HostThing>)[THING] === true) {\n const thing = here as HostThing;\n if (thing.resolve === undefined || !(keyed || 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 (type !== undefined && 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 * A compiled path: one static path for one navigator (PLAN.PATH). `compilePath` reads the root, the open roots and\n * the steps one time. It asks the ladder of the verb `step` for each step document one time. Each resolution then\n * examines only the values of the context.\n */\nexport interface CompiledPath {\n /** The steps of the path, as the document gives them. The list of reads records these steps. */\n readonly path: readonly unknown[];\n /** The navigator of the compilation. A runtime with another navigator resolves the steps again. */\n readonly nav: Navigator;\n /**\n * This function resolves the path from a context, without a record of hops.\n *\n * @param ctx - The context.\n * @returns The same resolution as `resolve(nav, ctx, path, { hops: false })`.\n */\n resolve(ctx: Context): Resolution;\n}\n\n/** The walker of each step document of a path, by its index: `null` when no rung answers, `undefined` for a key. */\ntype KnownWalkers = readonly (Walker | null | undefined)[];\n\n/** The root whose value starts the short path of a compiled path. `FULL` takes the full algorithm at once. */\nconst FULL = 0;\nconst FROM_NAMES = 1;\nconst FROM_SELF = 2;\nconst FROM_EVENT = 3;\nconst FROM_WORLD = 4;\ntype From = typeof FULL | typeof FROM_NAMES | typeof FROM_SELF | typeof FROM_EVENT | typeof FROM_WORLD;\n\n/**\n * A compiled path as an object with fields (PLAN.LEAN). The code of `resolve` is on the class, thus each compiled path\n * keeps only its fields and makes no closure.\n */\nclass StaticPath implements CompiledPath {\n // The constructor writes each field one time, thus each field stays constant for V8, as the variable of a closure.\n declare readonly path: readonly unknown[];\n declare readonly nav: Navigator;\n /** The walker of each step document, from the ladder of `step`, or `undefined` for a path of keys. */\n declare private readonly known: KnownWalkers | undefined;\n /** The root that starts the short path, or `FULL`. */\n declare private readonly from: From;\n declare private readonly plain: boolean;\n\n constructor(path: readonly unknown[], nav: Navigator, known: KnownWalkers | undefined, from: From, plain: boolean) {\n this.path = path;\n this.nav = nav;\n this.known = known;\n this.from = from;\n this.plain = plain;\n }\n\n resolve(ctx: Context): Resolution {\n const from = this.from;\n if (from !== FULL) {\n const start = from === FROM_NAMES ? ctx.names : from === FROM_WORLD ? ctx.world : from === FROM_SELF ? ctx.self : ctx.event;\n const quick = walkQuick(start, this.path, this.plain, true);\n if (quick !== undefined) return quick;\n }\n return resolveFully(this.nav, ctx, this.path, undefined, this.known);\n }\n}\n\n/**\n * This function compiles one static path for one navigator. The resolver gives the same thing, error and reason as\n * `resolve` without hops (PLAN.PATH-SAME). It keeps no value of a context.\n *\n * - Some paths take the full algorithm at once, because the short path cannot answer them. A path from `caps` or from\n * a closed root is one. A path with a step document and each path of a navigator with `adopt` are others.\n * - Each other path walks the short path from its root, and it takes the full algorithm when the values need it.\n * - The walker of each step document comes from the ladder one time, here. The navigator and the step document do\n * not change, thus the answer does not change either.\n *\n * @param nav - The navigator. A plan compiles its paths for its machine.\n * @param path - The steps. The first step is a root.\n * @returns The compiled path.\n */\nexport function compilePath(nav: Navigator, path: readonly unknown[]): CompiledPath {\n const keyed = keysFrom(path, 1);\n const known = keyed ? undefined : walkersOf(nav, path);\n return new StaticPath(path, nav, known, startOf(nav, path, keyed), nav.plain === true);\n}\n\n/** This function gives the root that starts the short path of a compiled path, or `FULL`. */\nfunction startOf(nav: Navigator, path: readonly unknown[], keyed: boolean): From {\n const root = path[0];\n // The short path of `resolveQuick` refuses each of these paths before it reads a value, thus it is not necessary.\n if (!keyed || !quickRoot(root) || nav.adopt !== undefined) return FULL;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return FULL;\n return root === \"names\" ? FROM_NAMES : root === \"self\" ? FROM_SELF : root === \"event\" ? FROM_EVENT : FROM_WORLD;\n}\n\n/**\n * This function asks the ladder of the verb `step` for each step document of a path. A step whose lookup throws\n * stays unknown, thus the full algorithm asks the ladder again for it.\n */\nfunction walkersOf(nav: Navigator, path: readonly unknown[]): KnownWalkers | undefined {\n // Without walkers, `walkerOf` gives `undefined` at once.\n if (nav.walkers === undefined) return undefined;\n const out = new Array<Walker | null | undefined>(path.length);\n for (let index = 1; index < path.length; index += 1) {\n const step = path[index];\n if (isKey(step)) continue;\n try {\n out[index] = walkerOf(nav, step) ?? null;\n } catch {\n // The full algorithm asks the ladder again, and it gives the exception there.\n }\n }\n return out;\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 that the\n * ladder of the verb `step` gives, with the thing that the path reached. After each hop, a reference document is\n * followed until the path reaches 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 return resolveFully(nav, ctx, path, options.hops === false ? undefined : [], undefined);\n}\n\n/**\n * This function resolves a path with the full algorithm of `resolve`.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The steps.\n * @param hops - The list that gets each hop, or `undefined` for no record.\n * @param known - The walker of each step document of the path, from `compilePath`. A reference that a step reaches has its own steps, and the ladder answers them.\n * @returns What the path reached and each hop, or an error.\n */\nfunction resolveFully(nav: Navigator, ctx: Context, path: readonly unknown[], hops: Hop[] | undefined, known: KnownWalkers | undefined): Resolution {\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, undefined);\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[], walkers: KnownWalkers | undefined): 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 && keysFrom(steps, index)) {\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 given = walkers?.[index];\n const walker = given === undefined ? walkerOf(nav, step) : (given ?? undefined);\n if (walker === undefined) return failed(\"#STEP?\", \"A step is a key, or a document of a kind with the verb step.\");\n const envelope = step as Envelope;\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, known);\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 NamesSource, type ScopeRule, type Shape, type World, lookupKind } from \"./world.ts\";\nimport type { ValueType } from \"./types.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 /** The value type that the shape declares for the part (`expect`). Only a check of types reads it. */\n readonly expect?: ValueType;\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[] = /* @__PURE__ */ Object.freeze([]);\n\nfunction hasSlots(template: Template): boolean {\n return template.t !== \"data\";\n}\n\n/** This function gives the shape of a part with the default type `of` and the value type `expect` of its container. */\nfunction termOf(of: string | undefined, expect: ValueType | undefined): Shape {\n return { shape: \"term\", ...(of === undefined ? {} : { of }), ...(expect === undefined ? {} : { expect }) };\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, expect?: ValueType): Template => {\n parts.push({\n path,\n key: path.join(\".\"),\n item,\n ...(of === undefined ? {} : { of }),\n ...(address ? { address: true as const } : {}),\n ...(expect === undefined ? {} : { expect }),\n });\n return { t: \"slot\", index: parts.length - 1 };\n };\n\n const deep = (item: Json, path: readonly Key[], of: string | undefined, expect: ValueType | undefined): Template => {\n if (isEnvelope(item)) return slot(item, path, of, false, expect);\n if (Array.isArray(item)) {\n const items = (item as readonly Json[]).map((child, index) => deep(child, [...path, index], of, expect));\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, expect)] 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, spec.expect);\n }\n if (spec.shape === \"deep\") return deep(item, path, spec.of, spec.expect);\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 ?? termOf(spec.of, spec.expect);\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 ?? termOf(spec.of, spec.expect);\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, termOf(spec.of, spec.expect)]))\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\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/**\n * This function gives the names that the scope rules of a kind give each part, and the names that only later parts\n * see. `check`, `conforms` and the plan read the scope rules with it.\n *\n * @param rules - The scope rules of the kind.\n * @param value - The value of the document.\n * @param slots - The parts of the value, in order.\n * @returns The names that each part sees, and the names that only the later parts see, by the index of the part.\n */\nexport function 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","import { type Envelope, type Json, type Key, type TypeRef, isEnvelope, isKey, typeName } from \"./doc.ts\";\nimport { type PartSlot, type Split, partsOf, pathMatches, scopesOf } from \"./parts.ts\";\nimport { answerOf, ask, type Answer } from \"./ladder.ts\";\nimport type { CapsRule, Kind, KindFacts, Side } from \"./world.ts\";\nimport type { Domain } from \"./types.ts\";\nimport type { TypeRule } from \"./typing.ts\";\nimport { type ErrorCode, type EvalError, type Result, Failure, fail, ok, placed, thrown, describe } from \"./errors.ts\";\nimport {\n type Cap,\n type CompiledPath,\n type Context,\n type Hop,\n type Navigator,\n type Resolution,\n type ResolveOptions,\n type Root,\n type Thing,\n ROOTS,\n context as makeRootContext,\n isHostThing,\n isRef,\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[] = /* @__PURE__ */ Object.freeze([]);\n\n/** No capability rules. One list serves each part that no rule narrows. */\nconst NO_RULES: readonly CapsRule[] = /* @__PURE__ */ 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 key of the grant of a context (CAP.NARROW-CODE): the capabilities that the kernel gave the document of the\n * context. A spread of a context keeps its grant. Thus compiled code passes the grant on in each context that it makes\n * from the context of its document. Only the kernel writes a grant.\n */\nconst GRANT = /* @__PURE__ */ Symbol(\"coeval.grant\");\n\n/** A context with the grant of the kernel. */\ntype Granted = Context & { readonly [GRANT]?: readonly Cap[] };\n\n/**\n * This function gives a context whose capabilities its grant permits (CAP.NARROW-CODE). A context whose grant is its\n * own list of capabilities stays the same object. Each other context keeps only the capabilities that its grant\n * permits, and a context without a grant keeps none. The result has the grant of its capabilities.\n */\nfunction granted(ctx: Context): Context {\n const grant = (ctx as Granted)[GRANT];\n if (grant === ctx.caps) return ctx;\n const caps = grant === undefined ? NO_CAPS : ctx.caps.every((cap) => permits(grant, cap)) ? ctx.caps : ctx.caps.filter((cap) => permits(grant, cap));\n const out: Granted = { ...ctx, caps, [GRANT]: caps };\n return out;\n}\n\n/**\n * This function gives the context of a part of a function evaluator. It is the context that the evaluator gives,\n * narrowed by the context of the document (CAP.NARROW), with the grant of its capabilities.\n */\nfunction handed(parent: Context, next: Context): Context {\n const ctx = narrow(parent, next);\n if ((ctx as Granted)[GRANT] === ctx.caps) return ctx;\n const out: Granted = { ...ctx, [GRANT]: ctx.caps };\n return out;\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 /** The number of effects before this effect. Under `all`, this number follows the order of the host. */\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 * The stable address of the effect (RUN.ADDRESS). The order of the host does not change it. The address has the\n * keys of the place, a `#` and the count of the earlier effects at that place in its scope. An example is\n * `1/bind/x#0`. Each item of `all` is a scope, and its prefix comes first: `all0.1/` is the item 1 of the first `all`\n * of the scope. The kernel gives each effect its address.\n */\n readonly address?: string;\n /**\n * The outcome of the effect: the result that it gave its document (RUN.OUTCOME). The kernel sets it when the answer\n * comes. It stays `undefined` when the run stops first, for example at an abort.\n */\n readonly outcome?: Result;\n}\n\n/**\n * One read of an evaluation: a path that code resolved, and what the path reached (READS.RECORD, D26). A schedule\n * keeps the list of the reads of an evaluation. `verifyReads` resolves each free read again in a new context, and it\n * tells if the old result stays valid.\n */\nexport interface Read {\n /** The path that the code resolved: its root, and its steps with the value of each step document. */\n readonly path: readonly unknown[];\n /**\n * What the path reached: the thing, or the error of the resolution. A host thing stays a thing. An exception of the\n * host gives its error value.\n */\n readonly reached: Result;\n /**\n * `true` when the read reads the context of the evaluation (READS.FREE). A read of a name that a kind binds, for\n * example a name of `let`, is not free. A read of a `self` that a kind sets is not free either, for example a node\n * of a tree. A path without a root is not free. `verifyReads` resolves only the free reads again.\n */\n readonly free: boolean;\n /**\n * `true` when the kernel adds the read, because a value keeps a root of the context for later (READS.KEPT). Such a\n * read has the whole root as its path.\n */\n readonly kept?: true;\n /** The hops of the resolution, only when the code asked for them. `verifyReads` then compares each hop too. */\n readonly hops?: readonly Hop[];\n}\n\n/** The text that names a resolution in the error of an exception of the host. */\nconst READ_FAILED = \"the resolution of a path\";\n\n/**\n * This function gives what a resolution reached as a result: the thing, or the error with its code and its reason.\n * The record of a read and `verifyReads` share it.\n *\n * @param found - The resolution.\n * @returns The result.\n */\nexport function reachedOf(found: Resolution): Result {\n return found.ok ? ok(found.thing) : fail(found.code, found.reason);\n}\n\n/**\n * This function resolves the path of a read, and it gives an exception of the host as an error value. The record of\n * a kept read and `verifyReads` use it.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The path.\n * @param hops - `true` records each hop.\n * @returns What the path reached, and the hops when the resolution gave them.\n */\nexport function readAgain(nav: Navigator, ctx: Context, path: readonly unknown[], hops: boolean): { readonly reached: Result; readonly hops?: readonly Hop[] } {\n try {\n const found = resolve(nav, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n return hops ? { reached: reachedOf(found), hops: found.hops } : { reached: reachedOf(found) };\n } catch (error) {\n return { reached: thrown(error, READ_FAILED) };\n }\n}\n\n/**\n * This function tells if a read reads the context at the root of the evaluation (READS.FREE). A kind can bind a name\n * or set `self` for its parts, and a read of that binding is not free. A path without a root reads no context. A read\n * of each other root is free. When a kind changes such a root, the read resolves again to another value, thus\n * `verifyReads` only does more work.\n */\nfunction isFree(root: Context, ctx: Context, path: readonly unknown[]): boolean {\n const head = path[0];\n if (head === \"self\") return ctx === root || Object.is(ctx.self, root.self);\n if (head !== \"names\") return typeof head === \"string\" && (ROOTS as readonly string[]).includes(head);\n if (ctx === root || ctx.names === root.names) return true;\n const name = path[1];\n // A read of the whole record of the names reads each free name too.\n if (!isKey(name)) return true;\n const key = String(name);\n const has = Object.hasOwn(ctx.names, key);\n return has === Object.hasOwn(root.names, key) && (!has || Object.is(ctx.names[key], root.names[key]));\n}\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, and a\n * `Failure` gives its own error value. In an evaluation, this function is a mock: it answers at once, and a promise\n * from it gives `#CALC!` (RUN.MOCK).\n */\nexport type Perform = (effect: Effect) => unknown;\n\n/** The key of the journal of a recorder or of a replayer, on its function. Two copies of the kernel share it. */\nexport const JOURNAL: unique symbol = /* @__PURE__ */ Symbol.for(\"coeval.journal\") as never;\n\n/**\n * The journal of a recorder or of a replayer, on its function `perform`. The kernel tells it the order in which the\n * waits of each `all` settle. In a replay, the kernel asks the journal for that order (RUN.RECORD, RUN.REPLAY).\n */\nexport interface Journal {\n /**\n * This function gets the item whose wait settled.\n *\n * @param all - The address of the `all`, for example `all0` or `all0.1/all0`.\n * @param item - The index of the item.\n */\n readonly settled?: (all: string, item: number) => void;\n /**\n * This function gives the item whose wait settles next.\n *\n * @param all - The address of the `all`.\n * @param waiting - The indices of the items that wait.\n * @returns The index of an item that waits, or `undefined` for the order of the host.\n */\n readonly next?: (all: string, waiting: readonly number[]) => number | undefined;\n}\n\n/** This function gives the journal of a function `perform`, when it has one. */\nfunction journalOf(perform: Perform | undefined): Journal | undefined {\n return perform === undefined ? undefined : (perform as { readonly [JOURNAL]?: Journal })[JOURNAL];\n}\n\n/**\n * This function gives the outcome of an effect that the host failed. A `Failure` gives its own error value, for\n * example the recorded error of a replay or `#REPLAY!`. Each other exception gives `#CALC!`, with the exception as the\n * cause (RUN.CAUSE).\n */\nfunction hostFailed(kind: string, place: readonly Key[], error: unknown): Result {\n if (error instanceof Failure) return placed({ ok: false, error: error.error }, place);\n return fail(\"#CALC!\", `The host failed the effect ${kind}: ${describe(error)}`, { place, cause: error });\n}\n\n/**\n * The scope of the addresses of effects (RUN.ADDRESS). The root of an evaluation is one scope, and each item of `all`\n * is a scope. The code of one scope does not interleave with itself, thus its counts do not depend on the host.\n */\ninterface Scope {\n /** The text before each address of the scope, for example `all0.1/`. */\n readonly prefix: string;\n /** The number of earlier effects at each place, by the text of the place. It is made at the first effect. */\n counts: Map<string, number> | undefined;\n /** The number of earlier uses of `all` in the scope. */\n alls: number;\n}\n\n/**\n * This function gives the text of a place in an address: each key, with a slash between two keys. A text key with\n * other characters than letters, digits, `_`, `$` and `-` gets quotes.\n *\n * @param place - The keys from the root document to a document.\n * @returns The text of the place.\n */\nexport function placeText(place: readonly Key[]): string {\n let text = \"\";\n for (let index = 0; index < place.length; index += 1) {\n const key = place[index] as Key;\n if (index > 0) text += \"/\";\n text += typeof key === \"number\" || /^[\\w$-]+$/.test(key) ? String(key) : JSON.stringify(key);\n }\n return text;\n}\n\n/** An effect while the kernel waits for its outcome. */\ntype Recorded = { -readonly [K in keyof Effect]: Effect[K] };\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. It gives only the capabilities that the document has (CAP.NARROW-CODE).\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 answer of the mock, the payload without a mock, 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. It gives only the capabilities that the document has (CAP.NARROW-CODE).\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 * This optional function tells the runtime that a value keeps the context for later, for example a closure of\n * `fn`. A later use of the value reads that context, and no evaluation records these reads. Thus the list of reads\n * gets a read of each root of the context (READS.KEPT).\n */\n keepsContext?(): void;\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/**\n * Compiled code: the evaluation of a document in a context. The code gives each part a context that it makes from\n * its own context with a spread. The part then keeps only the capabilities of the document (CAP.NARROW-CODE). A\n * context that the code makes without a spread gives the part no capabilities.\n */\nexport type Code = (ctx: Context, rt: Runtime) => Result;\n\n/**\n * Compiled code that can wait: the run of a document in a context. Its parts keep only the capabilities of the\n * document, as for `Code`.\n */\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 /** The machine of the evaluation, for example for its domains (D40). The kernel sets it. */\n readonly machine?: Machine;\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 answer of the mock, the payload without a mock, or an error value, for example `#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 /** The machine of the evaluation, for example for its domains (D40). The kernel sets it. */\n readonly machine?: Machine;\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, a mock answers the effect at once, or 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 * The type rule of the evaluator: the value types that a check of types gives its documents and their parts\n * (TYPE.RULE). Only a check reads it. An evaluator without a rule gives `unknown`.\n */\n readonly type?: TypeRule;\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. A run,\n * `check` and `effectsOf` ask it (CAP.PERMITS). In a check, its context has only the capabilities and the world.\n * - `known`: the names that the evaluators know, for `check`. Without it, `check` does not check such names.\n * - `domains`: the value domains of the language, by the name of their base type (D22).\n * - `facts`: the static facts of the names that a fallback kind covers, for `factsOf` (D24).\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 of the verb of the check 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 * The value domains of the language, by the name of their base type, for example a color or a unit of length. A\n * check reads them through `fits` and `member`. A domain of the kernel that the table does not name comes from\n * `STD_DOMAINS`.\n */\n readonly domains?: Readonly<Record<string, Domain>>;\n /**\n * This function gives the static facts of the code of a name, for `factsOf` (D24). An example is the operation\n * `[\"ops\", \"now\"]` of a formula language: a fallback kind names it, and only the language knows that it is volatile.\n * Each field of the answer wins over the same field of the contract of the kind. The function must be pure.\n *\n * @param path - The keys of the kind of the document, after each alias.\n * @param code - The name of the evaluator of the document, or of the walker of a step document.\n * @returns The facts, or `undefined` for the facts of the contract.\n */\n readonly facts?: (path: readonly Key[], code: string) => KindFacts | undefined;\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 of the plan, `eval` by default. */\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 /**\n * The verb of `run`, for example `format`. The default is `eval` (VERB.PREPARE). A plan keeps the verb of its\n * `prepare`, thus `plan.run` does not read this option.\n */\n readonly verb?: string;\n /** A signal of the host. When it aborts, the run stops with `#ABORT`. */\n readonly signal?: StopSignal;\n /**\n * A list that gets each read, in the order of the resolutions (READS.RECORD). Under `all`, the order of the host\n * decides the order of the reads of the items.\n */\n readonly reads?: Read[];\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 * The mock of the host (RUN.MOCK). It answers each effect at once, and its answer is the result of the effect.\n * Without it, an effect gives its payload (RUN.EVAL).\n */\n readonly perform?: Perform;\n /**\n * A list that gets each read, in the order of the resolutions (READS.RECORD). Without it, the plan records no read,\n * and each resolution costs one more test.\n */\n readonly reads?: Read[];\n}\n\n/** The options of `evaluate`. */\nexport interface EvaluateOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The verb that goes up the ladder at each document, for example `format`. The default is `eval` (VERB.PREPARE). */\n readonly verb?: string;\n /** The mock of the host (RUN.MOCK). Without it, an effect gives its payload (RUN.EVAL). */\n readonly perform?: Perform;\n /** A list that gets each read, in the order of the resolutions (READS.RECORD). */\n readonly reads?: Read[];\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 = /* @__PURE__ */ Object.freeze({ hops: false });\nconst WITH_HOPS: ResolveOptions = /* @__PURE__ */ Object.freeze({ hops: true });\n\n/** The record of the reads of one evaluation (READS.RECORD). */\ninterface Reading {\n readonly list: Read[];\n /** The context at the root of the evaluation. A free read has the binding of this context. */\n readonly root: Context;\n /** `true` after the kernel added a read of each root (READS.KEPT). */\n kept: boolean;\n /** `true` after the kernel added the read of the root `self`. */\n self: boolean;\n}\n\n/** This function makes the record of the reads of an evaluation, when the host gives a list. */\nfunction readingOf(list: Read[] | undefined, root: Context): Reading | undefined {\n return list === undefined ? undefined : { list, root, kept: false, self: false };\n}\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 * The scope of the addresses of the code that runs at this time (RUN.ADDRESS). `all` changes it for each item. The\n * root scope is made at the first effect or `all`, thus an evaluation without effects makes no scope.\n */\n private scope: Scope | 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 /** The record of the reads. Without it, a resolution records nothing. */\n private readonly reading: Reading | undefined = 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 /** `true` when the evaluation records its reads. Then folded code evaluates again, thus each read goes in the list (PLAN.FOLD). */\n get recording(): boolean {\n return this.reading !== undefined;\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n return this.read(ctx, path, undefined, options);\n }\n\n /**\n * This function resolves a compiled path (PLAN.PATH). Without a list of reads and without a trace, the compiled\n * path answers at once. Each other resolution records its read, as `resolve` does.\n */\n resolvePath(ctx: Context, compiled: CompiledPath): Resolution {\n if (this.reading === undefined && !this.traced && compiled.nav === this.machine) return compiled.resolve(ctx);\n return this.read(ctx, compiled.path, compiled, undefined);\n }\n\n /** This function resolves a path, and records its read when the evaluation has a list of reads (READS.RECORD). */\n private read(ctx: Context, path: readonly unknown[], compiled: CompiledPath | undefined, options: ResolveOptions | undefined): Resolution {\n const hops = options?.hops ?? this.traced;\n const reading = this.reading;\n if (reading === undefined) return this.find(ctx, path, compiled, hops);\n const free = isFree(reading.root, ctx, path);\n // A kind that sets another self can give the old self on, as the parent of a node of a tree does (READS.KEPT).\n if (!free && path[0] === \"self\" && !reading.self) this.keep(reading, [\"self\"]);\n // A free read of the whole root self already holds what a kept read of self holds, as the root of a tree reads it.\n else if (free && path.length === 1 && path[0] === \"self\") reading.self = true;\n let found: Resolution;\n try {\n found = this.find(ctx, path, compiled, hops);\n } catch (error) {\n reading.list.push({ path, reached: thrown(error, READ_FAILED), free });\n throw error;\n }\n const asked = options?.hops === true;\n reading.list.push(asked ? { path, reached: reachedOf(found), free, hops: found.hops } : { path, reached: reachedOf(found), free });\n return found;\n }\n\n /**\n * This function resolves the steps of a path. A compiled path of this machine answers a resolution without hops. A\n * resolution with hops, and a path that compiled for another navigator, resolve the steps again.\n */\n private find(ctx: Context, path: readonly unknown[], compiled: CompiledPath | undefined, hops: boolean): Resolution {\n if (compiled !== undefined && !hops && compiled.nav === this.machine) return compiled.resolve(ctx);\n return resolve(this.machine, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n }\n\n keepsContext(): void {\n const reading = this.reading;\n if (reading === undefined || reading.kept) return;\n reading.kept = true;\n this.keep(reading, reading.self ? ROOTS.filter((root) => root !== \"self\") : ROOTS);\n }\n\n /**\n * This function adds a read of each whole root to the list, from the context at the root (READS.KEPT). An exception\n * of the host gives the error value of the read, because the evaluation did not ask for the read.\n */\n private keep(reading: Reading, roots: readonly Root[]): void {\n for (const root of roots) {\n if (root === \"self\") reading.self = true;\n const path = [root];\n reading.list.push({ path, reached: readAgain(this.machine, reading.root, path, false).reached, free: true, kept: true });\n }\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 /**\n * This function checks the capability of an effect, and records the effect with its address (RUN.ADDRESS). The\n * context keeps only the capabilities of its grant, thus compiled code cannot widen the context of its own effect\n * (CAP.NARROW-CODE).\n */\n private record(given: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result | Recorded {\n const ctx = granted(given);\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 scope = (this.scope ??= { prefix: \"\", counts: undefined, alls: 0 });\n const at = placeText(place);\n const counts = (scope.counts ??= new Map<string, number>());\n const count = counts.get(at) ?? 0;\n counts.set(at, count + 1);\n const effect: Recorded = {\n index: list.length,\n kind: text,\n path: keys,\n payload,\n node: node?.id ?? -1,\n at: this.tick,\n place,\n context: ctx,\n address: `${scope.prefix}${at}#${count}`,\n };\n list.push(effect);\n if (node !== undefined) node.effects.push(effect.index);\n return effect;\n }\n\n /**\n * This function answers an effect at once, without a wait: the mock gives the result, or the effect gives its\n * payload without a mock (RUN.MOCK, RUN.EVAL). A promise from the mock gives `#CALC!`.\n */\n private answer(effect: Recorded, place: readonly Key[]): Result {\n const perform = this.perform;\n if (perform === undefined) return (effect.outcome = ok(effect.payload));\n let done: unknown;\n try {\n done = perform(effect);\n } catch (error) {\n return (effect.outcome = hostFailed(effect.kind, place, error));\n }\n if (!(done instanceof Promise)) return (effect.outcome = ok(done));\n // The evaluation does not read the promise, thus its rejection must not be unhandled.\n void done.catch(() => undefined);\n return (effect.outcome = fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place }));\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 : this.answer(made, place);\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 this.answer(made, place);\n let done: unknown;\n try {\n done = perform(made);\n } catch (error) {\n return (made.outcome = hostFailed(made.kind, place, error));\n }\n if (!(done instanceof Promise)) return (made.outcome = ok(done));\n const result = (yield done.then(\n (value: unknown) => ok(value),\n (error: unknown) => hostFailed(made.kind, place, error),\n )) as Result;\n // A run that stops at this wait does not reach this line, thus the effect keeps no outcome (RUN.OUTCOME).\n return (made.outcome = 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 // The address of this call, and a scope for each item (RUN.ADDRESS). The journal of a replay reads the address.\n const outer = (this.scope ??= { prefix: \"\", counts: undefined, alls: 0 });\n const address = `${outer.prefix}all${outer.alls}`;\n outer.alls += 1;\n const scopes: Scope[] = new Array<Scope>(list.length);\n const journal = journalOf(this.perform);\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 const before = this.scope;\n this.scope = scopes[index] as Scope;\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 } finally {\n this.scope = before;\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 scope: Scope = { prefix: `${address}.${index}/`, counts: undefined, alls: 0 };\n scopes[index] = scope;\n const begin = list[index] as () => Steps;\n let steps: Steps;\n const before = this.scope;\n this.scope = scope;\n try {\n steps = begin();\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n continue;\n } finally {\n this.scope = before;\n }\n advance(index, steps, { threw: false });\n }\n };\n start();\n while (active.length > 0 && !failed) {\n // A replay settles the waits in the recorded order. Each other run takes the first wait that settles.\n const chosen = journal?.next?.(address, active.map((item) => item.index));\n const pick = chosen === undefined ? undefined : active.find((item) => item.index === chosen);\n const settled = (yield pick === undefined ? Promise.race(active.map((item) => item.pending)) : pick.pending) as {\n readonly item: Active;\n readonly value?: unknown;\n readonly error?: unknown;\n readonly threw: boolean;\n };\n journal?.settled?.(address, settled.item.index);\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\n/**\n * This function resolves a compiled path through a runtime (PLAN.PATH). The runtime of the kernel uses the compiled\n * path. Each other runtime gets the steps through `resolve`, thus a runtime that wraps another runtime sees each path.\n *\n * @param rt - The runtime.\n * @param ctx - The context.\n * @param compiled - The compiled path, from `compilePath`.\n * @returns What the path reached, or an error.\n */\nexport function resolveCompiled(rt: Runtime, ctx: Context, compiled: CompiledPath): Resolution {\n return rt instanceof Session ? rt.resolvePath(ctx, compiled) : rt.resolve(ctx, compiled.path);\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/**\n * This function gives the reason of a runner that waits where its parent cannot wait (RUN.WAIT). The plan, the\n * reference and `check` with the option `run` give the same reason.\n *\n * @param kindText - The text of the type of the runner document.\n * @returns The reason.\n */\nexport function waitedReason(kindText: string): string {\n return `${kindText} waits for effects, and its parent cannot wait. Give the parent a runner.`;\n}\n\n/** This function drives steps that cannot wait. A step that waits stops the steps, and gives `#CALC!`. */\nfunction drive(steps: Steps, kindText: string): 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!\", waitedReason(kindText));\n void steps.return(waited);\n return waited;\n}\n\nconst ABORTED = /* @__PURE__ */ 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 * The verb that goes up the ladder at each document, for example `format`. Each part evaluates with the same verb.\n * The default is `eval` (VERB.PREPARE).\n */\n readonly verb?: string;\n /**\n * `false`: no part of the plan folds. The default is `true`. Then a closed pure part of a plan without a trace\n * evaluates one time, when the plan compiles. Its result is one frozen value for each evaluation (PLAN.FOLD).\n */\n readonly fold?: 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. A mock can answer each\n * effect at once (RUN.MOCK).\n *\n * @param context - The names and the capabilities at the root.\n * @param options - A list that gets the effects, the mock of the host and a list that gets the reads.\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, a signal to stop the run and a list that gets the reads.\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 /** The verb that goes up the ladder at each document. */\n readonly verb: string;\n /** The answer of a document that the ladder did not see, in a trace. */\n readonly noAnswer: Answer;\n /** `true` when closed pure parts fold (PLAN.FOLD). A plan with a trace does not fold. */\n readonly fold: boolean;\n /** The runtime of the folds of this compilation. The first fold makes it. */\n probe?: Probe;\n}\n\nfunction failing(c: Compiler, meta: Meta, place: readonly Key[], code: ErrorCode, reason: string): Compiled {\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): Compiled {\n const plain: Code = () => result;\n return finish(c, meta, plain, undefined);\n}\n\n/**\n * This function gives the code of a document in a trace. Each node records the context that its grant permits\n * (CAP.NARROW-CODE), as the code of the document gets it.\n */\nfunction finish(c: Compiler, meta: Meta, code: Code, steps: RunCode | undefined): Compiled {\n if (!c.traced) return { code, run: steps };\n const run = steps ?? runOf(code);\n const tracedCode: Code = (given, rt) => {\n const ctx = granted(given);\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* (given, rt) {\n const ctx = granted(given);\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/** The meta of a node of a compilation without a trace. Only a trace reads the meta of a node. */\nconst NO_META: Meta = /* @__PURE__ */ 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): Compiled {\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: c.noAnswer, 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: c.noAnswer, 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 let quick: ReturnType<typeof answerOf>;\n if (c.traced) {\n const answer = ask(world, envelope ?? {}, c.verb, 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 // A document has a type here, thus a kind that the read did not find is a kind that the world does not have.\n quick = answerOf(world, envelope?.own, kind ?? null, c.verb);\n name = quick?.name;\n unknown = quick === undefined && kind === undefined;\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 // The free names of each part, for the fold of this document (PLAN.FOLD). A plan without folds does not collect them.\n const frees: (readonly string[] | undefined)[] | undefined = c.fold ? [] : undefined;\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 frees?.push(own.free);\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 const run = compiled.run ?? runOf(compiled.code);\n return header === undefined\n ? { key: slot.key, path: slot.path, code: compiled.code, run }\n : { key: slot.key, path: slot.path, name: header, code: compiled.code, 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 done = finish(c, meta, placedCode(inner, place, name), undefined);\n if (frees === undefined || kind === undefined || !pureCode(c, envelope, kind, typePath, name, quick)) return done;\n const free = freeOf(doc, kind, split.parts, frees);\n if (free === undefined) return done;\n return free.length === 0 ? folded(c, done) : { code: done.code, run: done.run, free };\n}\n\n/*\n * The fold of a closed pure part (PLAN.FOLD, D43). A part folds when it evaluates one time at compile time, and its\n * code then gives that one result. These conditions make the result the same as at each evaluation:\n *\n * - The code of the part and of each part in it is pure, and the kind declares no effect and no run side.\n * - The part reads no name that it does not bind (STATIC.REFS). A reference is the only document that reads a name.\n * - The evaluation at compile time gets an empty context and a probe runtime. The probe resolves only the names that\n * the part binds. It refuses each other read, each effect and each closure that keeps its context.\n *\n * A refusal, an exception, the error #DEPTH! and a result that is not plain data cancel the fold.\n */\n\n/** The free names of a closed part. */\nconst CLOSED: readonly string[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function tells if the code of a document is pure, by the facts of D24 (FACTS.PURE). It reads the facts as\n * `factsOf` reads them. A kind with a run side, with declared effects or with volatile code is not pure here.\n */\nfunction pureCode(c: Compiler, envelope: Envelope | undefined, kind: Kind, typePath: readonly Key[], name: string, quick: ReturnType<typeof answerOf>): boolean {\n if (kind.side === \"run\" || (kind.effects !== undefined && kind.effects.length > 0)) return false;\n let answer: KindFacts | undefined;\n try {\n answer = c.machine.facts?.(typePath, name);\n } catch {\n return false;\n }\n // The contract of the kind describes the code of its own name, or an own entry that names the same code (D24).\n const described = c.verb === \"eval\" && (envelope === undefined || quick?.rung !== \"own\" || name === answerOf(c.machine.world, undefined, kind, c.verb)?.name);\n const pure = described ? (answer?.pure ?? kind.pure) : answer?.pure;\n const volatile = described ? (answer?.volatile ?? kind.volatile) : answer?.volatile;\n return pure === true && volatile !== true;\n}\n\n/**\n * This function gives the names that a document reads and does not bind, or `undefined` when the document can read\n * other roots. A reference reads the name of its path. Each other document reads the free names of its parts, less\n * the names that its scope rules give each part (STATIC.REFS).\n */\nfunction freeOf(doc: Envelope, kind: Kind, slots: readonly PartSlot[], frees: readonly (readonly string[] | undefined)[]): readonly string[] | undefined {\n if (isRef(doc)) {\n const path = doc.value;\n if (path.length < 2 || path[0] !== \"names\" || !path.every((step, index) => index === 0 || isKey(step))) return undefined;\n return [String(path[1])];\n }\n let sees: readonly (readonly string[])[] | undefined;\n let out: string[] | undefined;\n for (let index = 0; index < frees.length; index += 1) {\n const free = frees[index];\n if (free === undefined) return undefined;\n if (free.length === 0) continue;\n if (sees === undefined) sees = kind.scope === undefined || kind.scope.length === 0 ? [] : scopesOf(kind.scope, doc.value, slots).sees;\n const bound = sees[index] ?? CLOSED;\n for (const name of free) {\n if (bound.includes(name)) continue;\n out ??= [];\n if (!out.includes(name)) out.push(name);\n }\n }\n return out ?? CLOSED;\n}\n\n/** This class is the runtime of a fold. It reads only the names that the folded part binds, and it causes no effect. */\nclass Probe implements Runtime {\n readonly running = false;\n /** `true` after the part asked for something that a fold cannot give. */\n refused = false;\n /** The count of the names that the part read. */\n reads = 0;\n /**\n * The context of the folded part. Its roots `self`, `event` and `names` are traps: a direct read of a field\n * refuses the fold, as a resolution of these roots does. A copy of the record of the names reads no field.\n */\n readonly root: Context;\n\n constructor(readonly machine: Machine) {\n const refuse = (): void => {\n this.refused = true;\n };\n const root: Granted = {\n self: trap(refuse, false),\n event: trap(refuse, false),\n names: trap(refuse, true) as Readonly<Record<string, unknown>>,\n world: worldThing(machine.world),\n caps: NO_CAPS,\n [GRANT]: NO_CAPS,\n };\n this.root = root;\n }\n\n resolve(ctx: Context, path: readonly unknown[]): Resolution {\n const name = path[1];\n if (path[0] === \"names\" && isKey(name) && Object.hasOwn(ctx.names, String(name))) {\n this.reads += 1;\n const found = resolve(this.machine, ctx, path, WITH_HOPS);\n // A reference in the data resolves in the context of its reader, thus it can read a free name (DEREF.READER).\n if (found.hops.some((hop) => hop.by === \"collapse\" || isRef(hop.thing))) this.refused = true;\n return found;\n }\n this.refused = true;\n return { ok: false, code: \"#REF!\", reason: \"A folded part reads only the names that it binds.\", hops: [] };\n }\n\n effect(): Result {\n this.refused = true;\n return fail(\"#CAP!\", \"A folded part causes no effect.\");\n }\n\n *runEffect(): Steps {\n return this.effect();\n }\n\n *all(): Generator<Promise<unknown>, readonly Result[], unknown> {\n this.refused = true;\n return [];\n }\n\n keepsContext(): void {\n this.refused = true;\n }\n}\n\n/**\n * This function makes a trap for a root of the context of a fold. Each read of a field calls `refuse`. A trap of the\n * names gives no keys, thus a copy of the names reads no field.\n */\nfunction trap(refuse: () => void, copies: boolean): object {\n const no = (): undefined => {\n refuse();\n return undefined;\n };\n return new Proxy(\n {},\n {\n get: no,\n getOwnPropertyDescriptor: no,\n has: () => (refuse(), false),\n ownKeys: () => {\n if (!copies) refuse();\n return [];\n },\n getPrototypeOf: () => (refuse(), null),\n set: () => (refuse(), false),\n defineProperty: () => (refuse(), false),\n deleteProperty: () => (refuse(), false),\n },\n );\n}\n\n/**\n * This function folds the code of a closed pure part. The part evaluates one time with the probe. Its result becomes\n * one deeply frozen copy, and the code gives that copy at each evaluation (PLAN.SHARED). A fold that the probe cancels\n * gives the code without free names, thus no parent tries the fold again.\n */\nfunction folded(c: Compiler, done: Compiled): Compiled {\n const probe = (c.probe ??= new Probe(c.machine));\n probe.refused = false;\n probe.reads = 0;\n let constant: Result | undefined;\n try {\n const result = done.code(probe.root, probe);\n if (!probe.refused && (result.ok || result.error.code !== \"#DEPTH!\")) constant = sharedCopy(result) as Result | undefined;\n } catch {\n constant = undefined;\n }\n if (constant === undefined) return { code: done.code, run: done.run };\n const value = constant;\n if (probe.reads === 0) return { code: () => value, run: undefined, free: CLOSED };\n // The part reads its own names. A list of reads gets each read, thus the code evaluates again (READS.RECORD).\n const original = done.code;\n return { code: (ctx, rt) => (rt instanceof Session && !rt.traced && !rt.recording ? value : original(ctx, rt)), run: undefined, free: CLOSED };\n}\n\n/** The objects that a fold made. Each one is deeply frozen, thus a later fold uses it again and does not copy it. */\nconst SHARED: WeakSet<object> = /* @__PURE__ */ new WeakSet();\n\n/** The mark of a value that is not plain data. */\nconst NOT_PLAIN: unique symbol = /* @__PURE__ */ Symbol(\"not plain\");\n\n/**\n * This function gives a deeply frozen copy of plain data, or `undefined` for other values. Plain data is a primitive or\n * an array without holes and extra keys. It is also a record of enumerable data fields with the prototype of an object\n * or no prototype. The copy keeps cycles and shared objects. The objects of the host do not change.\n */\nfunction sharedCopy(value: unknown): unknown {\n try {\n const out = copyPlain(value, new Map());\n return out === NOT_PLAIN ? undefined : out;\n } catch {\n // A very deep value overflows the stack of the host.\n return undefined;\n }\n}\n\n/** This function copies one value for `sharedCopy`. The map holds the copy of each object that the copy saw. */\nfunction copyPlain(value: unknown, memo: Map<object, unknown>): unknown {\n if (typeof value === \"function\") return NOT_PLAIN;\n if (typeof value !== \"object\" || value === null) return value;\n if (SHARED.has(value)) return value;\n const seen = memo.get(value);\n if (seen !== undefined) return seen;\n const proto: unknown = Object.getPrototypeOf(value);\n const keys = Reflect.ownKeys(value);\n let out: Record<string, unknown> | unknown[];\n if (Array.isArray(value)) {\n if (proto !== Array.prototype || keys.length !== value.length + 1) return NOT_PLAIN;\n const list: unknown[] = [];\n memo.set(value, list);\n for (let index = 0; index < value.length; index += 1) {\n const field = Object.getOwnPropertyDescriptor(value, index);\n if (field === undefined || !(\"value\" in field) || field.enumerable !== true) return NOT_PLAIN;\n const item = copyPlain(field.value, memo);\n if (item === NOT_PLAIN) return NOT_PLAIN;\n list.push(item);\n }\n out = list;\n } else {\n if (proto !== Object.prototype && proto !== null) return NOT_PLAIN;\n const record: Record<string, unknown> = proto === null ? (Object.create(null) as Record<string, unknown>) : {};\n memo.set(value, record);\n for (const key of keys) {\n if (typeof key !== \"string\") return NOT_PLAIN;\n const field = Object.getOwnPropertyDescriptor(value, key);\n if (field === undefined || !(\"value\" in field) || field.enumerable !== true) return NOT_PLAIN;\n const item = copyPlain(field.value, memo);\n if (item === NOT_PLAIN) return NOT_PLAIN;\n // The key __proto__ is a field of the data, thus it does not set the prototype of the copy.\n if (key === \"__proto__\") Object.defineProperty(record, key, { value: item, enumerable: true, writable: true, configurable: true });\n else record[key] = item;\n }\n out = record;\n }\n Object.freeze(out);\n SHARED.add(out);\n return out;\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/**\n * This function gives the code of a document: the code of its evaluator, with the place of each error and of each\n * exception. The code gets the context that its grant permits, thus a compiled parent cannot widen it (CAP.NARROW-CODE).\n */\nfunction placedCode(inner: Code, place: readonly Key[], name: string): Code {\n return (ctx, rt) => {\n try {\n return placed(inner(granted(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. First the context keeps only the capabilities of its grant, thus a compiled\n * parent cannot widen the capabilities that the rules narrow (CAP.NARROW-CODE).\n */\nfunction gated(rules: readonly CapsRule[], part: Compiled): Compiled {\n const inner = part.code;\n const steps = part.run;\n const under = (given: Context): Context => {\n const ctx = granted(given);\n const caps = capsUnder(rules, ctx.caps);\n if (caps === ctx.caps || (caps.length === 0 && ctx.caps.length === 0)) return ctx;\n const out: Granted = { ...ctx, caps, [GRANT]: caps };\n return out;\n };\n // The steps of an evaluator are `runOf` of its code, thus `runOf` of this code narrows the context the same way.\n return { code: (ctx, rt) => inner(under(ctx), rt), run: steps === undefined ? undefined : (ctx, rt) => steps(under(ctx), rt) };\n}\n\n/**\n * This function gives the steps of a runner, with the place of each error and of each exception. The steps get the\n * context that its grant permits (CAP.NARROW-CODE).\n */\nfunction placedRun(inner: RunCode, place: readonly Key[], name: string): RunCode {\n return function* (ctx, rt) {\n try {\n return placed(yield* inner(granted(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 under a parent that cannot wait: its steps, driven without a wait. An\n * evaluation and a run both drive them (RUN.DRIVE-NESTED). Only a step that really waits gives `#CALC!`, at the place\n * of the runner, where the error started (RUN.WAIT).\n */\nfunction runnerCode(run: RunCode, place: readonly Key[], kindText: string): Code {\n return (ctx, rt) => placed(drive(run(ctx, rt), kindText), place);\n}\n\n/**\n * The code of a compiled document. The steps of a run are `undefined` for an evaluator: they are `runOf(code)`, and a\n * plan makes them only for a run (PLAN.LEAN).\n */\ninterface Compiled {\n readonly code: Code;\n readonly run: RunCode | undefined;\n /**\n * The names that the document reads and does not bind, when it is pure. An empty list marks a folded document.\n * `undefined` marks a document that cannot fold, or a plan without folds (PLAN.FOLD).\n */\n readonly free?: readonly string[];\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, machine } = input;\n const address = input.address === true ? { address: true } : {};\n // The code keeps the fill and not the whole input, thus it does not keep the compiled value of the document (PLAN.LEAN).\n const refill = input.fill;\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 : handed(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 machine,\n ...address,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.effect(ctx, effectKind, payload, place),\n fill: refill,\n });\n };\n}\n\nfunction interpretRun(fn: RunFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): RunCode {\n const { kind, typePath, doc, data, place, machine } = input;\n const refill = input.fill;\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 : handed(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 machine,\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: refill,\n });\n };\n}\n\n/**\n * This function gives the context at the root of an evaluation. It is the context of the host, with the world of\n * the machine when the context has none. The host gives the capabilities, thus the root has the grant of each one\n * (CAP.NARROW-CODE). An evaluation and `verifyReads` share it.\n *\n * @param machine - The machine.\n * @param ctx - The context of the host.\n * @returns The context at the root.\n */\nexport function rootContext(machine: Machine, ctx: Context): Context {\n if (ctx.world !== null && (ctx as Granted)[GRANT] === ctx.caps) return ctx;\n const root: Granted = { ...ctx, world: ctx.world === null ? worldThing(machine.world) : ctx.world, [GRANT]: ctx.caps };\n return root;\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 * The verb of the options goes up the ladder at each document, and each part evaluates with the same verb. The\n * default verb is `eval`. A plan of another verb, for example `format`, evaluates, runs and traces as a plan of\n * `eval` does (VERB.PREPARE).\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, a trace and the verb.\n * @returns The plan.\n */\nexport function prepare(machine: Machine, doc: unknown, options: PrepareOptions = {}): Plan {\n const verb = options.verb ?? \"eval\";\n const noAnswer: Answer = verb === \"eval\" ? NO_ANSWER : { verb, error: \"no-answer\", steps: [] };\n const traced = options.trace === true;\n const c: Compiler = { machine, traced, maxDepth: machine.maxDepth ?? 1000, verb, noAnswer, fold: !traced && options.fold !== false };\n let root: Compiled;\n try {\n root = compileNode(c, doc, [], options.declaredType, 0);\n } catch (error) {\n const result = placed(thrown(error, \"the compilation\"), []);\n root = { code: () => result, run: undefined };\n }\n return new CompiledPlan(machine, c.traced, root.code, root.run);\n}\n\n/**\n * The object of a plan (PLAN.LEAN). The code of `evaluate` and `run` is on the class, thus a plan keeps only its\n * machine and its compiled code. A plan makes its compiled root and the steps of a run at their first use.\n */\nclass CompiledPlan implements Plan {\n /*\n * The constructor writes each field one time, and the class declares the fields with `declare`. A field that a class\n * defines first as `undefined` and then writes again is not constant for V8, and the code of an evaluation then\n * loads it at each call.\n */\n declare readonly machine: Machine;\n declare readonly traced: boolean;\n /** The code of the root document. */\n declare readonly code: Code;\n /** The steps of a run of the root document. `undefined` gives `runOf(code)` at the first `run`. */\n declare private steps: RunCode | undefined;\n /** The compiled root, after the first read of `root`. */\n declare private part: CompiledPart | undefined;\n\n constructor(machine: Machine, traced: boolean, code: Code, steps: RunCode | undefined) {\n this.machine = machine;\n this.traced = traced;\n this.code = code;\n this.steps = steps;\n this.part = undefined;\n }\n\n get root(): CompiledPart {\n return (this.part ??= { key: \"\", path: [], code: this.code, run: this.runCode() });\n }\n\n /** This function gives the steps of a run of the root document. */\n runCode(): RunCode {\n return (this.steps ??= runOf(this.code));\n }\n\n evaluate(context: Context = makeContext(), evalOptions?: EvalOptions): Result {\n const machine = this.machine;\n const ctx = rootContext(machine, context);\n const s = new Session(machine, false, this.traced, evalOptions?.perform, undefined, evalOptions?.effects, readingOf(evalOptions?.reads, ctx));\n return this.code(ctx, s);\n }\n\n run(context: Context = makeContext(), runOptions: RunOptions = {}): Promise<Result> {\n const machine = this.machine;\n const ctx = rootContext(machine, context);\n const s = new Session(machine, true, this.traced, runOptions.perform, runOptions.signal, undefined, readingOf(runOptions.reads, ctx));\n return driveWaiting(this.runCode()(ctx, s), runOptions.signal);\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 // A map treats -0 and 0 as one key, so -0 gets its own plan each time.\n if (Object.is(doc, -0)) return prepare(machine, doc, options);\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 of the options goes up the ladder for each document. The default verb is `eval`. The kind of the document\n * tells where its parts are. The evaluator gets each part sealed: it can evaluate the part, and it cannot read its\n * value.\n *\n * A failure gives an error value, and the function does not throw. The function records each effect in its order,\n * and the host does not do it. A mock can answer each effect at once (RUN.MOCK).\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 options - The type of a bare root value, or the options: that type, the mock of the host, the verb and a list for the reads.\n * @returns The result, the trace and the effects in their order.\n */\nexport function evaluate(machine: Machine, doc: unknown, context: Context = makeContext(), options?: string | EvaluateOptions): Run {\n const given: EvaluateOptions = typeof options === \"string\" ? { declaredType: options } : (options ?? {});\n const declaredType = given.declaredType;\n const plan = prepare(machine, doc, {\n trace: true,\n ...(declaredType === undefined ? {} : { declaredType }),\n ...(given.verb === undefined ? {} : { verb: given.verb }),\n });\n const ctx = rootContext(machine, context);\n const s = new Session(machine, false, true, given.perform, undefined, undefined, readingOf(given.reads, ctx));\n const result = (plan as CompiledPlan).code(ctx, 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, a signal, the verb and a list for the reads.\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, {\n trace: true,\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n });\n const ctx = rootContext(machine, context);\n const s = new Session(machine, true, true, options.perform, options.signal, undefined, readingOf(options.reads, ctx));\n const result = await driveWaiting((plan as CompiledPlan).runCode()(ctx, 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 {\n type EvalInput,\n type Evaluator,\n type Machine,\n type Plan,\n type Result,\n type RunPart,\n type Runner,\n type Steps,\n fail,\n ok,\n planner,\n} from \"./evaluate.ts\";\nimport { Failure } from \"./errors.ts\";\nimport { type Cap, type HostThing, type Thing, type Walker, THING, isHostThing, valueOfThing } from \"./deref.ts\";\nimport type { World } from \"./ladder.ts\";\nimport { type AttributeDeclaration, type TreeContract, equationType, lookupKind } from \"./world.ts\";\nimport { STD_DOMAINS } from \"./types.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\" }, pure: true, summary: \"A number. Its value is the result.\" },\n text: { verbs: { eval: \"data.text\", view: \"view.value\" }, pure: true, summary: \"A text. Its value is the result.\" },\n bool: { verbs: { eval: \"data.bool\", view: \"view.value\" }, pure: true, 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 pure: true,\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 pure: true,\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 pure: true,\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\" }, pure: true, 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 pure: true,\n lazy: [{ in: [[\"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 pure: true,\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 pure: true,\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 // A node that nothing reads keeps its attributes without an evaluation (TREE.LAZY).\n pure: true,\n lazy: [{}],\n // The code resolves self to find an open tree and the parent (C4, D44).\n reads: [\"self\"],\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 pure: true,\n lazy: [{}],\n reads: [\"self\"],\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 pure: true,\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 // The runner evaluates only the first part.\n pure: true,\n lazy: [{ after: 1 }],\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\": /* @__PURE__ */ dataOf(\"number\"),\n \"data.text\": /* @__PURE__ */ dataOf(\"string\"),\n \"data.bool\": /* @__PURE__ */ 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 = /* @__PURE__ */ 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 rungs of the ladder of an attribute, in their order (TREE.LADDER, D42). */\nexport type AttributeRung = \"own\" | \"kind\" | \"parent\" | \"copy\" | \"default\";\n\n/** The rungs of the ladder of an attribute, in their order (TREE.LADDER, D42). */\nexport const ATTRIBUTE_RUNGS: readonly AttributeRung[] = /* @__PURE__ */ Object.freeze([\"own\", \"kind\", \"parent\", \"copy\", \"default\"] as const);\n\n/** The record of the demand of one attribute of a node (TREE.RUNGS). */\nexport interface AttributeTrace {\n readonly attribute: string;\n /** The rungs that the demand visited, in their order. The last one answered, unless no rung answered. */\n readonly rungs: readonly AttributeRung[];\n /** The rung that answered. It is `undefined` when no rung answered. */\n readonly by?: AttributeRung;\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 /** The tree contract of the kind of the node (D42). */\n readonly tree: TreeContract | undefined;\n /**\n * This function gives an attribute through its ladder (TREE.LADDER).\n *\n * @param key - The name of the attribute.\n * @returns The result, or `undefined` when no rung answers.\n */\n read(key: string): Result | undefined;\n /**\n * This function evaluates an equation of the kind of the node, with the node as `self` and no capabilities.\n *\n * @param term - The equation.\n * @param names - The names that the equation sees.\n * @returns The result.\n */\n equation(term: Json, names: Readonly<Record<string, unknown>>): Result;\n /**\n * This function gives the names of a child for an equation of `down`: `child`, `index` and `prev` (TREE.DOWN).\n *\n * @param child - The thing of the child.\n * @returns The names, or the error of the list `children`.\n */\n childNames(child: HostThing): Result;\n /**\n * This function gives the record of the demand of an attribute that ended (TREE.RUNGS).\n *\n * @param key - The name of the attribute.\n * @returns The record, or `undefined` before the end of the demand.\n */\n trace(key: string): AttributeTrace | undefined;\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/**\n * The memo cell of one attribute: in evaluation, or done with its result and the rung that answered. A done cell\n * without a result tells that no rung answered.\n */\ntype Cell = { readonly busy: true } | { readonly busy: false; readonly result: Result | undefined; readonly by: AttributeRung | undefined };\n\n/** The capabilities of an equation: none (CAP.PURE). */\nconst NO_CAPS: readonly Cap[] = /* @__PURE__ */ Object.freeze([]);\n\n/** The names of an equation of `equations`, of a `unit` and of a `default`. */\nconst NO_NAMES: Readonly<Record<string, unknown>> = /* @__PURE__ */ Object.freeze({});\n\n/** The planners of equations, for each machine and each type of a bare equation (TREE.PLAN). */\nconst equationPlanners = /* @__PURE__ */ new WeakMap<Machine, Map<string, (doc: unknown) => Plan>>();\n\n/**\n * This function gives the plan of an equation. Each equation compiles one time for each machine (PLAN.CACHE). The\n * plan of the document does not keep it (PLAN.LEAN).\n */\nfunction equationPlan(machine: Machine, of: string | undefined, term: Json): Plan {\n let byType = equationPlanners.get(machine);\n if (byType === undefined) {\n byType = new Map();\n equationPlanners.set(machine, byType);\n }\n const key = of ?? \"\";\n let plans = byType.get(key);\n if (plans === undefined) {\n plans = planner(machine, of === undefined ? {} : { declaredType: of });\n byType.set(key, plans);\n }\n return plans(term);\n}\n\n/** This function gives the own entry of a table of a tree contract, or `undefined`. */\nfunction entryOf<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/** The contract of the kind of a node: its tree contract and the type of a bare equation. */\ninterface NodeContract {\n readonly tree: TreeContract | undefined;\n readonly of: string | undefined;\n}\n\nconst NO_CONTRACT: NodeContract = /* @__PURE__ */ Object.freeze({ tree: undefined, of: undefined });\n\n/** This function finds the tree contract of the kind of a node in the world of the machine. */\nfunction contractOf(machine: Machine | undefined, typePath: readonly Key[]): NodeContract {\n if (machine === undefined || typePath.length === 0) return NO_CONTRACT;\n const found = lookupKind(machine.world, typePath);\n if (!found.ok || found.kind.tree === undefined) return NO_CONTRACT;\n return { tree: found.kind.tree, of: equationType(found.kind) };\n}\n\nconst BUSY: Cell = /* @__PURE__ */ 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. Another step reads an attribute through its ladder (TREE.LADDER). The rungs are a part of\n * the node, an equation of its kind and an equation `down` of the kind of its parent. A copy from the parent, then a\n * fold or a default, come last. A failed attribute throws `Failure` with its own error, thus a reference to it gives that error.\n * The argument `outer` is the self of the context, that `treeNode` resolved. The node reads no root of the context directly (C4).\n */\nfunction treeThing(input: EvalInput, build: TreeBuild, outer: Thing | undefined): HostThing {\n const { parts, context, kind: type, place, machine } = input;\n const { tree, of } = contractOf(machine, input.typePath);\n const above = stateOf(outer);\n // Only a node of the same tree is a parent for the rungs `parent` and `copy`.\n const up = above !== undefined && above.build === build ? above : undefined;\n const cells = new Map<string, Cell>();\n /** The positions of the items of the list `children`, for the names of the children. */\n let positions: { readonly list: readonly unknown[]; readonly at: Map<unknown, number> } | undefined;\n\n const fold = (key: string, declared: NonNullable<AttributeDeclaration[\"fold\"]>): Result => {\n let acc = state.equation(declared.unit, NO_NAMES);\n if (!acc.ok) return acc;\n const children = read(\"children\");\n if (children === undefined) return acc;\n if (!children.ok) return children;\n if (!Array.isArray(children.value)) return fail(\"#VALUE!\", `The fold of ${key} needs a list in children.`);\n for (const item of children.value as readonly unknown[]) {\n const child = stateOf(item);\n // An item that is not a node of this tree does not count.\n if (child === undefined || child.build !== build) continue;\n const value = child.read(key);\n if (value === undefined) return fail(\"#N/A\", `No rung gives ${attributeText(key, child.type, child.place)}.`);\n if (!value.ok) return value;\n acc = state.equation(declared.combine, { acc: acc.value, item: value.value });\n if (!acc.ok) return acc;\n }\n return acc;\n };\n\n /** This function visits the rungs of the ladder of an attribute in their order, until one answers. */\n const climb = (key: string): { readonly result: Result; readonly by: AttributeRung } | undefined => {\n const part = parts.find((item) => item.key === key);\n if (part !== undefined) return { result: part.evaluate({ ...context, self: node }), by: \"own\" };\n const equation = entryOf(tree?.equations, key);\n if (equation !== undefined) return { result: state.equation(equation, NO_NAMES), by: \"kind\" };\n const down = up === undefined ? undefined : entryOf(up.tree?.down, key);\n if (up !== undefined && down !== undefined) {\n const names = up.childNames(node);\n return { result: names.ok ? up.equation(down, names.value as Readonly<Record<string, unknown>>) : names, by: \"parent\" };\n }\n const declared = entryOf(tree?.attributes, key);\n if (declared?.copy === true && up !== undefined) {\n const copied = up.read(key);\n if (copied !== undefined) return { result: copied, by: \"copy\" };\n }\n if (declared?.fold !== undefined) return { result: fold(key, declared.fold), by: \"default\" };\n if (declared?.default !== undefined) return { result: state.equation(declared.default, NO_NAMES), by: \"default\" };\n return undefined;\n };\n\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 // A node without a contract has only its parts, as before D42. Thus a missing part needs no cell.\n if (tree === undefined && up?.tree === undefined && !parts.some((item) => item.key === key)) return undefined;\n cells.set(key, BUSY);\n demands.push({ cells, key, text: attributeText(key, type, place) });\n let answer: { readonly result: Result; readonly by: AttributeRung } | undefined;\n try {\n answer = climb(key);\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: answer?.result, by: answer?.by });\n return answer?.result;\n };\n\n const state: NodeState = {\n build,\n type,\n place,\n tree,\n read,\n equation(term, names) {\n if (machine === undefined) return fail(\"#NOEVAL\", \"The evaluation of an equation needs the machine.\");\n return equationPlan(machine, of, term).evaluate({ ...context, names, caps: NO_CAPS, self: node });\n },\n childNames(child) {\n const children = read(\"children\");\n if (children !== undefined && !children.ok) return children;\n const list = children !== undefined && Array.isArray(children.value) ? (children.value as readonly unknown[]) : [];\n if (positions?.list !== list) {\n const at = new Map<unknown, number>();\n list.forEach((item, index) => {\n if (!at.has(item)) at.set(item, index);\n });\n positions = { list, at };\n }\n const index = positions.at.get(child);\n return ok({ child, index: index ?? null, prev: index === undefined || index === 0 ? null : list[index - 1] });\n },\n trace(key) {\n const cell = cells.get(key);\n if (cell === undefined || cell.busy) return undefined;\n const rungs = cell.by === undefined ? ATTRIBUTE_RUNGS : ATTRIBUTE_RUNGS.slice(0, ATTRIBUTE_RUNGS.indexOf(cell.by) + 1);\n return cell.by === undefined ? { attribute: key, rungs } : { attribute: key, rungs, by: cell.by };\n },\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 outer;\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 has(key: Key): boolean {\n // DEREF.HOST-UNDEFINED: an attribute with the value undefined is a field, not a missing step.\n if (key === \"parent\" || key === \"type\" || parts.some((part) => part.key === String(key))) return true;\n const cell = cells.get(String(key));\n return cell !== undefined && !cell.busy && cell.result !== undefined;\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 gives the record of the demand of an attribute of a node of the decorated tree (TREE.RUNGS). The\n * record holds the rungs that the demand visited, and the rung that answered. An explorer draws the ladder with it.\n *\n * @param node - The thing of a node.\n * @param attribute - The name of the attribute.\n * @returns The record, or `undefined` for a thing that is not a node or an attribute that no demand reached.\n */\nexport function attributeTrace(node: Thing, attribute: string): AttributeTrace | undefined {\n return stateOf(node)?.trace(attribute);\n}\n\n/** The path of the root `self`. A node of the tree resolves it, thus the list of reads holds the read (C4). */\nconst SELF_PATH: readonly Json[] = /* @__PURE__ */ Object.freeze([\"self\"]);\n\n/** The options of the resolution of `self`: the node needs no hops. */\nconst NO_HOPS = /* @__PURE__ */ Object.freeze({ hops: false });\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. The\n * node reads `self` through `resolve` (C4, D44). A machine that closes the root `self` thus gives no nested trees.\n */\nfunction treeNode(input: EvalInput): Result {\n const found = input.resolve(SELF_PATH, NO_HOPS);\n const outer = found.ok ? found.thing : undefined;\n const above = stateOf(outer);\n if (above !== undefined && above.build.open) return ok(treeThing(input, above.build, outer));\n const build: TreeBuild = { open: true };\n const root = treeThing(input, build, outer);\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 = /* @__PURE__ */ 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 || parts.length > 1) return fail(\"#VALUE!\", \"pure needs exactly 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, its walkers and the domains of the kernel. */\nexport const STD_MACHINE: Machine = { world: STD_WORLD, evaluators: STD_EVALUATORS, runners: STD_RUNNERS, walkers: STD_WALKERS, domains: STD_DOMAINS };\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 Key, isRecord, typeName } from \"./doc.ts\";\nimport type { Machine } from \"./evaluate.ts\";\nimport type { DocVisit, Issue } from \"./static.ts\";\nimport { type ValueType, fits, isUnknown, typeIssues, typeText } from \"./types.ts\";\n\n/*\n * The check of value types (R5 P3, D25). The pass reads the documents that the walk of `check` visited. It goes down\n * to give each part the type that its position needs, and it goes up to synthesize the type of each document from the\n * types of its parts. A type issue is a static finding: it does not change an evaluation.\n */\n\n/** What a type rule gets for one document. */\nexport interface TypeInput {\n /** The keys of the kind of the document, after each alias. */\n readonly typePath: readonly Key[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** The type that the position of the document needs. It is `unknown` when the position needs no type. */\n readonly expected: ValueType;\n /** The paths of the parts in the value, in the order of the value. */\n readonly paths: readonly (readonly Key[])[];\n /** `true` when the position declares an address. A reference there gives a thing, not a value. */\n readonly address: boolean;\n readonly machine: Machine;\n /**\n * This function gives the type of a part that the check typed before. It gives `unknown` for a part that the check\n * did not type yet, and for a part with an issue.\n *\n * @param path - The path of the part in the value.\n * @returns The type of the part.\n */\n typeOf(path: readonly Key[]): ValueType;\n /**\n * This function gives the type of a name: the type that a kind around the document binds. Without such a kind, it\n * gives the type from the option `rootTypes` of the host.\n *\n * @param name - The name.\n * @returns The type, or `undefined` when neither a kind around the document nor the host gives the name a type.\n */\n nameType(name: string): ValueType | undefined;\n /**\n * This function gives the type of a root of the context at the document (TYPE.ROOTS). The host gives the types of\n * `self`, `world` and `event` in the option `rootTypes`. A rule can give other types to its parts. The root `caps`\n * always has the type `CAPS_TYPE`. A rule reads the type of a name with `nameType`, thus the root `names` gives\n * `unknown`.\n *\n * @param root - The root.\n * @returns The type. It is `unknown` for a root without a type.\n */\n rootType(root: string): ValueType;\n /**\n * This function examines a value type of a contract with `typeIssues`, one time in a check. The first problem of a\n * type becomes an issue at the document. A term with a problem reads as `unknown`.\n *\n * @param type - The value type of the contract.\n * @param what - What the type is, for the reason, for example \"the result of ops.add\".\n * @returns The type.\n */\n contract(type: unknown, what: string): ValueType;\n}\n\n/** What a type rule tells for one part: the type that the part must have, and the types of the names of the part. */\nexport interface PartType {\n /** The type that the part must have. */\n readonly expect?: ValueType;\n /** What the part is, for the reason of an issue, for example \"argument 2 of ops.add\". */\n readonly what?: string;\n /** The types of the names that the scope rules of the kind bind for the part. Each other name of the rules gets `unknown`. */\n readonly names?: Readonly<Record<string, ValueType>>;\n /**\n * The types of the roots that the evaluator changes for the part, for example `self` for the attributes of a node.\n * Each other root keeps its type. The parts of an evaluator without a rule get `unknown` for each of these roots.\n */\n readonly roots?: Omit<RootTypes, \"names\">;\n}\n\n/**\n * The value types of the roots of a context, for a check of types (TYPE.ROOTS). The host gives them in the option\n * `rootTypes` of `check` and `typeCheck`. A root without a type has the type `unknown`. The root `caps` always has the\n * type `CAPS_TYPE`, because the kernel narrows it.\n *\n * The host keeps the types true: each root of the context holds a member of its type. A host thing, or a machine\n * with `adopt`, keeps each step true too. The context binds each name of `names`, thus the option `names` of `check`\n * lists it too.\n */\nexport interface RootTypes {\n /** The type of each name that the host binds. A name of the host without a type here has the type `unknown`. */\n readonly names?: Readonly<Record<string, ValueType>>;\n /** The type of `self`: the node or the position that the document is part of. */\n readonly self?: ValueType;\n /** The type of `world`, for example the schema of a store. The context then gives the world. */\n readonly world?: ValueType;\n /** The type of `event`: the event that started a run. */\n readonly event?: ValueType;\n}\n\n/**\n * The value type of the root `caps`: a list of capabilities. A capability is a text, or a list of keys. The kernel\n * narrows the capabilities for each part, thus the host does not give this type.\n */\nexport const CAPS_TYPE: ValueType = { list: { union: [\"text\", { list: { union: [\"text\", \"number\"] } }] } };\n\n/** A problem that a type rule finds. Its place is a part of the document, or the document itself. */\nexport interface TypeProblem {\n /** The path of the part in the value. Without it, the problem is at the document. */\n readonly path?: readonly Key[];\n readonly reason: string;\n readonly expected?: ValueType;\n readonly found?: ValueType;\n}\n\n/**\n * The type rule of an evaluator: what a check of types knows about the values that the evaluator gives. An evaluator\n * object holds its rule in its field `type`. Thus the rule follows the evaluator that the ladder gives a document\n * (TYPE.RULE).\n */\nexport interface TypeRule {\n /**\n * This function tells the type that a part must have, and the types of the names for the part. The check asks it\n * before it types the part. The parts that give the names of a rule `keysAt` come first.\n *\n * @param input - The document, the type that its position needs, and the types of the parts before.\n * @param path - The path of the part in the value.\n * @returns The type of the part and the types of its names.\n */\n readonly part?: (input: TypeInput, path: readonly Key[]) => PartType;\n /**\n * This function synthesizes the type of the document from the types of its parts. It must be sound: each value that\n * the evaluator gives is a member of the type.\n *\n * @param input - The document, the type that its position needs, and the types of its parts.\n * @param report - The function that gets each problem that the rule finds.\n * @returns The type of the document.\n */\n readonly synth: (input: TypeInput, report: (problem: TypeProblem) => void) => ValueType;\n}\n\n/** The type of one document of a check of types. */\nexport interface Typed {\n /** The keys from the root document to the document. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to the document. */\n readonly at: readonly Key[];\n /** The type that the check synthesized. A document with an issue has the type `unknown`. */\n readonly type: ValueType;\n /** The type that the position of the document needs, when it needs one. */\n readonly expected?: ValueType;\n}\n\n/** One document that the walk of a check visited, with what the pass of types needs. The package does not export it. */\nexport interface TypeNode {\n readonly visit: DocVisit;\n /** The names that the scope rules of the parent bind for this document. */\n readonly bound: readonly string[];\n /** The type that the shape of the parent declares for this part. */\n readonly expect: ValueType | undefined;\n /** The indices of the parts that the walk visited, in the order of the value. */\n readonly children: number[];\n /** The evaluator name that the ladder gives for the verb of the check. */\n evaluator: string | undefined;\n /** `true` when the check found an issue at this document. Then its type is `unknown`. */\n marked: boolean;\n}\n\n/** The result of the pass of types. */\nexport interface TypePass {\n readonly type: ValueType;\n readonly issues: readonly Issue[];\n readonly places: readonly Typed[];\n}\n\n/** A type that a position needs, and what the position is. */\ninterface Need {\n readonly type: ValueType;\n readonly what: string;\n}\n\n/** The types of the roots that an evaluator can change for its parts. */\ninterface Roots {\n readonly self: ValueType;\n readonly world: ValueType;\n readonly event: ValueType;\n}\n\n/** The roots that can change, as a rule gives them in `PartType.roots`. */\nconst CHANGING = [\"self\", \"world\", \"event\"] as const;\n\n/** The roots of the parts of an evaluator without a rule: such an evaluator can change each root. */\nconst UNKNOWN_ROOTS: Roots = { self: \"unknown\", world: \"unknown\", event: \"unknown\" };\n\n/** One document on the stack of the pass. */\ninterface Frame {\n readonly index: number;\n readonly rule: TypeRule | undefined;\n readonly input: TypeInput;\n readonly order: readonly number[];\n next: number;\n readonly typed: Map<string, ValueType>;\n readonly needs: readonly Need[];\n readonly names: ReadonlyMap<string, ValueType>;\n readonly roots: Roots;\n}\n\nfunction pathKey(path: readonly Key[]): string {\n return JSON.stringify(path.map(String));\n}\n\n/** This function gives the type rule of an evaluator name. A runner hides the evaluator of its name, and a runner has no rule yet (K29). */\nfunction ruleOf(machine: Machine, name: string | undefined): TypeRule | undefined {\n if (name === undefined || (machine.runners !== undefined && Object.hasOwn(machine.runners, name))) return undefined;\n const evaluator = Object.hasOwn(machine.evaluators, name) ? machine.evaluators[name] : undefined;\n const rule = typeof evaluator === \"object\" && evaluator !== null ? (evaluator as { readonly type?: unknown }).type : undefined;\n return typeof rule === \"object\" && rule !== null && typeof (rule as TypeRule).synth === \"function\" ? (rule as TypeRule) : undefined;\n}\n\n/** This function gives the order of the parts of a document: first the parts that give the names of a rule `keysAt`. */\nfunction orderOf(node: TypeNode, nodes: readonly TypeNode[]): readonly number[] {\n const sources = (node.visit.kind?.scope ?? []).flatMap((rule) => (\"keysAt\" in rule.names ? [rule.names.keysAt] : []));\n if (sources.length === 0 || node.children.length < 2) return node.children;\n const gives = (index: number): boolean => {\n const slot = (nodes[index] as TypeNode).visit.slot;\n return sources.some((prefix) => prefix.length <= slot.length && prefix.every((key, at) => String(key) === String(slot[at])));\n };\n return [...node.children.filter(gives), ...node.children.filter((index) => !gives(index))];\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * This function checks the value types of the documents that the walk of a check visited (TYPE.CHECK). The walk gives\n * the documents in the order of the document. The pass uses its own stack, thus a deep document cannot overflow the\n * stack of the host.\n *\n * @param machine - The machine of the check.\n * @param nodes - The documents, in the order of the document. The root is the first.\n * @param verb - The verb of the check. The value types of a contract describe the verb `eval` only.\n * @param expect - The type that the root must have.\n * @param rootTypes - The types of the roots and of the names of the host.\n * @returns The type of the root, the type issues in the order of the document, and the type of each document.\n */\nexport function typePass(machine: Machine, nodes: readonly TypeNode[], verb: string, expect: ValueType | undefined, rootTypes: RootTypes = {}): TypePass {\n if (nodes.length === 0) return { type: \"unknown\", issues: [], places: [] };\n const domains = machine.domains;\n const contracts = verb === \"eval\";\n const found: { readonly index: number; readonly issue: Issue }[] = [];\n const types = new Array<ValueType>(nodes.length);\n const needed = new Array<ValueType | undefined>(nodes.length);\n const seen = new Set<unknown>();\n\n const issueAt = (index: number, problem: TypeProblem): void => {\n const visit = (nodes[index] as TypeNode).visit;\n const issue: Issue = {\n code: \"#TYPE!\",\n place: visit.place,\n reason: problem.reason,\n at: visit.at,\n ...(problem.expected === undefined ? {} : { expected: problem.expected }),\n ...(problem.found === undefined ? {} : { found: problem.found }),\n };\n found.push({ index, issue });\n };\n\n const contract = (index: number, type: unknown, what: string): ValueType => {\n if (!seen.has(type)) {\n seen.add(type);\n const problem = typeIssues(type, domains)[0];\n if (problem !== undefined) issueAt(index, { reason: `The ${what} is not a correct value type. ${problem.reason}` });\n }\n return type as ValueType;\n };\n\n const enter = (index: number, needs: readonly Need[], names: ReadonlyMap<string, ValueType>, roots: Roots): Frame => {\n const node = nodes[index] as TypeNode;\n const visit = node.visit;\n const typed = new Map<string, ValueType>();\n const input: TypeInput = {\n typePath: visit.typePath ?? [],\n doc: visit.doc,\n // The need of the rule of the parent comes last. It is the type that the rule of this document reads.\n expected: needs.length === 0 ? \"unknown\" : (needs[needs.length - 1] as Need).type,\n paths: node.children.map((child) => (nodes[child] as TypeNode).visit.slot),\n address: visit.address === true,\n machine,\n typeOf: (path) => typed.get(pathKey(path)) ?? \"unknown\",\n nameType: (name) => names.get(name),\n rootType: (root) => (root === \"caps\" ? CAPS_TYPE : root === \"self\" || root === \"world\" || root === \"event\" ? roots[root] : \"unknown\"),\n contract: (type, what) => contract(index, type, what),\n };\n return { index, rule: node.marked ? undefined : ruleOf(machine, node.evaluator), input, order: orderOf(node, nodes), next: 0, typed, needs, names, roots };\n };\n\n const ruleFailed = (frame: Frame, error: unknown): void => {\n issueAt(frame.index, { reason: `The type rule of ${(nodes[frame.index] as TypeNode).evaluator ?? \"the evaluator\"} fails: ${message(error)}` });\n };\n\n const report = (frame: Frame, problem: TypeProblem): void => {\n const node = nodes[frame.index] as TypeNode;\n const key = problem.path === undefined ? undefined : pathKey(problem.path);\n const part = key === undefined ? undefined : node.children.find((child) => pathKey((nodes[child] as TypeNode).visit.slot) === key);\n issueAt(part ?? frame.index, problem);\n };\n\n const rootNeeds: Need[] = expect === undefined || isUnknown(contract(0, expect, \"expected type of the check\"), domains) ? [] : [{ type: expect, what: \"document\" }];\n // The check examines each type of the host at the root, one time. A kind that binds a name hides the name of the host.\n const hostNames = new Map<string, ValueType>();\n const given: Readonly<Record<string, ValueType>> = isRecord(rootTypes.names) ? rootTypes.names : {};\n for (const name of Object.keys(given)) hostNames.set(name, contract(0, given[name], `type of the name ${name} of the host`));\n const hostRoot = (root: (typeof CHANGING)[number]): ValueType => (rootTypes[root] === undefined ? \"unknown\" : contract(0, rootTypes[root], `type of the root ${root}`));\n const stack: Frame[] = [enter(0, rootNeeds, hostNames, { self: hostRoot(\"self\"), world: hostRoot(\"world\"), event: hostRoot(\"event\") })];\n while (stack.length > 0) {\n const frame = stack[stack.length - 1] as Frame;\n if (frame.next < frame.order.length) {\n const child = frame.order[frame.next] as number;\n frame.next += 1;\n const node = nodes[child] as TypeNode;\n const slot = node.visit.slot;\n const what = `part ${slot.join(\".\")} of ${typeName((nodes[frame.index] as TypeNode).visit.doc.type)}`;\n let part: PartType = {};\n if (frame.rule?.part !== undefined) {\n try {\n part = frame.rule.part(frame.input, slot) ?? {};\n } catch (error) {\n ruleFailed(frame, error);\n }\n }\n const needs: Need[] = [];\n // A need of the type `unknown` needs nothing, thus the pass leaves it out.\n const need = (type: ValueType, text: string): void => {\n if (!isUnknown(type, domains)) needs.push({ type, what: text });\n };\n if (contracts && node.expect !== undefined) need(contract(child, node.expect, `expected type of the ${what}`), what);\n if (part.expect !== undefined) need(part.expect, part.what ?? what);\n let names = frame.names;\n if (node.bound.length > 0) {\n // Each name that the scope rules bind hides the name around it. A name without a type from the rule gets `unknown`.\n const copy = new Map(names);\n for (const name of node.bound) copy.set(name, part.names !== undefined && Object.hasOwn(part.names, name) ? (part.names[name] as ValueType) : \"unknown\");\n names = copy;\n }\n // No contract tells how an evaluator changes the roots, thus only a rule keeps their types for its parts (TYPE.ROOTS).\n let roots = frame.rule === undefined ? UNKNOWN_ROOTS : frame.roots;\n const changes = part.roots;\n if (typeof changes === \"object\" && changes !== null) {\n const copy: Record<(typeof CHANGING)[number], ValueType> = { ...roots };\n for (const root of CHANGING) if (changes[root] !== undefined) copy[root] = changes[root] as ValueType;\n roots = copy;\n }\n stack.push(enter(child, needs, names, roots));\n continue;\n }\n stack.pop();\n const node = nodes[frame.index] as TypeNode;\n let type: ValueType = \"unknown\";\n if (!node.marked) {\n let synthesized: ValueType = \"unknown\";\n if (frame.rule !== undefined) {\n try {\n synthesized = frame.rule.synth(frame.input, (problem) => report(frame, problem));\n } catch (error) {\n ruleFailed(frame, error);\n }\n }\n const result = contracts ? node.visit.kind?.result : undefined;\n type = result === undefined ? synthesized : contract(frame.index, result, `result of the kind ${typeName(node.visit.doc.type)}`);\n }\n for (const need of frame.needs) {\n if (fits(type, need.type, domains)) continue;\n issueAt(frame.index, { reason: `The ${need.what} has the type ${typeText(type)}. It must have the type ${typeText(need.type)}.`, expected: need.type, found: type });\n // A part with an issue gets the type `unknown`, thus one problem does not give a chain of issues.\n type = \"unknown\";\n break;\n }\n types[frame.index] = type;\n needed[frame.index] = frame.needs.length === 0 ? undefined : (frame.needs[frame.needs.length - 1] as Need).type;\n stack[stack.length - 1]?.typed.set(pathKey(node.visit.slot), type);\n }\n\n const places = nodes.map((node, index) => {\n const want = needed[index];\n const entry = { type: types[index] ?? \"unknown\", ...(want === undefined ? {} : { expected: want }) } as Typed;\n // The keys of a place are made only when a reader asks for them, as a visit does.\n Object.defineProperty(entry, \"place\", { enumerable: true, get: () => node.visit.place });\n Object.defineProperty(entry, \"at\", { enumerable: true, get: () => node.visit.at });\n return entry;\n });\n const issues = found.sort((a, b) => a.index - b.index).map((item) => item.issue);\n return { type: types[0] ?? \"unknown\", issues, places };\n}\n","import { type Envelope, type Json, type Key, isKey, isRecord, typeName } from \"./doc.ts\";\nimport { type Kind, type Namespace, type World, type WorldEntry, effectsOfVerb, equationType, isKind, isNamespace } from \"./world.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type PartSlot, partsOf, scopesOf } from \"./parts.ts\";\nimport { type Cap, type Context, type Root, ROOTS, context, isRef, walkerOf, worldThing } from \"./deref.ts\";\nimport type { ErrorCode } from \"./errors.ts\";\nimport { type Machine, partCaps, permits, waitedReason } from \"./evaluate.ts\";\nimport type { ValueType } from \"./types.ts\";\nimport { type RootTypes, type TypeNode, type Typed, typePass } from \"./typing.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\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> = /* @__PURE__ */ 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 readonly #bound: readonly string[];\n readonly #expect: ValueType | 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 bound: readonly string[],\n expect: ValueType | undefined,\n ) {\n this.#place = place;\n this.#at = at;\n this.#bound = bound;\n this.#expect = expect;\n }\n\n /** The names that the scope rules of the parent bind for this document. The check of types reads them. */\n get bound(): readonly string[] {\n return this.#bound;\n }\n\n /** The type that the shape of the parent declares for this part. The check of types reads it. */\n get expect(): ValueType | undefined {\n return this.#expect;\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 readonly bound: readonly string[];\n readonly expect: ValueType | 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 bound: [],\n expect: undefined,\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 item.bound,\n item.expect,\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 bound: extra,\n expect: slot.expect,\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 /** The type that the position needs, for a type issue (`#TYPE!`). */\n readonly expected?: ValueType;\n /** The type that the check found, for a type issue (`#TYPE!`). */\n readonly found?: ValueType;\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 * The verb that goes up the ladder at each document, as in `prepare`. The default is `eval`. `#NOEVAL` and the hook\n * `known` follow this verb. The type rule of an evaluator serves each verb.\n *\n * The check tests the effects that the contract declares for this verb (VERB.EFFECTS). A kind without a declaration\n * for the verb gives no effect issue. The contract declares the value types of `eval` only, thus only `eval` checks\n * them (VERB.CHECK).\n */\n readonly verb?: string;\n /**\n * With `true`, the check also checks the value types (TYPE.CHECK). It reads the type rules of the evaluators, the\n * signatures of the operations and the value types of the contracts. A type issue has the code `#TYPE!`. The\n * default is `false`, thus a host opts in.\n */\n readonly types?: boolean;\n /** The type that the root document must have, for the check of the value types. */\n readonly expect?: ValueType;\n /**\n * With `true`, the check also finds the problems of a run (RUN.CAN-WAIT). A runner under a parent without a runner\n * gives `#CALC!` when an effect of its runners can reach the host. The parent cannot pass that wait through.\n * A runner without such an effect does not wait, and the run drives it (RUN.DRIVE-NESTED). A kind that declares\n * effects and has no runner gives `#CALC!` too, because in a run only a runner can wait for the host. The default is\n * `false`.\n */\n readonly run?: boolean;\n /**\n * The value types of the roots and of the names of the host, for the check of the value types (TYPE.ROOTS). A\n * reference then gets the type that its path reaches. Only a check with `types: true` reads them.\n */\n readonly rootTypes?: RootTypes;\n}\n\n/** The result of `typeCheck`. */\nexport interface Typing {\n /** The type of the root document. It is `unknown` when the root has an issue. */\n readonly type: ValueType;\n /** Each issue of the check. The type issues come after the other issues. */\n readonly issues: readonly Issue[];\n /** The type of each document, in the order of the document. */\n readonly places: readonly Typed[];\n}\n\n/** The least authority: the capability `[]` permits each effect (CAP.KEYS). */\nconst EACH: readonly Cap[] = /* @__PURE__ */ Object.freeze([[]]);\n\n/** No declared effect. One list serves each visit without effects. */\nconst NO_EFFECTS: readonly (readonly Key[])[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function gives the effects that the contract of the kind of a visit declares for a verb, as keys\n * (FACTS.EFFECTS, VERB.EFFECTS). The text `\"type\"` gives the type of the document after each alias. A visit without a\n * kind declares no effect. `check`, `factsOf` and `effectsOf` read the declarations with this one function (D27).\n *\n * @param v - The visit.\n * @param verb - The verb. The default is `eval`. A kind without a declaration for the verb gives no effect.\n * @returns The keys of each declared effect, in the order of the contract.\n */\nexport function declaredEffects(v: DocVisit, verb = \"eval\"): readonly (readonly Key[])[] {\n return verbDeclared(v, verb) ?? NO_EFFECTS;\n}\n\n/**\n * This function gives the effects that the contract of the kind of a visit declares for a verb, as keys. The result\n * is `undefined` when the contract has no declaration for the verb (D49). A visit without a kind declares no effect\n * for `eval` and no declaration for another verb.\n */\nfunction verbDeclared(v: DocVisit, verb: string): readonly (readonly Key[])[] | undefined {\n if (v.kind === undefined) return verb === \"eval\" ? NO_EFFECTS : undefined;\n const effects = effectsOfVerb(v.kind, verb);\n if (effects === undefined) return undefined;\n if (effects.length === 0) return NO_EFFECTS;\n return effects === \"type\" ? [v.typePath ?? []] : effects.map((kind) => kind.split(\".\"));\n}\n\n/**\n * This function gives the rule of a machine for an effect, for the static kit (CAP.PERMITS). The rule is the hook\n * `permits` of the machine, as in a run, or else the function `permits`. A check has no values, thus the hook gets a\n * context with the capabilities of the document and the world of the machine. Its names, its self and its event are\n * empty.\n *\n * @param machine - The machine.\n * @returns The rule. It gets the capabilities of a document and the keys of an effect.\n */\nexport function permitsOf(machine: Machine): (caps: readonly Cap[], kind: readonly Key[]) => boolean {\n const hook = machine.permits;\n if (hook === undefined) return permits;\n let base: Context | undefined;\n return (caps, kind) => hook(caps, kind, { ...(base ??= context({ world: worldThing(machine.world) })), caps });\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[], allowed: (caps: readonly Cap[], kind: readonly Key[]) => boolean): string {\n const text = kind.join(\".\");\n for (let up = v.parent; up !== undefined; up = up.parent) {\n if (up.caps !== undefined && allowed(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 * The hook `permits` of the machine decides, as in a run (CAP.PERMITS).\n * - `#CALC!`: with the option `run`, a runner under a parent without a runner, when an effect of its runners can reach\n * the host. Also a kind that declares effects and has no runner (RUN.CAN-WAIT). The issue has the place and the\n * reason of the run.\n * - `#TYPE!`: with the option `types`, a part whose type does not fit the type that its position needs (TYPE.CHECK).\n * A run does not always fail there, thus a type issue is a static finding, not an error of a run.\n *\n * The check asks the ladder for the verb of the options, `eval` by default (VERB.CHECK). The shapes, the paths and the\n * names follow the contracts, thus they are the same for each verb. The check tests the effects that each contract\n * declares for the verb: `effects` for `eval`, and the entry of `verbEffects` for another verb (VERB.EFFECTS). A kind\n * without a declaration for the verb gives no `#CAP!` and no `#CALC!` for an effect.\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, the capabilities, the verb, the types and the run.\n * @returns The problems, in the order of the document. The type issues come after the other issues.\n */\nexport function check(machine: Machine, doc: unknown, options: CheckOptions = {}): readonly Issue[] {\n return options.types === true ? typeCheck(machine, doc, options).issues : checkAll(machine, doc, options, undefined);\n}\n\n/**\n * This function checks a document, and it also checks the value types (TYPE.CHECK, D25). It finds each issue of\n * `check`. Then it synthesizes the type of each document from the types of its parts. It also checks each part\n * against the type that its position needs. The type rule of the parent, the signature of an operation or the shape\n * of the contract gives that type. A part with an issue gets the type `unknown`, thus one\n * problem does not give a chain of issues.\n *\n * A type issue has the code `#TYPE!`, the type that the position needs (`expected`) and the type that the check found\n * (`found`). It is a static finding: the evaluation of the document does not change.\n *\n * The option `rootTypes` gives the types of the roots and of the names of the host (TYPE.ROOTS). A reference then gets\n * the type that its path reaches, and a field that a closed record does not have is a type issue (TYPE.CLOSED).\n *\n * @param machine - The world and the code of the evaluators, with their type rules.\n * @param doc - The document, as JSON.\n * @param options - The options of `check`, the type that the root must have and the types of the roots.\n * @returns The type of the root, each issue, and the type of each document.\n */\nexport function typeCheck(machine: Machine, doc: unknown, options: CheckOptions = {}): Typing {\n const nodes: TypeNode[] = [];\n const issues = checkAll(machine, doc, options, nodes);\n const pass = typePass(machine, nodes, options.verb ?? \"eval\", options.expect, options.rootTypes);\n return { type: pass.type, issues: pass.issues.length === 0 ? issues : [...issues, ...pass.issues], places: pass.places };\n}\n\n/**\n * A problem of a world that `checkWorld` finds before a document exists (STATIC.COVERAGE). Each document of the\n * kind gives this problem for the verb, thus `check` with the verb finds it too.\n */\nexport interface WorldIssue {\n /** The code of the problem. `#NOEVAL`: no rung of the ladder gives an evaluator for the verb. */\n readonly code: \"#NOEVAL\";\n /** The keys of the kind from the root of the world. For a fallback kind, the keys of its namespace. */\n readonly kind: readonly Key[];\n /** `true` for the fallback kind of a namespace or of the world. */\n readonly fallback?: true;\n /** The verb without an evaluator. */\n readonly verb: string;\n readonly reason: string;\n}\n\n/** This function tells if a table of verbs has an entry for a verb. */\nfunction hasVerb(table: Readonly<Record<string, string>> | undefined, verb: string): boolean {\n return table !== undefined && Object.hasOwn(table, verb);\n}\n\n/**\n * This function checks the world of a machine before a document exists. It finds each kind that has no entry for a\n * verb of the list, when the world has no default for that verb (STATIC.COVERAGE). A document of such a kind gets no\n * evaluator for the verb, thus the check gives the same proof of coverage as a type system.\n *\n * The check visits each kind of each namespace, at each depth, and the fallback kind of each namespace and of the\n * world. It does not follow an alias, because the kind of an alias has its own place. The check reads only the world.\n *\n * @param machine - The machine, for its world.\n * @param verbs - The verbs that each kind of the language must answer, for example `eval`, `view` and `type`.\n * @returns One issue for each kind and verb without an evaluator. The order is the order of the world, then the\n * order of the verbs. The fallback kind of a namespace comes after the entries of that namespace.\n */\nexport function checkWorld(machine: Machine, verbs: readonly string[]): readonly WorldIssue[] {\n const world = machine.world;\n const open = verbs.filter((verb) => !hasVerb(world.defaults, verb));\n const out: WorldIssue[] = [];\n if (open.length === 0) return out;\n const visit = (kind: Kind, path: readonly Key[], fallback: boolean): void => {\n const text = path.join(\".\");\n const name = fallback ? (path.length === 0 ? \"the fallback kind of the world\" : `the fallback kind of ${text}`) : `the kind ${text}`;\n for (const verb of open) {\n if (hasVerb(kind.verbs, verb)) continue;\n const reason = `${name.charAt(0).toUpperCase()}${name.slice(1)} has no entry for the verb ${verb}, and the world has no default for it.`;\n out.push(fallback ? { code: \"#NOEVAL\", kind: path, fallback: true, verb, reason } : { code: \"#NOEVAL\", kind: path, verb, reason });\n }\n };\n // The set holds the namespaces on the way, thus a namespace that holds itself does not loop.\n const way = new Set<Namespace>();\n const entries = (kinds: Readonly<Record<string, WorldEntry>>, path: readonly Key[]): void => {\n for (const key of Object.keys(kinds)) {\n const entry = kinds[key];\n const here = [...path, key];\n if (isKind(entry)) visit(entry, here, false);\n else if (isNamespace(entry) && !way.has(entry)) {\n way.add(entry);\n entries(entry.kinds, here);\n if (entry.fallback !== undefined) visit(entry.fallback, here, true);\n way.delete(entry);\n }\n }\n };\n entries(world.kinds, []);\n if (world.fallback !== undefined) visit(world.fallback, [], true);\n return out;\n}\n\n/**\n * A runner under an evaluator in a check of a run. The run drives its steps without a wait, thus only a wait for an\n * effect of its runners fails (RUN.DRIVE-NESTED).\n */\ninterface Drive {\n /** The issue of the run when a step waits. */\n readonly issue: Issue;\n /** The index of the issue in the order of the document. */\n readonly index: number;\n /** The node of the runner for the pass of types. */\n readonly node: TypeNode | undefined;\n /** `true` when an effect of its runners can reach the host, and thus wait. */\n wait: boolean;\n}\n\n/** What the code of a document does with a wait: an evaluator stops it, and a runner passes it on. */\ntype Waits = boolean | Drive;\n\n/** The names that an equation of `down` sees (TREE.DOWN). */\nconst DOWN_NAMES: readonly string[] = /* @__PURE__ */ Object.freeze([\"child\", \"index\", \"prev\"]);\n\n/** The names that the term `combine` of a fold sees (TREE.FOLD). */\nconst FOLD_NAMES: readonly string[] = /* @__PURE__ */ Object.freeze([\"acc\", \"item\"]);\n\n/**\n * This function gives each equation of the tree contract of a kind, with the names that it sees (D42). An equation of\n * `equations`, a `unit` and a `default` see no names.\n */\nfunction equationsOf(kind: Kind): readonly { readonly label: string; readonly term: Json; readonly names: readonly string[] }[] {\n const tree = kind.tree;\n if (tree === undefined) return [];\n const out: { readonly label: string; readonly term: Json; readonly names: readonly string[] }[] = [];\n for (const [name, term] of Object.entries(tree.equations ?? {})) out.push({ label: `tree.equations.${name}`, term, names: [] });\n for (const [name, term] of Object.entries(tree.down ?? {})) out.push({ label: `tree.down.${name}`, term, names: DOWN_NAMES });\n for (const [name, declared] of Object.entries(tree.attributes ?? {})) {\n if (declared.fold !== undefined) {\n out.push({ label: `tree.attributes.${name}.fold.unit`, term: declared.fold.unit, names: [] });\n out.push({ label: `tree.attributes.${name}.fold.combine`, term: declared.fold.combine, names: FOLD_NAMES });\n }\n if (declared.default !== undefined) out.push({ label: `tree.attributes.${name}.default`, term: declared.default, names: [] });\n }\n return out;\n}\n\n/**\n * This function checks the equations of the tree contract of a kind, each with the names of its rung (TREE.DOWN-NAMES).\n * An equation evaluates without capabilities, thus a check with capabilities gives it none. Each issue gets the place\n * of the document of the kind, and its reason names the equation.\n */\nfunction equationIssues(machine: Machine, kind: Kind, kindText: string, options: CheckOptions, seen: Set<Kind>): readonly Issue[] {\n const of = equationType(kind);\n const out: Issue[] = [];\n for (const { label, term, names } of equationsOf(kind)) {\n const inner: CheckOptions = { names, ...(of === undefined ? {} : { declaredType: of }), ...(options.caps === undefined ? {} : { caps: [] }) };\n for (const issue of checkAll(machine, term, inner, undefined, seen)) {\n out.push({ code: issue.code, place: [], reason: `In the equation ${label} of the kind ${kindText}: ${issue.reason}` });\n }\n }\n return out;\n}\n\n/**\n * This function finds the issues of `check`. With a list of nodes, it also records each document that it visits for\n * the pass of types. It marks each document with an issue. The set `seen` holds the kinds whose equations the check\n * walked, thus it walks the equations of each kind one time.\n */\nfunction checkAll(machine: Machine, doc: unknown, options: CheckOptions, nodes: TypeNode[] | undefined, seen: Set<Kind> = new Set()): readonly Issue[] {\n const issues: Issue[] = [];\n const verb = options.verb ?? \"eval\";\n const indices = nodes === undefined ? undefined : new Map<DocVisit, number>();\n let current: TypeNode | undefined;\n const push = (issue: Issue): void => {\n issues.push(issue);\n if (current !== undefined) current.marked = true;\n };\n // The field effects declares eval, and verbEffects declares the other verbs (VERB.EFFECTS). An effect of a verb\n // without a declaration meets its test when it happens (RUN.CAP).\n const allowed = options.caps === undefined ? undefined : permitsOf(machine);\n // In a run, a part that can wait needs a parent that can wait (RUN.CAN-WAIT). The map tells for each document with\n // code if its code passes a wait on: false for an evaluator, true for a runner whose waits reach the driver of the\n // run, and a drive for a runner under an evaluator. A document without code fails before its parts, thus it is not\n // in the map.\n const waits = options.run === true ? new Map<DocVisit, Waits>() : undefined;\n const drives: Drive[] = [];\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 (nodes !== undefined && indices !== undefined) {\n current = { visit: v, bound: v instanceof Visit ? v.bound : [], expect: v instanceof Visit ? v.expect : undefined, children: [], evaluator: undefined, marked: false };\n const parent = v.parent === undefined ? undefined : indices.get(v.parent);\n if (parent !== undefined) nodes[parent]?.children.push(nodes.length);\n indices.set(v, nodes.length);\n nodes.push(current);\n }\n if (v.depth > maxDepth) {\n 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, verb, v.declared ? { declaredType: typeName(v.doc.type) } : {});\n if (answer.error === \"unknown-kind\") {\n push({ code: \"#KIND?\", place: v.place, reason: `The world has no kind ${typeName(v.doc.type)}.`, at: v.at });\n return \"skip\";\n }\n // The equations of a kind are code of the kind. The check walks them at the first document of the kind (D42).\n if (v.kind?.tree !== undefined && !seen.has(v.kind)) {\n seen.add(v.kind);\n for (const issue of equationIssues(machine, v.kind, typeName(v.doc.type), options, seen)) push({ ...issue, place: v.place, at: v.at });\n }\n const name = answer.evaluator;\n if (current !== undefined) current.evaluator = name;\n // A runner hides the evaluator of its name (MACHINE.RUNNER), as in the compilation of a plan.\n const runner = name !== undefined && has(machine.runners, name);\n const coded = name !== undefined && (runner || has(machine.evaluators, name));\n if (name === undefined || !coded) {\n 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) push({ code: \"#NAME?\", place: v.place, reason: known, at: v.at });\n }\n const caps = v.caps;\n const stated = verbDeclared(v, verb);\n const declared = stated ?? NO_EFFECTS;\n if (allowed !== undefined && caps !== undefined) {\n for (const kind of declared) {\n if (!allowed(caps, kind)) push({ code: \"#CAP!\", place: v.place, reason: capReason(v, kind, allowed), at: v.at });\n }\n }\n if (waits !== undefined && coded) {\n // The parent of the root is the driver of the run, and it can wait. An evaluator gives its parts no wait.\n const up = v.parent === undefined ? true : waits.get(v.parent);\n let chain: Waits = false;\n if (runner && up === false) {\n // The run drives a runner under an evaluator, and only a real wait fails (RUN.DRIVE-NESTED). Its issue goes in\n // here, in the order of the document, when an effect of its runners can wait.\n const issue: Issue = { code: \"#CALC!\", place: v.place, reason: waitedReason(typeName(v.doc.type)), at: v.at };\n chain = { issue, index: issues.length, node: current, wait: false };\n drives.push(chain);\n } else if (runner) {\n chain = up ?? true;\n }\n waits.set(v, chain);\n // A runner waits only for an effect that reaches the host (C6). A refused effect gives #CAP! without a wait. A\n // runner without a declaration for the verb can cause each effect, thus it can wait.\n if (typeof chain === \"object\" && !chain.wait) {\n const rule = allowed ?? permits;\n chain.wait = stated === undefined || declared.some((kind) => caps === undefined || rule(caps, kind));\n }\n // In a run, the host does each effect, thus an evaluator cannot cause one.\n const first = declared[0];\n if (!runner && first !== undefined) {\n push({ code: \"#CALC!\", place: v.place, reason: `The effect ${first.join(\".\")} needs a runner: in a run, the host does each effect.`, at: v.at });\n }\n }\n const isPath = isRef(v.doc);\n if (!isPath && v.typePath?.length === 1 && v.typePath[0] === \"ref\") {\n 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 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 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 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 // The resolution finds the walker with the same function, thus the check and a run agree (VERB.LADDER).\n if (walkerOf(machine, step) === undefined) {\n 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 // Without capabilities, a check of the run narrows the least authority, as effectsOf does. Thus a mask of a kind\n // removes the effects that cannot wait. The check of the capabilities stays off.\n ...(options.caps === undefined ? (waits === undefined ? {} : { caps: EACH }) : { caps: options.caps }),\n problem: (problem) => {\n issues.push({ code: problem.code, place: problem.place, reason: problem.reason, at: problem.at });\n // A value without the shape of its kind is a problem of the document that the walk visited last. A part that is\n // not a document has no visit, thus it marks nothing.\n if (problem.code === \"#VALUE!\" && current !== undefined) current.marked = true;\n },\n },\n );\n // The issue of each drive that can wait goes in at its place. The last drive goes in first, thus each index stays.\n for (let index = drives.length - 1; index >= 0; index -= 1) {\n const drive = drives[index] as Drive;\n if (!drive.wait) continue;\n issues.splice(drive.index, 0, drive.issue);\n if (drive.node !== undefined) drive.node.marked = true;\n }\n return issues;\n}\n","import { type Json, type Key, isEnvelope, isKey } from \"./doc.ts\";\nimport { type Kind, type LazyRule, type Side, type World, lookupKind } from \"./world.ts\";\nimport { answerOf } from \"./ladder.ts\";\nimport { pathMatches, splitParts } from \"./parts.ts\";\nimport { type Root, ROOTS, isRef } from \"./deref.ts\";\nimport type { Machine } from \"./evaluate.ts\";\nimport { type DocVisit, declaredEffects, walk } from \"./static.ts\";\n\n/**\n * One read of a document: a free reference, with its marks (FACTS.READS). A plan resolves the path of the reference\n * when it evaluates the reference. The static read covers each path that the plan resolves there (FACTS.SOUND). A\n * root that a kind declares in `reads` is a read too, with the path of the root alone.\n */\nexport interface StaticRead {\n /** The root of the path. */\n readonly root: Root;\n /** The keys after the root, up to the first step that is not a key. */\n readonly keys: readonly Key[];\n /**\n * `true` when each step after the root is a key. Then the plan resolves this path and no other. A step document,\n * for example `nearest`, makes it `false`: the plan resolves a path that starts with the keys.\n */\n readonly exact: boolean;\n /** `true` when only a lazy part reaches the reference. An evaluation can then give a value without this read (FACTS.LAZY). */\n readonly lazy: boolean;\n /** `true` when the position of the reference declares an address. The read gives what the path reaches, not its value. */\n readonly address: boolean;\n /** The path of the reference: its root and its steps. */\n readonly path: readonly Json[];\n /** The keys from the root document to 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}\n\n/** The static facts of one document (D24). They depend only on the document and the machine, not on a context. */\nexport interface DocFacts {\n /**\n * The free references, in the order of the document (FACTS.READS). A reference to a name that a kind binds is not\n * here. The roots that a kind declares in `reads` are here too, each one at the place of its document.\n */\n readonly reads: readonly StaticRead[];\n /** `\"run\"` when one kind of the document is on the run side (FACTS.SIDE). */\n readonly side: Side;\n /** The kinds of the effects that the contracts declare, as texts with dots, each one time (FACTS.EFFECTS). */\n readonly effects: readonly string[];\n /**\n * `true` when each kind of the document declares `pure`, and the document has no effect and is not volatile. Then\n * its result depends only on what its reads give (FACTS.PURE).\n */\n readonly pure: boolean;\n /** `true` when the result can change while each read gives the same thing, for example with a clock (FACTS.VOLATILE). */\n readonly volatile: boolean;\n /** The number of documents in the document: a hint of the cost of an evaluation. */\n readonly size: number;\n}\n\n/** The options of `factsOf`. */\nexport interface FactsOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The verb whose evaluators the facts describe, as in `prepare`. The default is `eval`. The contract of a kind\n * describes the code of `eval` only. For another verb, only the hook `facts` describes the code (FACTS.VERB).\n */\n readonly verb?: string;\n /**\n * This function tells if a read reaches a volatile value of the host, for example a function that reads a clock.\n * A read that it marks makes the document volatile (FACTS.VOLATILE).\n *\n * @param read - The read.\n * @returns `true` when the read reaches a volatile value.\n */\n readonly volatile?: (read: StaticRead) => boolean;\n}\n\n/** The lazy rules that cover each part: the rules of a document whose evaluator the contract does not describe. */\nconst EACH = \"each\";\n\n/** An empty list. One frozen list serves each empty list of the facts, thus a store of many facts keeps less (PLAN.LEAN). */\nconst NONE: readonly never[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function gives a list of the facts with no free room. A list that grows by `push` keeps room for more items,\n * thus a copy of a short list is smaller.\n */\nfunction tight<T>(list: readonly T[]): readonly T[] {\n return list.length === 0 ? NONE : list.slice();\n}\n\n/** What a document gives to its parts: its own lazy mark, and the lazy rules of its kind for the parts. */\ninterface Above {\n readonly lazy: boolean;\n readonly rules: readonly LazyRule[] | typeof EACH | undefined;\n /** The position of each part among the parts that a rule `after` covers. It is made at the first need. */\n positions?: Map<LazyRule, Map<string, number>>;\n}\n\n/**\n * This function gives the name of the evaluator that the ladder finds for a verb (VERB.LADDER). It also tells if\n * the contract of the kind describes that code. The contract describes the code of its kind for its verb `contract`.\n * An own entry for another evaluator has code that the contract does not describe.\n */\nfunction codeOf(\n world: World,\n own: Readonly<Record<string, string>> | undefined,\n kind: Kind,\n verb: string,\n contract: string,\n): { readonly name: string | undefined; readonly described: boolean } {\n const found = answerOf(world, own, kind, verb);\n if (verb !== contract) return { name: found?.name, described: false };\n if (found?.rung !== \"own\") return { name: found?.name, described: true };\n return { name: found.name, described: found.name === answerOf(world, undefined, kind, verb)?.name };\n}\n\n/** This function gives the position of a part among the parts that a rule covers, by the split of its document. */\nfunction positionOf(above: Above, parent: DocVisit, rule: LazyRule, slot: readonly Key[]): number {\n const positions = (above.positions ??= new Map());\n let table = positions.get(rule);\n if (table === undefined) {\n table = new Map();\n const split = splitParts(parent.kind?.parts, parent.doc.value);\n let count = 0;\n for (const part of split.ok ? split.parts : []) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(part.path, pattern))) continue;\n table.set(JSON.stringify(part.path), count);\n count += 1;\n }\n positions.set(rule, table);\n }\n return table.get(JSON.stringify(slot)) ?? 0;\n}\n\n/** This function tells if the lazy rules of a document cover one of its parts. */\nfunction partLazy(above: Above, parent: DocVisit, slot: readonly Key[]): boolean {\n const rules = above.rules;\n if (rules === undefined) return false;\n if (rules === EACH) return true;\n for (const rule of rules) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(slot, pattern))) continue;\n const after = rule.after ?? 0;\n if (after <= 0 || positionOf(above, parent, rule, slot) >= after) return true;\n }\n return false;\n}\n\n/**\n * This function gives the static facts of a document, for a schedule (R4 P2, D24). It walks the document one time,\n * by the contracts of its kinds:\n *\n * - `reads`: each free reference, with the root and the keys of its path. A read under a lazy part has the mark\n * `lazy`, for example a read in a branch of `if`. A read after a step document has `exact: false`. A kind that\n * declares `reads` adds a read of each of its roots at each document of the kind.\n * - `side` and `effects`: from the contract of each kind.\n * - `pure`: each kind declares `pure`, and the document has no effect and is not volatile.\n * - `volatile`: a kind, an operation or a step document declares `volatile`, or the host marks a read.\n *\n * The hook `facts` of the machine answers for a name that a fallback kind covers, for example an operation. Its\n * answer wins over the contract of the kind. The contract of a kind does not describe the evaluator of an own\n * entry. Thus a document with an own entry for another evaluator is not pure, and each of its parts is lazy. The\n * hook can still answer for that evaluator.\n *\n * The option `verb` names the verb whose code the facts describe (FACTS.VERB). A contract describes the code of\n * `eval`, thus the rule of an own entry applies to each document for another verb. The side and the effects come\n * from the contracts for each verb.\n *\n * A read is one resolution of its path. A reference that the resolution reaches and follows is a part of that read\n * (DEREF.COLLAPSE), not a separate read. The facts depend only on the document and the machine. Thus a host computes\n * them again only after an edit of the document or of the machine.\n *\n * @param machine - The world, the code and the hook `facts`.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, the verb and the volatile reads of the host.\n * @returns The facts.\n */\nexport function factsOf(machine: Machine, doc: unknown, options: FactsOptions = {}): DocFacts {\n const world = machine.world;\n const hook = machine.facts;\n const verb = options.verb ?? \"eval\";\n const reads: StaticRead[] = [];\n const effects: string[] = [];\n const above = new Map<DocVisit, Above>();\n let side: Side = \"derive\";\n let pure = true;\n let volatile = false;\n let size = 0;\n const note = (isPure: boolean | undefined, isVolatile: boolean | undefined): void => {\n if (isPure !== true) pure = false;\n if (isVolatile === true) volatile = true;\n };\n walk(\n world,\n doc,\n (v) => {\n size += 1;\n const up = v.parent === undefined ? undefined : above.get(v.parent);\n const lazy = up !== undefined && v.parent !== undefined && (up.lazy || partLazy(up, v.parent, v.slot));\n const kind = v.kind;\n if (kind === undefined) {\n // A kind that the world does not have gives #KIND?, and the walk does not visit its value.\n pure = false;\n above.set(v, { lazy, rules: undefined });\n return undefined;\n }\n const code = codeOf(world, v.declared ? undefined : v.doc.own, kind, verb, \"eval\");\n const answer = code.name === undefined ? undefined : hook?.(v.typePath ?? [], code.name);\n let roots: readonly Root[] | undefined;\n if (code.described) {\n note(answer?.pure ?? kind.pure, answer?.volatile ?? kind.volatile);\n above.set(v, { lazy, rules: answer?.lazy ?? kind.lazy });\n roots = answer?.reads ?? kind.reads;\n } else {\n // The contract of the kind does not describe this code. Only the hook can.\n note(answer?.pure, answer?.volatile);\n above.set(v, { lazy, rules: answer?.lazy ?? EACH });\n roots = answer?.reads;\n }\n // The code of the kind resolves each of these roots as a whole, at the place of its document (FACTS.KIND-READS).\n for (const root of roots ?? NONE) {\n const read: StaticRead = { root, keys: NONE, exact: true, lazy, address: false, path: [root], place: tight(v.place), at: tight(v.at) };\n reads.push(read);\n if (options.volatile?.(read) === true) volatile = true;\n }\n if (kind.side === \"run\") side = \"run\";\n // check and effectsOf read the declared effects with the same function (D27).\n for (const keys of declaredEffects(v)) {\n const text = keys.join(\".\");\n if (!effects.includes(text)) effects.push(text);\n }\n if (!isRef(v.doc)) return undefined;\n const path = v.doc.value;\n const root = path[0];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) return undefined;\n let exact = true;\n const keys: Key[] = [];\n for (let index = 1; index < path.length; index += 1) {\n const step = path[index];\n if (exact && isKey(step)) {\n keys.push(step);\n continue;\n }\n exact = false;\n // A step document runs the walker that the ladder finds for the verb step.\n const found = isEnvelope(step) ? lookupKind(world, step.type) : undefined;\n if (found?.ok !== true) {\n pure = false;\n continue;\n }\n const walker = codeOf(world, (step as { readonly own?: Readonly<Record<string, string>> }).own, found.kind, \"step\", \"step\");\n const stepAnswer = walker.name === undefined ? undefined : hook?.(found.path, walker.name);\n if (walker.described) note(stepAnswer?.pure ?? found.kind.pure, stepAnswer?.volatile ?? found.kind.volatile);\n else note(stepAnswer?.pure, stepAnswer?.volatile);\n }\n const first = path[1];\n // A reference to a name that a kind around it binds reads inside the document: it is not a read.\n if (root === \"names\" && isKey(first) && v.names.has(String(first))) return undefined;\n const read: StaticRead = { root: root as Root, keys: tight(keys), exact, lazy, address: v.address === true, path, place: tight(v.place), at: tight(v.at) };\n reads.push(read);\n if (options.volatile?.(read) === true) volatile = true;\n return undefined;\n },\n options.declaredType === undefined ? {} : { declaredType: options.declaredType },\n );\n return { reads: tight(reads), side, effects: tight(effects), pure: pure && !volatile && effects.length === 0 && side === \"derive\", volatile, size };\n}\n","import type { Key } from \"./doc.ts\";\nimport type { Cap } from \"./deref.ts\";\nimport { type Machine, capKeys, permits } from \"./evaluate.ts\";\nimport { type DocVisit, type Issue, declaredEffects, permitsOf, walk } from \"./static.ts\";\n\n/*\n * The effects that reach the host (R2 P3, D27). The contract of each kind declares the effects of its documents, and\n * its capability rules narrow the capabilities of its parts (D14). One walk narrows the capabilities as a run does. An\n * effect that the capabilities of its document do not permit fails in the run, thus it does not reach the host.\n *\n * A procedure value keeps the capabilities of the document that made it, as the closure of `fn` does. Thus its latent\n * effects are the effects of its body, under the capabilities of the body, and the fold needs no effect variables.\n */\n\n/** The options of `effectsOf`. */\nexport interface EffectsOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The capabilities at the root. With them, the result keeps only the effects that the rule of the machine permits at\n * their documents, as a run does (CAP.PERMITS). Without them, the root has each capability, and only the capability\n * rules of the kinds remove an effect.\n */\n readonly caps?: readonly Cap[];\n}\n\n/** Each capability: one capability with no keys. It permits each effect, because each kind starts with no keys (CAP.KEYS). */\nconst EACH: readonly Cap[] = /* @__PURE__ */ Object.freeze([[]]);\n\n/** One declared effect that can reach the host: its keys and the visit of its document. */\ninterface Reaching {\n readonly kind: readonly Key[];\n readonly visit: DocVisit;\n}\n\n/**\n * This function finds each declared effect that can reach the host, in the order of the document. It is the one\n * inference of `effectsOf` and `checkLatent`. `check` and `factsOf` read the same declarations (`declaredEffects`).\n */\nfunction reaching(machine: Machine, doc: unknown, options: EffectsOptions): readonly Reaching[] {\n const out: Reaching[] = [];\n // Without capabilities, the host has no rule to ask. The capability rules of the kinds still narrow each capability.\n const rule = options.caps === undefined ? permits : permitsOf(machine);\n walk(\n machine.world,\n doc,\n (v) => {\n const caps = v.caps ?? EACH;\n for (const kind of declaredEffects(v)) if (rule(caps, kind)) out.push({ kind, visit: v });\n return undefined;\n },\n { caps: options.caps ?? EACH, ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }) },\n );\n return out;\n}\n\n/**\n * This function gives the effects of a document that can reach the host (CAP.EFFECTS-OF, R2 P3). The result is the\n * effects that the contract of each kind declares, without the effects that the capability rules around them remove.\n * A rule `mask` removes each effect of its parts, and a rule `only` removes each effect outside its list.\n *\n * Without capabilities in the options, the result is the least authority of the document. A host that grants these\n * kinds as capabilities grants each effect that a run of the document can give it. With capabilities, the result keeps\n * only the effects that the rule of the machine permits at their documents.\n *\n * The result covers each effect that an evaluation or a run gives the host (CAP.EFFECTS-SOUND). A procedure value keeps\n * the capabilities of the document that made it, thus the effects of its body count at the body (CAP.LATENT). The\n * contract describes the code of its kind. The code of an own entry for another evaluator is outside the result.\n *\n * @param machine - The world and its contracts, and the hook `permits`.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value and the capabilities at the root.\n * @returns The kinds of the effects, as texts with dots, each one time, in the order of the document.\n */\nexport function effectsOf(machine: Machine, doc: unknown, options: EffectsOptions = {}): readonly string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const { kind } of reaching(machine, doc, options)) {\n const text = kind.join(\".\");\n if (seen.has(text)) continue;\n seen.add(text);\n out.push(text);\n }\n return out;\n}\n\n/**\n * This function compares the latent effects that a procedure declares with the body of the procedure (CAP.LATENT). A\n * procedure entry is a kind whose code evaluates the document of a procedure. Its field `effects` declares the latent\n * effects: the effects that a call of the procedure can cause. `check` tests each call against this declaration.\n *\n * The function gives a `#CAP!` for each effect of the body that can reach the host and that the declaration does not\n * permit. An effect that a kind in the body masks fails in the body, thus it is not a latent effect.\n *\n * @param machine - The world and its contracts.\n * @param declared - The latent effects that the procedure declares, for example the field `effects` of its kind.\n * @param body - The document of the procedure, as JSON.\n * @param options - The type of a bare root value.\n * @returns The issues, in the order of the body.\n */\nexport function checkLatent(machine: Machine, declared: readonly Cap[], body: unknown, options: Omit<EffectsOptions, \"caps\"> = {}): readonly Issue[] {\n const issues: Issue[] = [];\n const list = declared.map((cap) => capKeys(cap).join(\".\")).join(\", \");\n const head = declared.length === 0 ? \"The procedure declares no latent effect\" : `The procedure declares the latent effects ${list}`;\n for (const { kind, visit } of reaching(machine, body, options.declaredType === undefined ? {} : { declaredType: options.declaredType })) {\n if (permits(declared, kind)) continue;\n issues.push({ code: \"#CAP!\", place: visit.place, reason: `${head}, and its body can cause the effect ${kind.join(\".\")} here.`, at: visit.at });\n }\n return issues;\n}\n","import { type Json, isEnvelope, isRecord } from \"./doc.ts\";\nimport { type Result, describe, fail, ok } from \"./errors.ts\";\nimport { type Machine, makeContext, prepare } from \"./evaluate.ts\";\nimport { type Domain, type DomainCodec, domainOf, member } from \"./types.ts\";\n\n/*\n * The codec of the values that JSON cannot write (K140, D40). A document holds such a value as a standard extension:\n * `ext.number` for `NaN`, an infinity and `-0`, `ext.undefined` for `undefined`, and `ext.domain` for a member of a\n * domain with a codec. Thus the same value has the same document in each language (D12).\n */\n\n/** The domains of a machine, by their names. */\ntype Domains = Readonly<Record<string, Domain>> | undefined;\n\n/** This function gives the codec of a domain, or `undefined` when the domain has no codec. */\nfunction codecOf(domain: Domain): DomainCodec | undefined {\n const codec: unknown = domain.codec;\n if (typeof codec !== \"object\" || codec === null) return undefined;\n const { encode, decode } = codec as Partial<DomainCodec>;\n return typeof encode === \"function\" && typeof decode === \"function\" ? (codec as DomainCodec) : undefined;\n}\n\n/**\n * This function reads the value of an extension `ext.domain` (EXT.DOMAIN). The value is a record with only the text\n * `domain` and the JSON `data`. The codec of the named domain reads the data, and the result must be a member of the\n * domain.\n *\n * @param data - The value of the extension document.\n * @param domains - The domains of the machine.\n * @returns The member, `#NAME?` for a domain without a codec, or `#VALUE!` for data that the codec cannot read.\n */\nexport function decodeDomain(data: Json, domains: Domains): Result {\n if (!isRecord(data) || typeof data[\"domain\"] !== \"string\" || !Object.hasOwn(data, \"data\") || Object.keys(data).length !== 2) {\n return fail(\"#VALUE!\", \"The value of ext.domain is a record with only the text domain and the data.\");\n }\n const name = data[\"domain\"];\n const domain = domainOf(name, domains);\n if (domain === undefined) return fail(\"#NAME?\", `The machine has no domain ${name}.`);\n const codec = codecOf(domain);\n if (codec === undefined) return fail(\"#NAME?\", `The domain ${name} has no codec.`);\n let value: unknown;\n try {\n value = codec.decode(data[\"data\"] as Json);\n } catch (error) {\n return fail(\"#VALUE!\", `The codec of the domain ${name} cannot read the data: ${describe(error)}`, { cause: error });\n }\n if (!member(value, name, domains)) return fail(\"#VALUE!\", `The codec of the domain ${name} gives a value that is not a member of the domain.`);\n return ok(value);\n}\n\n/**\n * This function gives the static type of an extension `ext.domain`: the name of its domain when that domain has a\n * codec. A run then gives a member of the domain or an error, because `decodeDomain` tests the membership.\n *\n * @param data - The value of the extension document.\n * @param domains - The domains of the machine.\n * @returns The name of the domain, or `unknown`.\n */\nexport function domainTypeOf(data: unknown, domains: Domains): string {\n if (!isRecord(data) || typeof data[\"domain\"] !== \"string\") return \"unknown\";\n const domain = domainOf(data[\"domain\"], domains);\n return domain !== undefined && codecOf(domain) !== undefined ? data[\"domain\"] : \"unknown\";\n}\n\n/** This function sets an own data property. Only the key `__proto__` needs `defineProperty`. */\nfunction setOwn(target: Record<string, Json>, key: string, value: Json): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\n/** The state of one call of `encodeValue`. */\ninterface Encoder {\n readonly domains: Domains;\n /** The domains with a codec, in the order of their names. */\n readonly codecs: readonly (readonly [string, DomainCodec])[];\n /** The answer of `isJson` for each container that it examined. */\n readonly json: WeakMap<object, boolean>;\n /** The containers on the way from the root to the value. A container on the way again is a cycle. */\n readonly open: Set<object>;\n}\n\n/**\n * This function tells if JSON writes a value exactly. Such a value is a finite number other than `-0`, a text, a truth\n * value, `null`, or a container of such values.\n */\nfunction isJson(value: unknown, encoder: Encoder): boolean {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value) && !Object.is(value, -0);\n const list = Array.isArray(value);\n if (!list && !isRecord(value)) return false;\n const container = value as object;\n const known = encoder.json.get(container);\n if (known !== undefined) return known;\n // A cycle is not JSON. The mark stays false until each item is JSON.\n encoder.json.set(container, false);\n let all = true;\n if (list) {\n const items = value as readonly unknown[];\n for (let index = 0; index < items.length && all; index += 1) all = isJson(items[index], encoder);\n } else {\n const record = value as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(record)) {\n if (!isJson(record[key], encoder)) {\n all = false;\n break;\n }\n }\n }\n encoder.json.set(container, all);\n return all;\n}\n\n/** This function gives the text of a number that JSON cannot write, for `ext.number`. */\nfunction numberText(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Number.POSITIVE_INFINITY) return \"Infinity\";\n if (value === Number.NEGATIVE_INFINITY) return \"-Infinity\";\n return \"-0\";\n}\n\n/** This function gives the term document of a value in one call of `encodeValue`. */\nfunction encodeTerm(value: unknown, encoder: Encoder): Json {\n if (isJson(value, encoder)) return isEnvelope(value) ? { type: \"lit\", value: value as Json } : (value as Json);\n if (value === undefined) return { type: [\"ext\", \"undefined\"], value: null };\n if (typeof value === \"number\") return { type: [\"ext\", \"number\"], value: numberText(value) };\n for (const [name, codec] of encoder.codecs) {\n if (member(value, name, encoder.domains)) return { type: [\"ext\", \"domain\"], value: { domain: name, data: codec.encode(value) } };\n }\n if (!Array.isArray(value) && !isRecord(value)) {\n throw new TypeError(`encodeValue cannot write the value ${describe(value)}: no domain of the machine with a codec holds it.`);\n }\n if (encoder.open.has(value)) throw new TypeError(\"encodeValue cannot write a value with a cycle.\");\n encoder.open.add(value);\n let out: Json;\n if (Array.isArray(value)) {\n // `Array.from` visits each hole of a sparse list as `undefined`.\n out = { type: \"list\", value: Array.from(value as readonly unknown[], (item) => encodeTerm(item, encoder)) };\n } else {\n const fields: Record<string, Json> = {};\n const record = value as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(record)) setOwn(fields, key, encodeTerm(record[key], encoder));\n out = { type: \"record\", value: fields };\n }\n encoder.open.delete(value);\n return out;\n}\n\n/**\n * This function writes a host value as a term document of the formula kit (EXT.ENCODE, D40). Thus the same value has\n * the same document in each language (D12).\n *\n * - A value that JSON writes exactly stays as it is. A literal with the shape of an envelope goes into `lit`.\n * - `NaN`, an infinity and `-0` become `ext.number`, and `undefined` becomes `ext.undefined`.\n * - A member of a domain with a codec becomes `ext.domain`. The domains go in the order of their names.\n * - A list or a plain record with such a value becomes the construct `list` or `record`.\n *\n * @param machine - The machine, or only its domains.\n * @param value - The host value.\n * @returns The document. `decodeValue` gives the value again (EXT.ROUNDTRIP).\n * @throws {TypeError} The value has a cycle, or it is not JSON and no domain with a codec holds it.\n */\nexport function encodeValue(machine: Pick<Machine, \"domains\">, value: unknown): Json {\n const domains = machine.domains;\n const codecs: (readonly [string, DomainCodec])[] = [];\n if (domains !== undefined) {\n for (const name of Object.keys(domains).sort()) {\n const domain = domainOf(name, domains);\n const codec = domain === undefined ? undefined : codecOf(domain);\n if (codec !== undefined) codecs.push([name, codec]);\n }\n }\n return encodeTerm(value, { domains, codecs, json: new WeakMap(), open: new Set() });\n}\n\n/**\n * This function reads a document of `encodeValue` again: it evaluates the document as a term, in an empty context.\n * A bare root value is a literal.\n *\n * @param machine - A machine of the formula kit, with the domains of the document.\n * @param doc - The document.\n * @returns The value, or the error of the evaluation.\n */\nexport function decodeValue(machine: Machine, doc: unknown): Result {\n return prepare(machine, doc, { declaredType: \"lit\" }).evaluate(makeContext());\n}\n","import { type Json, type Key, docEquals, isKey, isRecord } from \"./doc.ts\";\nimport type { Kind, KindFacts, LazyRule, WorldEntry } from \"./world.ts\";\nimport { type CompiledPath, type Context, type Resolution, compilePath, valueOfThing } from \"./deref.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, thrown } from \"./errors.ts\";\nimport { type Code, type CompileInput, type CompiledEvaluator, type CompiledPart, type Evaluator, type Machine, type Runtime, resolveCompiled } from \"./evaluate.ts\";\nimport { type MachinePart, mergeMachines } from \"./merge.ts\";\nimport { type Domain, type ValueType, HEADER_KEYS, STD_DOMAINS, callable, fieldOf, fits, fnOf, holdsEnvelope, isPrecise, isUnknown, itemOf, join, member, stepType, typeText } from \"./types.ts\";\nimport type { TypeInput, TypeRule } from \"./typing.ts\";\nimport { decodeDomain, domainTypeOf } from \"./codec.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/**\n * The code of an extension: it gives the value of the data of an extension document, in the context of the document.\n * It also gets the domains of the machine, for the codecs of `ext.domain` (D40).\n */\nexport type ExtFn = (data: Json, context: Context, domains?: Readonly<Record<string, Domain>>) => 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`, `ext.number` and\n * `ext.domain`.\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 * - `pure`: the pure operations, for `factsOf` (D24). `true` names each operation that is not volatile. The default\n * names no operation.\n * - `pureExt`: the pure extensions of `ext`, by their name, for `factsOf` and the folds of a plan (PLAN.FOLD, D47).\n * The default names no extension. A standard extension is pure without a name here.\n * - `volatile`: the operations whose results can change while their arguments stay the same, for example a clock.\n * - `sigs`: the signatures of the operations, by their name, for a check of types (TYPE.SIGNATURE). A list gives\n * overloads. An operation without a signature takes and gives `unknown` (TYPE.GRADUAL).\n *\n * A check of types trusts the signatures. Each operation must give a member of the result of each signature that\n * its arguments match. The hook `check` must keep each result in that type.\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 readonly pure?: true | readonly string[];\n readonly pureExt?: readonly string[];\n readonly volatile?: readonly string[];\n readonly sigs?: Readonly<Record<string, Signature | readonly Signature[]>> | ((name: string) => Signature | readonly Signature[] | undefined);\n}\n\n/**\n * The signature of an operation: the value types of its parameters and of its result (TYPE.SIGNATURE). A parameter at\n * the end of `params` is optional when `undefined` is a member of its type, for example `unknown`. A later version can add a key, for example the type that a\n * true result proves.\n */\nexport interface Signature {\n /** The types of the parameters, in order. */\n readonly params: readonly ValueType[];\n /** The type of each argument after the parameters. Without it, the operation takes no more arguments. */\n readonly rest?: ValueType;\n /** The type of the result. */\n readonly to: ValueType;\n}\n\n/** The mark of a field that the profile leaves out of a record. */\nconst SKIPPED: unique symbol = /* @__PURE__ */ 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 = /* @__PURE__ */ 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/**\n * The standard extensions: the values that JSON cannot write. `ext.domain` reads a member of a domain through the\n * codec of the domain (EXT.DOMAIN, D40).\n */\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 domain: (data, _context, domains) => decodeDomain(data, domains),\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\" }, pure: true, summary: LIT_SUMMARY },\n ref: { verbs: { eval: \"formula.ref\" }, pure: true, 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\" }, pure: true, summary: \"A record: each field is a term.\" },\n list: { verbs: { eval: \"formula.list\" }, parts: terms, pure: true, 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 pure: true,\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 // The body evaluates only when something calls the function.\n pure: true,\n lazy: [{ 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 // A host function in a name is a value. When it is volatile, the host marks its read (FACTS.VOLATILE).\n pure: true,\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 pure: true,\n lazy: [{ in: [[\"then\"], [\"else\"]] }],\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n and: { verbs: { eval: \"formula.and\" }, parts: terms, pure: true, lazy: [{ after: 1 }], summary: \"True when each term is true. It stops at the first false term.\" },\n or: { verbs: { eval: \"formula.or\" }, parts: terms, pure: true, lazy: [{ after: 1 }], 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 gives the type of a value of a profile: the value itself as `one`. `undefined` gives the base type\n * `undefined`, because JSON and thus `one` cannot hold it (D48). A function gives `unknown`.\n */\nfunction valueType(value: unknown): ValueType {\n if (value === undefined) return \"undefined\";\n return typeof value === \"function\" ? \"unknown\" : { one: [value as Json] };\n}\n\n/** This function tells if a value has the form of a signature: a record with `params` as a list, and `to`. */\nfunction isSignature(value: unknown): value is Signature {\n return typeof value === \"object\" && value !== null && Array.isArray((value as { readonly params?: unknown }).params) && Object.hasOwn(value, \"to\");\n}\n\n/** This function gives the text of a signature, for the reason of an issue. */\nfunction signatureText(sig: Signature): string {\n const params = sig.params.map(typeText);\n if (sig.rest !== undefined) params.push(`...${typeText(sig.rest)}`);\n return `(${params.join(\", \")}) => ${typeText(sig.to)}`;\n}\n\nfunction argumentsText(count: number): string {\n return `${count} argument${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** This function gives the text of a list of names for a reason, for example `a, b and c`. */\nfunction listText(names: readonly string[]): string {\n return names.length < 2 ? names.join(\"\") : `${names.slice(0, -1).join(\", \")} and ${names[names.length - 1] as string}`;\n}\n\n/**\n * This function tells if a signature takes a count of arguments. A parameter at the end is optional when its type\n * holds `undefined`, because a missing argument is `undefined`. `unknown` and the base type `undefined` hold it.\n *\n * @returns `undefined` when the number is correct, or else the text of the numbers that the signature takes.\n */\nfunction arityOf(sig: Signature, count: number, domains: Machine[\"domains\"]): string | undefined {\n let least = sig.params.length;\n while (least > 0 && member(undefined, sig.params[least - 1] as ValueType, domains)) least -= 1;\n const most = sig.rest === undefined ? sig.params.length : Number.POSITIVE_INFINITY;\n if (count >= least && count <= most) return undefined;\n if (most === Number.POSITIVE_INFINITY) return `at least ${argumentsText(least)}`;\n return least === most ? argumentsText(most) : `${least} to ${argumentsText(most)}`;\n}\n\n/** This function gives the parameters of a document of `fn`: the texts of its list `params`. */\nfunction paramsOf(value: unknown): readonly string[] {\n const params = isRecord(value) ? value[\"params\"] : undefined;\n return Array.isArray(params) ? params.filter((param): param is string => typeof param === \"string\") : [];\n}\n\n/**\n * This function makes the type rules of the formula kit for one profile (TYPE.SYNTH, D25). Each evaluator of the kit\n * holds its rule. The rules read the rules of the profile that change a type: `truthy`, `logic`, `otherwise`, `omit`\n * and `sigs`.\n */\nfunction formulaTypes(profile: FormulaProfile): Readonly<Record<string, TypeRule>> {\n // Only the default truth accepts nothing but a truth value. A truth of the profile accepts each value.\n const truth: ValueType | undefined = profile.truthy === undefined ? \"bool\" : undefined;\n const logicValue = profile.logic === \"value\";\n const otherwise = Object.hasOwn(profile, \"otherwise\") ? valueType(profile.otherwise) : \"null\";\n const lookup = (name: string): readonly unknown[] | undefined => {\n const sigs = profile.sigs;\n if (sigs === undefined) return undefined;\n let found: unknown;\n if (typeof sigs === \"function\") {\n try {\n found = sigs(name);\n } catch {\n return undefined;\n }\n } else {\n found = Object.hasOwn(sigs, name) ? sigs[name] : undefined;\n }\n if (found === undefined) return undefined;\n return Array.isArray(found) ? found : [found];\n };\n const nameOf = (input: TypeInput): string => input.typePath.slice(1).join(\".\");\n /** The signatures of an operation. Each type of a signature is a contract, thus the check examines it one time. */\n const signatures = (input: TypeInput): { readonly sigs: readonly Signature[]; readonly bad: boolean } | undefined => {\n const name = nameOf(input);\n const raw = lookup(name);\n if (raw === undefined) return undefined;\n const sigs: Signature[] = [];\n for (const sig of raw) {\n if (!isSignature(sig)) continue;\n sig.params.forEach((param, index) => input.contract(param, `parameter ${index + 1} of a signature of ops.${name}`));\n if (sig.rest !== undefined) input.contract(sig.rest, `rest parameter of a signature of ops.${name}`);\n input.contract(sig.to, `result of a signature of ops.${name}`);\n sigs.push(sig);\n }\n return { sigs, bad: sigs.length !== raw.length };\n };\n const logic = (word: \"and\" | \"or\"): TypeRule => ({\n part: (_input, path) => (truth === undefined ? {} : { expect: truth, what: `term ${Number(path[0]) + 1} of ${word}` }),\n synth: (input) => {\n if (!logicValue) return \"bool\";\n // With the logic \"value\", the result is the term that decided, or the last term.\n if (input.paths.length === 0) return { one: [word === \"and\"] };\n return input.paths.reduce<ValueType>((type, path) => join(type, input.typeOf(path), input.machine.domains), \"never\");\n },\n });\n\n return {\n \"formula.lit\": { synth: (input) => valueType(input.doc.value) },\n\n \"formula.ref\": {\n synth: (input, report) => {\n const path = input.doc.value;\n // An address gives a thing, not a value. The check gives #VALUE! for a path that is not a list.\n if (input.address || !Array.isArray(path) || path.length === 0) return \"unknown\";\n const domains = input.machine.domains;\n const plain = input.machine.plain === true;\n let type: ValueType;\n let start: number;\n if (path[0] === \"names\") {\n const name = path[1];\n // The record of the names holds the error of a failed binding, thus the path [\"names\"] has no type. A record\n // of names with only the keys of a header is an envelope, and a path into it asks the ladder.\n if (!isKey(name) || (!plain && HEADER_KEYS.has(String(name)))) return \"unknown\";\n type = input.nameType(String(name)) ?? \"unknown\";\n start = 2;\n } else {\n type = input.rootType(String(path[0]));\n start = 1;\n }\n for (let index = start; ; index += 1) {\n // A path follows a reference document that it reaches, and it asks the ladder for a step into an envelope.\n if (isUnknown(type, domains) || (!plain && holdsEnvelope(type, domains))) return \"unknown\";\n if (index >= path.length) return type;\n const step = path[index];\n // A step document gives what its walker reaches. It has no type yet.\n if (!isKey(step)) return \"unknown\";\n const next = stepType(type, step, domains, input.contract);\n if (\"missing\" in next) {\n const fields = next.missing.length === 0 ? \"\" : ` Its fields are ${listText(next.missing)}.`;\n report({ reason: `The value at ${path.slice(0, index).map(String).join(\".\")} has no field ${String(step)}.${fields}` });\n return \"unknown\";\n }\n type = next.type;\n }\n },\n },\n\n \"formula.record\": {\n part: (input, path) => {\n const want = fieldOf(input.expected, String(path[0]), input.machine.domains);\n return want === undefined ? {} : { expect: want, what: `field ${String(path[0])} of the record` };\n },\n synth: (input) => {\n const fields: Record<string, ValueType> = {};\n for (const path of input.paths) setOwn(fields, String(path[0]), input.typeOf(path));\n const keys = Object.keys(fields);\n // A profile with omit can leave out each field, thus each field is optional.\n return { record: fields, ...(profile.omit !== undefined && keys.length > 0 ? { optional: keys } : {}), closed: true };\n },\n },\n\n \"formula.list\": {\n part: (input, path) => {\n const want = itemOf(input.expected, input.machine.domains);\n return want === undefined ? {} : { expect: want, what: `item ${Number(path[0]) + 1} of the list` };\n },\n synth: (input) => ({ list: input.paths.reduce<ValueType>((type, path) => join(type, input.typeOf(path), input.machine.domains), \"never\") }),\n },\n\n \"formula.let\": {\n part: (input, path) => {\n if (path[0] !== \"body\") return {};\n // The scope rule keysAt puts the bindings first, thus their types are known here.\n const names: Record<string, ValueType> = {};\n for (const each of input.paths) if (each[0] === \"bind\" && each.length === 2) setOwn(names, String(each[1]), input.typeOf(each));\n return { names, ...(isUnknown(input.expected, input.machine.domains) ? {} : { expect: input.expected, what: \"body of let\" }) };\n },\n synth: (input) => input.typeOf([\"body\"]),\n },\n\n \"formula.fn\": {\n part: (input, path) => {\n if (path[0] !== \"body\") return {};\n // An expected function type gives the types of the parameters. Without it, each parameter is unknown.\n const want = fnOf(input.expected, input.machine.domains);\n const names: Record<string, ValueType> = {};\n paramsOf(input.doc.value).forEach((name, index) => setOwn(names, name, want?.params[index] ?? \"unknown\"));\n return { names, ...(want === undefined || isUnknown(want.to, input.machine.domains) ? {} : { expect: want.to, what: \"body of fn\" }) };\n },\n synth: (input) => {\n const want = fnOf(input.expected, input.machine.domains);\n return { fn: paramsOf(input.doc.value).map((_name, index) => want?.params[index] ?? \"unknown\"), to: input.typeOf([\"body\"]) };\n },\n },\n\n \"formula.call\": {\n synth: (input, report) => {\n const domains = input.machine.domains;\n const target = input.typeOf([\"fn\"]);\n if (isUnknown(target, domains)) return \"unknown\";\n const want = fnOf(target, domains);\n if (want === undefined) {\n if (callable(target, domains)) return \"unknown\";\n report({ path: [\"fn\"], reason: `The fn of call has the type ${typeText(target)}. It must give a function.`, found: target });\n return \"unknown\";\n }\n const args = input.paths.filter((path) => path[0] === \"args\");\n for (const path of args) {\n const index = Number(path[1]);\n const param = want.params[index];\n // The function does not read an argument after its parameters.\n if (param === undefined) continue;\n const found = input.typeOf(path);\n if (!fits(found, param, domains)) {\n report({ path, reason: `The argument ${index + 1} of the call has the type ${typeText(found)}. The function expects the type ${typeText(param)}.`, expected: param, found });\n }\n }\n const missing = want.params.findIndex((param, index) => index >= args.length && !isUnknown(param, domains));\n if (missing !== -1) {\n const param = want.params[missing] as ValueType;\n report({ reason: `The call gives ${argumentsText(args.length)}. The function expects the type ${typeText(param)} for the argument ${missing + 1}.`, expected: param });\n }\n return want.to;\n },\n },\n\n \"formula.if\": {\n part: (input, path) => {\n if (path[0] === \"test\") return truth === undefined ? {} : { expect: truth, what: \"test of if\" };\n return isUnknown(input.expected, input.machine.domains) ? {} : { expect: input.expected, what: `${String(path[0])} branch of if` };\n },\n synth: (input) => {\n const value = input.doc.value;\n const other = isRecord(value) && Object.hasOwn(value, \"else\") ? input.typeOf([\"else\"]) : otherwise;\n return join(input.typeOf([\"then\"]), other, input.machine.domains);\n },\n },\n\n \"formula.and\": logic(\"and\"),\n \"formula.or\": logic(\"or\"),\n\n \"formula.op\": {\n part: (input, path) => {\n const read = signatures(input);\n // Only one signature gives the types of the arguments before their check. Overloads select after it.\n if (read === undefined || read.sigs.length !== 1) return {};\n const sig = read.sigs[0] as Signature;\n const index = Number(path[0]);\n const want = index < sig.params.length ? sig.params[index] : sig.rest;\n return want === undefined ? {} : { expect: want, what: `argument ${index + 1} of ops.${nameOf(input)}` };\n },\n synth: (input, report) => {\n const read = signatures(input);\n if (read === undefined) return \"unknown\";\n const name = nameOf(input);\n const domains = input.machine.domains;\n if (read.bad) report({ reason: `A signature of ops.${name} is not a record with params and to. The check does not read it.` });\n const { sigs } = read;\n if (sigs.length === 0) return \"unknown\";\n const args = input.paths.map((path) => input.typeOf(path));\n if (sigs.length === 1) {\n const sig = sigs[0] as Signature;\n const takes = arityOf(sig, args.length, domains);\n if (takes !== undefined) report({ reason: `The operation ops.${name} takes ${takes}. It gets ${args.length}.` });\n return sig.to;\n }\n const paramAt = (sig: Signature, index: number): ValueType => sig.params[index] ?? sig.rest ?? \"unknown\";\n const fitting = sigs.filter((sig) => arityOf(sig, args.length, domains) === undefined && args.every((arg, index) => fits(arg, paramAt(sig, index), domains)));\n if (fitting.length === 0) {\n const given = args.map(typeText).join(\", \");\n report({ reason: `No signature of ops.${name} fits the arguments (${given}). The signatures are ${sigs.map(signatureText).join(\" and \")}.` });\n return \"unknown\";\n }\n const first = fitting[0] as Signature;\n // Precise arguments are members of the first signature that fits. An argument with unknown can match a later one.\n if (fitting.length === 1 || args.every((arg) => isPrecise(arg, domains))) return first.to;\n return fitting.every((sig) => docEquals(sig.to, first.to)) ? first.to : \"unknown\";\n },\n },\n\n \"formula.ext\": {\n synth: (input) => {\n const name = nameOf(input);\n const own = profile.ext !== undefined && Object.hasOwn(profile.ext, name);\n if (own) return \"unknown\";\n // The standard extensions give the values that JSON cannot write, thus each has a base type (D48).\n if (name === \"undefined\") return \"undefined\";\n if (name === \"number\") return \"number\";\n return name === \"domain\" ? domainTypeOf(input.doc.value, input.machine.domains) : \"unknown\";\n },\n },\n };\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. Each evaluator also holds its type rule, for a check of types (TYPE.SYNTH).\n *\n * Equal profiles give the same evaluator objects (COMPOSE.UNIFY, D46). Thus two machines of one profile merge without\n * a conflict. Each call gives a new record. Each evaluator object is frozen, because many machines can share it.\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 return { ...kitOf(profile).evaluators };\n}\n\n/** This function makes new evaluators of the formula kit for the fields of one profile. */\nfunction makeEvaluators(profile: FormulaProfile): Readonly<Record<string, Evaluator>> {\n const evaluators = formulaCode(profile);\n const types = formulaTypes(profile);\n const out: Record<string, Evaluator> = {};\n for (const name of Object.keys(evaluators)) {\n const evaluator = evaluators[name] as CompiledEvaluator;\n const type = Object.hasOwn(types, name) ? types[name] : undefined;\n out[name] = Object.freeze(type === undefined ? evaluator : { compile: evaluator.compile, type });\n }\n return Object.freeze(out);\n}\n\n/** The keys of a profile that the kit reads. The kit ignores each other key. */\nconst PROFILE_KEYS = /* @__PURE__ */ Object.freeze([\n \"ops\",\n \"lazy\",\n \"ext\",\n \"truthy\",\n \"otherwise\",\n \"logic\",\n \"omit\",\n \"missing\",\n \"check\",\n \"combine\",\n \"pure\",\n \"pureExt\",\n \"volatile\",\n \"sigs\",\n] as const satisfies readonly (keyof FormulaProfile)[]);\n\n/** The evaluators and the hooks of the formula kit for one profile, with the fields that made them. */\ninterface Kit {\n readonly fields: FormulaProfile;\n readonly evaluators: Readonly<Record<string, Evaluator>>;\n readonly known: (path: readonly Key[], evaluator: string) => true | string;\n readonly facts: (path: readonly Key[], code: string) => KindFacts | undefined;\n}\n\n/** The number of recent kits that a profile in a new object can find by its fields. */\nconst RECENT_KITS = 16;\n\n/** The kit of each profile object. A kit goes when its profile object goes. */\nconst kitsByProfile = /* @__PURE__ */ new WeakMap<object, Kit>();\n\n/** The recent kits, the most recent first. The list holds `RECENT_KITS` kits or fewer. */\nconst recentKits: Kit[] = [];\n\n/**\n * This function gives the canonical form of a profile: a frozen record of the fields that the kit reads. A field\n * with the value `undefined` is absent, but `otherwise` is present when the profile has it as an own key. A list\n * is a frozen copy. Each other value stays the same object.\n */\nfunction fieldsOf(profile: FormulaProfile): FormulaProfile {\n const out: Record<string, unknown> = {};\n for (const key of PROFILE_KEYS) {\n if (key === \"otherwise\" ? !Object.hasOwn(profile, key) : profile[key] === undefined) continue;\n const value: unknown = profile[key];\n out[key] = Array.isArray(value) ? Object.freeze([...(value as unknown[])]) : value;\n }\n return Object.freeze(out);\n}\n\n/**\n * This function tells if two canonical forms are equal. They must have the same keys. A function, a record and a host\n * value are equal only to themselves. Two lists are equal when their items are the same, in order.\n */\nfunction sameFields(a: FormulaProfile, b: FormulaProfile): boolean {\n const left = a as Readonly<Record<string, unknown>>;\n const right = b as Readonly<Record<string, unknown>>;\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) return false;\n return keys.every((key) => {\n if (!Object.hasOwn(right, key)) return false;\n const x = left[key];\n const y = right[key];\n if (Object.is(x, y)) return true;\n return Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((item, index) => Object.is(item, y[index]));\n });\n}\n\n/**\n * This function gives the kit of a profile (D46). A profile object that the kit knows, with the same fields, gives its\n * kit. Then a recent kit with equal fields serves a new profile object. Else the function makes a new kit from the\n * canonical form. Thus a later change of a field of the profile object gives a new kit, and an old kit does not change.\n */\nfunction kitOf(profile: FormulaProfile): Kit {\n const fields = fieldsOf(profile);\n const known = kitsByProfile.get(profile);\n if (known !== undefined && sameFields(known.fields, fields)) return known;\n const index = recentKits.findIndex((kit) => sameFields(kit.fields, fields));\n let kit: Kit;\n if (index >= 0) {\n kit = recentKits[index] as Kit;\n recentKits.splice(index, 1);\n } else {\n const hook = makeKnown(fields);\n kit = { fields, evaluators: makeEvaluators(fields), known: hook, facts: makeFacts(fields, hook) };\n }\n recentKits.unshift(kit);\n if (recentKits.length > RECENT_KITS) recentKits.length = RECENT_KITS;\n kitsByProfile.set(profile, kit);\n return kit;\n}\n\n/** This function makes the code of the evaluators of the formula kit, without their type rules. */\nfunction formulaCode(profile: FormulaProfile): Readonly<Record<string, CompiledEvaluator>> {\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 /*\n * The code of a reference (PLAN.LEAN). The helpers below serve each reference of the language. Each code keeps only\n * what its own reference needs. A reference with a static path keeps its compiled path, its first name and its mark\n * `address`. It does not keep its document, its split or the functions of the other form.\n */\n\n /** This function gives the result of a resolution of a reference. An address gives what the path reaches: a host thing stays a thing. */\n const give = (found: Resolution, address: boolean): Result => {\n if (!found.ok) return fail(found.code, found.reason);\n if (address) 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 /** This function gives the error of a name whose binding failed, or `undefined` when the binding holds no error. */\n const held = (ctx: Context, rt: Runtime, head: string | undefined): Failed | undefined => {\n if (head === undefined || !Object.hasOwn(ctx.names, head)) return undefined;\n const bound = ctx.names[head];\n if (!(bound instanceof Held)) return undefined;\n // The result comes from the binding of the name, thus the runtime resolves the name for the list of reads (READS.RECORD).\n rt.resolve(ctx, [\"names\", head]);\n return { ok: false, error: bound.error };\n };\n /** This function gives the code of a reference with a static path. A path without a first name does not test a binding. */\n const staticRef = (compiledPath: CompiledPath, head: string | undefined, address: boolean): Code =>\n head === undefined\n ? (ctx, rt) => give(resolveCompiled(rt, ctx, compiledPath), address)\n : (ctx, rt) => held(ctx, rt, head) ?? give(resolveCompiled(rt, ctx, compiledPath), address);\n /**\n * This function gives the code of a reference whose step documents are parts, when the kind ref has a deep shape.\n * The steps evaluate first, in order, thus the error of a step comes before the error of a binding (FORMULA.STEPS).\n */\n const stepsRef = (parts: readonly CompiledPart[], fill: CompileInput[\"fill\"], head: string | undefined, address: boolean): Code => {\n return (ctx, rt) => {\n const steps = valuesOf(parts, ctx, rt);\n if (!Array.isArray(steps)) return steps;\n return held(ctx, rt, head) ?? give(rt.resolve(ctx, fill(steps) as readonly unknown[]), address);\n };\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, machine }) => {\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 // A path without parts is static, thus it compiles one time for the machine of the plan (PLAN.PATH).\n if (parts.length === 0) return staticRef(compilePath(machine, path), head, address === true);\n return stepsRef(parts, fill, head, address === true);\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 // A closure keeps the context for each later use, thus the list of reads gets each root (READS.KEPT).\n rt.keepsContext?.();\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, machine }) => {\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, machine.domains);\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 * Equal profiles give the same hook (D46).\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 return kitOf(profile).known;\n}\n\n/** This function makes a new hook `known` for the fields of one profile. */\nfunction makeKnown(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 * The facts of an extension of the profile that `pureExt` does not name. It gets the context, thus it can read outside\n * `resolve`.\n */\nconst NOT_PURE: KindFacts = /* @__PURE__ */ Object.freeze({ pure: false });\n\n/** The facts of a standard extension, and of an extension that `pureExt` names. */\nconst PURE: KindFacts = /* @__PURE__ */ Object.freeze({ pure: true });\n\n/** The lazy rule of a lazy operation: it covers each argument. */\nconst EACH_PART: readonly LazyRule[] = /* @__PURE__ */ Object.freeze([/* @__PURE__ */ Object.freeze({})]);\n\n/**\n * This function makes the hook `facts` of the formula kit for one profile (FACTS.PROFILE, D24). It answers for the\n * operations and the extensions, because one fallback kind covers each of them.\n *\n * - An operation of `lazy` has a lazy rule for each argument.\n * - An operation is pure when the profile names it in `pure`, or when `pure` is `true`. A volatile operation is not pure.\n * - A standard extension is pure. An extension of the profile is pure only when the profile names it in `pureExt` (D47).\n * Such an extension keeps C4: it reads the context only through `resolve`.\n *\n * Equal profiles give the same hook (D46).\n *\n * @param profile - The operations, the extensions and their facts.\n * @returns The hook: the facts of a name, or `undefined` for the facts of the contract.\n */\nexport function formulaFacts(profile: FormulaProfile = {}): (path: readonly Key[], code: string) => KindFacts | undefined {\n return kitOf(profile).facts;\n}\n\n/** This function makes a new hook `facts` for the fields of one profile, with the hook `known` of the same fields. */\nfunction makeFacts(profile: FormulaProfile, known: (path: readonly Key[], evaluator: string) => true | string): (path: readonly Key[], code: string) => KindFacts | undefined {\n const volatile = new Set(profile.volatile ?? []);\n const pure = profile.pure === true ? undefined : new Set(profile.pure ?? []);\n const pureExt = new Set(profile.pureExt ?? []);\n return (path, code) => {\n if (code !== \"formula.op\" && code !== \"formula.ext\") return undefined;\n const name = path.slice(1).join(\".\");\n if (code === \"formula.ext\") {\n if (profile.ext !== undefined && Object.hasOwn(profile.ext, name)) return pureExt.has(name) ? PURE : NOT_PURE;\n return Object.hasOwn(STD_EXT, name) ? PURE : undefined;\n }\n // An operation that the language does not have gives #NAME?. The kit gives it no facts.\n if (known(path, code) !== true) return undefined;\n const isVolatile = volatile.has(name);\n const lazy = profile.lazy !== undefined && Object.hasOwn(profile.lazy, name);\n return { pure: !isVolatile && (pure === undefined || pure.has(name)), volatile: isVolatile, ...(lazy ? { lazy: EACH_PART } : {}) };\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. The hook `facts` of the kit comes from the profile too (`formulaFacts`).\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 * The kit gives the domains of the kernel (`STD_DOMAINS`). Thus a domain of the language with the name `number` is a\n * conflict. The language names `[\"domains\", \"number\"]` in `replaces` to replace it.\n *\n * Equal profiles give the same evaluators and the same hooks (COMPOSE.UNIFY, D46). Thus two machines of one profile\n * merge, also when each adds its own language. Two profiles with different fields give different evaluators, and\n * their machines conflict at each evaluator name of the kit.\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 const kit = kitOf(profile);\n return mergeMachines({ world: { kinds: formulaKinds() }, evaluators: { ...kit.evaluators }, domains: STD_DOMAINS, known: kit.known, facts: kit.facts }, more);\n}\n","import { type Json, type Key, isEnvelope, isRecord, typePath } from \"./doc.ts\";\nimport { type Result, describe, fail, isStackOverflow, ok } from \"./errors.ts\";\nimport type { EvalFn, Part } from \"./evaluate.ts\";\nimport type { MachinePart } from \"./merge.ts\";\nimport { encodeValue } from \"./codec.ts\";\n\n/** The place of an operator: before its term, between two terms, or after its term. */\nexport type SyntaxFixity = \"prefix\" | \"infix\" | \"postfix\";\n\n/**\n * The grouping of a chain of one infix operator. `left` reads `a - b - c` as `(a - b) - c`, and `right` reads\n * `a ^ b ^ c` as `a ^ (b ^ c)`. `none` refuses a chain. `flat` reads a chain as one document with each term.\n */\nexport type SyntaxAssoc = \"left\" | \"right\" | \"none\" | \"flat\";\n\n/** One operator of a syntax profile. */\nexport interface SyntaxOperator {\n /** The text of the operator, for example `+`, `<>` or `and`. A word operator is a plain name. */\n readonly symbol: string;\n /** The place of the operator. */\n readonly fixity: SyntaxFixity;\n /** The precedence. A larger number binds more tightly. */\n readonly prec: number;\n /** The grouping of a chain of an infix operator. The default is `left`. */\n readonly assoc?: SyntaxAssoc;\n /** The type of the document that the operator makes, with dots between the keys, for example `ops.add` or `and`. */\n readonly kind: string;\n}\n\n/** The literal rules of a syntax profile. */\nexport interface SyntaxLiterals {\n /** `false` removes the decimal numbers. The default is `true`. */\n readonly numbers?: boolean;\n /** `true` puts a minus sign right before a digit into the number, where a term starts. The default is `true`. */\n readonly signed?: boolean;\n /** The texts: the quote and the escape of a quote. `false` removes the texts. The default is `\"` with backslashes. */\n readonly strings?: false | { readonly quote?: '\"' | \"'\"; readonly escape?: \"backslash\" | \"double\" };\n /** The words that are literals, with their values. The default is `true`, `false` and `null`. */\n readonly words?: Readonly<Record<string, unknown>>;\n}\n\n/** A reference syntax that a pattern gives, for example the address `A1` of a cell. */\nexport interface SyntaxRefPattern {\n /** The pattern of the text of a reference. The parser tries it before a name. */\n readonly pattern: RegExp;\n /** This function gives the path of the reference from its text. */\n readonly read: (text: string) => readonly Key[];\n /** This function gives the text of a path, or `undefined` when the pattern does not write the path. */\n readonly write: (path: readonly unknown[]) => string | undefined;\n}\n\n/** The reference syntax of a syntax profile. */\nexport interface SyntaxRefs {\n /** The root of a bare name. The default is `names`. Thus `x` is the path `[\"names\", \"x\"]`. */\n readonly bare?: string;\n /** The roots that the text names first, for example `self.price`. The default is `self`, `world`, `event` and `caps`. */\n readonly roots?: readonly string[];\n /** `false` removes the field steps `a.b`. The default is `true`. */\n readonly fields?: boolean;\n /** The patterns of other references. */\n readonly patterns?: readonly SyntaxRefPattern[];\n}\n\n/** A call form: a name with arguments in parentheses that makes a construct, for example `if(test, then, else)`. */\nexport interface SyntaxForm {\n /** The name in the text. */\n readonly name: string;\n /** The type of the document, with dots between the keys. */\n readonly kind: string;\n /** The fields of the value, in the order of the arguments. Without them, the value is the list of the arguments. */\n readonly fields?: readonly string[];\n /** The smallest number of arguments. The default is the number of the fields, or `0`. */\n readonly min?: number;\n}\n\n/** The call syntax of a syntax profile. */\nexport interface SyntaxCalls {\n /** The operations that a call `name(args)` can name. `true` permits each name. The default is `true`. */\n readonly ops?: boolean | readonly string[];\n /** The call forms of constructs. A form wins over an operation with the same name. */\n readonly forms?: readonly SyntaxForm[];\n /** The text between two arguments. The default is `,`. */\n readonly separator?: string;\n}\n\n/**\n * The text syntax of a language (D41): an operator table, literal rules, reference syntax and call syntax. `parse`\n * reads a text into a document, and `print` writes a document as text. The profile is data, thus a site, an editor\n * and a language read the same rules.\n */\nexport interface SyntaxProfile {\n /** The operators. */\n readonly operators?: readonly SyntaxOperator[];\n /** The literal rules. */\n readonly literals?: SyntaxLiterals;\n /** The reference syntax. */\n readonly refs?: SyntaxRefs;\n /** The call syntax. */\n readonly calls?: SyntaxCalls;\n /** The deepest nesting that `parse` accepts. The default is `256`. */\n readonly maxDepth?: number;\n}\n\n/** A problem of a text: its character offset, its length and a message. */\nexport interface SyntaxIssue {\n /** The 0-based character offset of the problem. */\n readonly offset: number;\n /** The number of characters of the problem. `0` marks a place between two characters. */\n readonly length: number;\n /** The message. */\n readonly message: string;\n}\n\n/** The result of `parse`: a document, or the problems of the text. */\nexport type ParseResult = { readonly ok: true; readonly doc: Json } | { readonly ok: false; readonly issues: readonly SyntaxIssue[] };\n\n/**\n * The standard syntax of the formula kit. It gives the site and the playground a text form. The operators are\n * `or`, `and`, `not`, the comparisons, `+ - * / %`, a minus sign and `^`, from the loosest to the tightest. A call\n * `name(args)` applies the operation `ops.name`. `if(test, then, else)` and `list(items)` make the constructs.\n */\nexport const STD_SYNTAX: SyntaxProfile = /* @__PURE__ */ Object.freeze({\n operators: [\n { symbol: \"or\", fixity: \"infix\", prec: 1, assoc: \"flat\", kind: \"or\" },\n { symbol: \"and\", fixity: \"infix\", prec: 2, assoc: \"flat\", kind: \"and\" },\n { symbol: \"not\", fixity: \"prefix\", prec: 3, kind: \"ops.not\" },\n { symbol: \"==\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.eq\" },\n { symbol: \"!=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.ne\" },\n { symbol: \"<\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.lt\" },\n { symbol: \"<=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.le\" },\n { symbol: \">\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.gt\" },\n { symbol: \">=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.ge\" },\n { symbol: \"+\", fixity: \"infix\", prec: 5, kind: \"ops.add\" },\n { symbol: \"-\", fixity: \"infix\", prec: 5, kind: \"ops.sub\" },\n { symbol: \"*\", fixity: \"infix\", prec: 6, kind: \"ops.mul\" },\n { symbol: \"/\", fixity: \"infix\", prec: 6, kind: \"ops.div\" },\n { symbol: \"%\", fixity: \"infix\", prec: 6, kind: \"ops.mod\" },\n { symbol: \"-\", fixity: \"prefix\", prec: 7, kind: \"ops.neg\" },\n { symbol: \"^\", fixity: \"infix\", prec: 8, assoc: \"right\", kind: \"ops.pow\" },\n ],\n literals: { words: { true: true, false: false, null: null, undefined: undefined, NaN: NaN, Infinity: Infinity } },\n calls: {\n forms: [\n { name: \"if\", kind: \"if\", fields: [\"test\", \"then\", \"else\"], min: 2 },\n { name: \"list\", kind: \"list\" },\n ],\n },\n} satisfies SyntaxProfile);\n\n// === The compiled profile ===\n\ninterface Op {\n readonly symbol: string;\n readonly fixity: SyntaxFixity;\n readonly prec: number;\n readonly assoc: SyntaxAssoc;\n readonly type: Json;\n readonly kindKey: string;\n readonly word: boolean;\n}\n\ninterface Form {\n readonly name: string;\n readonly type: Json;\n readonly fields: readonly string[] | undefined;\n readonly min: number;\n}\n\ninterface Pattern {\n readonly sticky: RegExp;\n readonly whole: RegExp;\n readonly read: (text: string) => readonly Key[];\n readonly write: (path: readonly unknown[]) => string | undefined;\n}\n\ninterface Compiled {\n readonly prefix: ReadonlyMap<string, Op>;\n readonly binary: ReadonlyMap<string, Op>;\n readonly prefixSymbols: readonly string[];\n readonly binarySymbols: readonly string[];\n readonly byKind: ReadonlyMap<string, readonly Op[]>;\n readonly numbers: boolean;\n readonly signed: boolean;\n readonly quote: string | undefined;\n readonly doubled: boolean;\n readonly words: ReadonlyMap<string, unknown>;\n readonly bare: string;\n readonly roots: ReadonlySet<string>;\n readonly fields: boolean;\n readonly patterns: readonly Pattern[];\n readonly ops: true | ReadonlySet<string>;\n readonly forms: ReadonlyMap<string, Form>;\n readonly formsByKind: ReadonlyMap<string, readonly Form[]>;\n readonly separator: string;\n readonly reserved: ReadonlySet<string>;\n readonly opWords: ReadonlySet<string>;\n readonly maxDepth: number;\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst NAME_AT = /[A-Za-z_][A-Za-z0-9_]*/y;\nconst DIGITS_AT = /[0-9]+/y;\nconst NUMBER_AT = /(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\nconst SYMBOL = /^[^\\sA-Za-z0-9_\"'`()$.]+$/;\nconst DEFAULT_WORDS: Readonly<Record<string, unknown>> = { true: true, false: false, null: null };\nconst DEFAULT_ROOTS: readonly string[] = [\"self\", \"world\", \"event\", \"caps\"];\n\nconst compiledProfiles = new WeakMap<SyntaxProfile, Compiled>();\n\nfunction typeOfKind(kind: string): { readonly type: Json; readonly key: string } {\n const keys = kind.split(\".\");\n if (kind === \"\" || keys.some((key) => key === \"\")) throw new TypeError(`The kind \"${kind}\" of a syntax profile has an empty key.`);\n return { type: keys.length === 1 ? (keys[0] as string) : keys, key: JSON.stringify(keys) };\n}\n\nfunction addTo<V>(map: Map<string, V[]>, key: string, value: V): void {\n const list = map.get(key);\n if (list === undefined) map.set(key, [value]);\n else list.push(value);\n}\n\nfunction compileOps(profile: SyntaxProfile, separator: string): Pick<Compiled, \"prefix\" | \"binary\" | \"prefixSymbols\" | \"binarySymbols\" | \"byKind\" | \"opWords\"> {\n const prefix = new Map<string, Op>();\n const binary = new Map<string, Op>();\n const byKind = new Map<string, Op[]>();\n const assocAt = new Map<number, SyntaxAssoc>();\n const opWords = new Set<string>();\n for (const given of profile.operators ?? []) {\n const word = NAME.test(given.symbol);\n if (!word && (!SYMBOL.test(given.symbol) || given.symbol.includes(separator))) {\n throw new TypeError(`The operator \"${given.symbol}\" is not a plain name or a group of symbols.`);\n }\n if (!Number.isFinite(given.prec)) throw new TypeError(`The operator \"${given.symbol}\" has no finite precedence.`);\n const { type, key } = typeOfKind(given.kind);\n const op: Op = { symbol: given.symbol, fixity: given.fixity, prec: given.prec, assoc: given.assoc ?? \"left\", type, kindKey: key, word };\n const table = op.fixity === \"prefix\" ? prefix : binary;\n if (table.has(op.symbol)) throw new TypeError(`The operator \"${op.symbol}\" has two entries of the same place.`);\n table.set(op.symbol, op);\n if (op.fixity === \"infix\") {\n const assoc = assocAt.get(op.prec);\n if (assoc !== undefined && assoc !== op.assoc) throw new TypeError(`The infix operators of the precedence ${String(op.prec)} have different groupings.`);\n assocAt.set(op.prec, op.assoc);\n }\n if (word) opWords.add(op.symbol);\n addTo(byKind, key, op);\n }\n const longestFirst = (table: Map<string, Op>): string[] =>\n [...table.keys()].filter((symbol) => !NAME.test(symbol)).sort((a, b) => b.length - a.length);\n return { prefix, binary, prefixSymbols: longestFirst(prefix), binarySymbols: longestFirst(binary), byKind, opWords };\n}\n\nfunction compileProfile(profile: SyntaxProfile): Compiled {\n const cached = compiledProfiles.get(profile);\n if (cached !== undefined) return cached;\n const calls = profile.calls ?? {};\n const separator = calls.separator ?? \",\";\n const ops = compileOps(profile, separator);\n const literals = profile.literals ?? {};\n const strings = literals.strings === false ? undefined : (literals.strings ?? {});\n const words = new Map(Object.entries(literals.words ?? DEFAULT_WORDS));\n const refs = profile.refs ?? {};\n const roots = new Set(refs.roots ?? DEFAULT_ROOTS);\n const forms = new Map<string, Form>();\n const formsByKind = new Map<string, Form[]>();\n for (const given of calls.forms ?? []) {\n if (!NAME.test(given.name)) throw new TypeError(`The call form \"${given.name}\" is not a plain name.`);\n const { type, key } = typeOfKind(given.kind);\n const form: Form = { name: given.name, type, fields: given.fields, min: given.min ?? given.fields?.length ?? 0 };\n forms.set(form.name, form);\n addTo(formsByKind, key, form);\n }\n const compiled: Compiled = {\n ...ops,\n numbers: literals.numbers ?? true,\n signed: literals.signed ?? true,\n quote: strings === undefined ? undefined : (strings.quote ?? '\"'),\n doubled: strings !== undefined && strings.escape === \"double\",\n words,\n bare: refs.bare ?? \"names\",\n roots,\n fields: refs.fields ?? true,\n patterns: (refs.patterns ?? []).map((p) => {\n const flags = p.pattern.flags.replace(/[gy]/g, \"\");\n return { sticky: new RegExp(p.pattern.source, `${flags}y`), whole: new RegExp(`^(?:${p.pattern.source})$`, flags), read: p.read, write: p.write };\n }),\n ops: calls.ops === undefined || calls.ops === true ? true : new Set(calls.ops === false ? [] : calls.ops),\n forms,\n formsByKind,\n separator,\n reserved: new Set([...words.keys(), ...ops.opWords, ...roots]),\n maxDepth: profile.maxDepth ?? 256,\n };\n compiledProfiles.set(profile, compiled);\n return compiled;\n}\n\n// === Parse ===\n\n/** The stop of a parse. The parser throws it, and `parse` gives its issue. */\nclass Stop {\n constructor(readonly issue: SyntaxIssue) {}\n}\n\nfunction literalDoc(value: unknown): Json {\n return encodeValue({}, value);\n}\n\nfunction opDoc(op: Op | Form, value: Json): Json {\n return { type: op.type, value };\n}\n\nconst ESCAPES: Readonly<Record<string, string>> = { '\"': '\"', \"'\": \"'\", \"\\\\\": \"\\\\\", \"/\": \"/\", b: \"\\b\", f: \"\\f\", n: \"\\n\", r: \"\\r\", t: \"\\t\" };\n\nclass Parser {\n private pos = 0;\n private depth = 0;\n\n constructor(\n private readonly syn: Compiled,\n private readonly text: string,\n ) {}\n\n parse(): Json {\n this.skip();\n if (this.pos >= this.text.length) this.stop(\"The text is empty.\", 0, 0);\n const doc = this.expr(0);\n this.skip();\n if (this.pos < this.text.length) this.stop(\"The text continues after the expression.\", this.pos, this.tokenLength());\n return doc;\n }\n\n position(): number {\n return this.pos;\n }\n\n private stop(message: string, offset: number, length: number): never {\n throw new Stop({ offset, length, message });\n }\n\n private skip(): void {\n while (this.pos < this.text.length && /\\s/.test(this.text[this.pos] as string)) this.pos += 1;\n }\n\n private at(pattern: RegExp, pos: number = this.pos): string | undefined {\n pattern.lastIndex = pos;\n return pattern.exec(this.text)?.[0];\n }\n\n private tokenLength(): number {\n return (this.at(NAME_AT) ?? this.at(DIGITS_AT) ?? \"x\").length;\n }\n\n /** This method reads an expression by precedence climbing. It stops at an operator below `min`. */\n private expr(min: number): Json {\n const start = this.pos;\n this.depth += 1;\n if (this.depth > this.syn.maxDepth) this.stop(`The text is deeper than ${String(this.syn.maxDepth)} levels.`, start, 0);\n let left = this.operand();\n for (;;) {\n this.skip();\n const found = this.operatorAt();\n if (found === undefined || found.op.prec < min) break;\n const op = found.op;\n this.pos += found.length;\n if (op.fixity === \"postfix\") {\n left = opDoc(op, [left]);\n continue;\n }\n if (op.assoc === \"flat\") {\n const terms = [left, this.expr(op.prec + 1)];\n for (;;) {\n this.skip();\n const next = this.operatorAt();\n if (next === undefined || next.op.fixity !== \"infix\" || next.op.kindKey !== op.kindKey) break;\n this.pos += next.length;\n terms.push(this.expr(op.prec + 1));\n }\n left = opDoc(op, terms);\n continue;\n }\n left = opDoc(op, [left, this.expr(op.assoc === \"right\" ? op.prec : op.prec + 1)]);\n if (op.assoc === \"none\") {\n this.skip();\n const next = this.operatorAt();\n if (next !== undefined && next.op.fixity === \"infix\" && next.op.prec === op.prec) {\n this.stop(`The operator ${next.op.symbol} does not chain after ${op.symbol}. Add parentheses.`, this.pos, next.length);\n }\n }\n }\n this.depth -= 1;\n return left;\n }\n\n /** This method finds an infix or a postfix operator at the position. */\n private operatorAt(): { readonly op: Op; readonly length: number } | undefined {\n const name = this.at(NAME_AT);\n if (name !== undefined) {\n const op = this.syn.binary.get(name);\n return op !== undefined && op.word ? { op, length: name.length } : undefined;\n }\n for (const symbol of this.syn.binarySymbols) {\n if (this.text.startsWith(symbol, this.pos)) return { op: this.syn.binary.get(symbol) as Op, length: symbol.length };\n }\n return undefined;\n }\n\n private operand(): Json {\n this.skip();\n const start = this.pos;\n const c = this.text[start];\n if (c === undefined) return this.stop(\"A term is missing at the end of the text.\", start, 0);\n for (const pattern of this.syn.patterns) {\n const match = this.at(pattern.sticky);\n if (match !== undefined && match !== \"\" && !/[A-Za-z0-9_$(]/.test(this.text[start + match.length] ?? \"\")) {\n this.pos += match.length;\n return { type: \"ref\", value: pattern.read(match) as Json };\n }\n }\n if (/[0-9]/.test(c)) return this.number(false);\n if (c === \"-\" && this.syn.signed && /[0-9]/.test(this.text[start + 1] ?? \"\")) return this.number(true);\n if (c === this.syn.quote) return this.string();\n if (c === \"(\") return this.group();\n if (c === \"`\" || /[A-Za-z_]/.test(c)) return this.named();\n for (const symbol of this.syn.prefixSymbols) {\n if (this.text.startsWith(symbol, start)) {\n this.pos += symbol.length;\n const op = this.syn.prefix.get(symbol) as Op;\n return opDoc(op, [this.expr(op.prec + 1)]);\n }\n }\n if (c === \")\" || this.text.startsWith(this.syn.separator, start)) return this.stop(\"A term is missing.\", start, 0);\n return this.stop(`The text \"${c}\" cannot start a term.`, start, 1);\n }\n\n private number(negative: boolean): Json {\n const start = this.pos;\n if (!this.syn.numbers) this.stop(\"This syntax has no numbers.\", start, this.tokenLength());\n if (negative) this.pos += 1;\n const digits = this.at(NUMBER_AT) as string;\n this.pos += digits.length;\n const value = Number(digits);\n return literalDoc(negative ? -value : value);\n }\n\n private string(): Json {\n const start = this.pos;\n const quote = this.syn.quote as string;\n let out = \"\";\n this.pos += 1;\n for (;;) {\n const c = this.text[this.pos];\n if (c === undefined) return this.stop(\"A closing quote is missing.\", start, this.text.length - start);\n if (c === quote) {\n if (this.syn.doubled && this.text[this.pos + 1] === quote) {\n out += quote;\n this.pos += 2;\n continue;\n }\n this.pos += 1;\n return literalDoc(out);\n }\n if (c === \"\\\\\" && !this.syn.doubled) {\n out += this.escape();\n continue;\n }\n out += c;\n this.pos += 1;\n }\n }\n\n private escape(): string {\n const start = this.pos;\n const c = this.text[start + 1] ?? \"\";\n if (c === \"u\") {\n const hex = this.text.slice(start + 2, start + 6);\n if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return this.stop(\"The escape \\\\u needs four hex digits.\", start, 2);\n this.pos += 6;\n return String.fromCharCode(Number.parseInt(hex, 16));\n }\n const out = Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : undefined;\n if (out === undefined) return this.stop(`The escape \\\\${c} is not valid.`, start, 2);\n this.pos += 2;\n return out;\n }\n\n private group(): Json {\n const open = this.pos;\n this.pos += 1;\n const inner = this.expr(0);\n this.skip();\n if (this.text[this.pos] !== \")\") {\n if (this.pos >= this.text.length) this.stop(\"A closing parenthesis is missing.\", open, 1);\n this.stop(\"A closing parenthesis is missing.\", this.pos, this.tokenLength());\n }\n this.pos += 1;\n return inner;\n }\n\n /** This method reads a name in backticks. Two backticks in the name are one backtick. */\n private quoted(): string {\n const start = this.pos;\n let out = \"\";\n this.pos += 1;\n for (;;) {\n const c = this.text[this.pos];\n if (c === undefined) return this.stop(\"A closing backtick is missing.\", start, this.text.length - start);\n if (c === \"`\") {\n if (this.text[this.pos + 1] !== \"`\") {\n this.pos += 1;\n return out;\n }\n this.pos += 1;\n }\n out += c;\n this.pos += 1;\n }\n }\n\n /** This method reads a name: a word operator, a call, a literal word or a reference. */\n private named(): Json {\n const start = this.pos;\n const plain = this.text[start] !== \"`\";\n const first = plain ? (this.at(NAME_AT) as string) : this.quoted();\n if (plain) {\n this.pos += first.length;\n const prefix = this.syn.prefix.get(first);\n if (prefix !== undefined && prefix.word) return opDoc(prefix, [this.expr(prefix.prec + 1)]);\n if (this.syn.binary.get(first)?.word === true) this.stop(`A term is missing before ${first}.`, start, first.length);\n }\n const path: Key[] = [first];\n let allPlain = plain;\n for (;;) {\n const back = this.pos;\n this.skip();\n if (!this.syn.fields || this.text[this.pos] !== \".\") {\n this.pos = back;\n break;\n }\n this.pos += 1;\n this.skip();\n if (this.text[this.pos] === \"`\") {\n path.push(this.quoted());\n allPlain = false;\n continue;\n }\n const name = this.at(NAME_AT);\n const digits = name === undefined ? this.at(DIGITS_AT) : undefined;\n if (name === undefined && digits === undefined) this.stop(\"A name is missing after the dot.\", this.pos, 0);\n this.pos += (name ?? (digits as string)).length;\n path.push(name ?? Number(digits));\n if (name === undefined) allPlain = false;\n }\n const back = this.pos;\n this.skip();\n if (this.text[this.pos] === \"(\") {\n if (!allPlain) this.stop(\"The name of a call is a plain name.\", start, back - start);\n return this.call(path.join(\".\"), start, back - start);\n }\n this.pos = back;\n if (plain && path.length === 1 && this.syn.words.has(first)) return literalDoc(this.syn.words.get(first));\n const full = plain && this.syn.roots.has(first) ? path : [this.syn.bare, ...path];\n return { type: \"ref\", value: full };\n }\n\n private call(name: string, start: number, nameLength: number): Json {\n const open = this.pos;\n const args: Json[] = [];\n this.pos += 1;\n this.skip();\n if (this.text[this.pos] === \")\") this.pos += 1;\n else {\n for (;;) {\n args.push(this.expr(0));\n this.skip();\n if (this.text.startsWith(this.syn.separator, this.pos)) {\n this.pos += this.syn.separator.length;\n continue;\n }\n if (this.text[this.pos] === \")\") {\n this.pos += 1;\n break;\n }\n if (this.pos >= this.text.length) this.stop(\"A closing parenthesis is missing.\", open, 1);\n this.stop(`A \"${this.syn.separator}\" or a closing parenthesis is missing.`, this.pos, this.tokenLength());\n }\n }\n const form = this.syn.forms.get(name);\n if (form !== undefined) {\n const most = form.fields?.length ?? Number.POSITIVE_INFINITY;\n if (args.length < form.min || args.length > most) {\n const range = most === form.min ? String(most) : most === Number.POSITIVE_INFINITY ? `${String(form.min)} or more` : `${String(form.min)} to ${String(most)}`;\n this.stop(`The form ${name} takes ${range} arguments.`, start, this.pos - start);\n }\n if (form.fields === undefined) return opDoc(form, args);\n const value: Record<string, Json> = {};\n args.forEach((arg, index) => {\n value[form.fields?.[index] as string] = arg;\n });\n return opDoc(form, value);\n }\n if (this.syn.ops !== true && !this.syn.ops.has(name)) this.stop(`This syntax has no function ${name}.`, start, nameLength);\n return { type: [\"ops\", ...name.split(\".\")], value: args };\n }\n}\n\n/**\n * This function reads a text into a document with the rules of a profile (SYNTAX.PARSE). It does not throw for a\n * bad text. The issue gives the offset, the length and a message (SYNTAX.SPAN).\n *\n * @param profile - The syntax profile.\n * @param text - The text.\n * @returns The document, or the issues of the text.\n * @throws {TypeError} The profile is not valid, for example an operator has two entries of the same place.\n */\nexport function parse(profile: SyntaxProfile, text: string): ParseResult {\n const parser = new Parser(compileProfile(profile), text);\n try {\n return { ok: true, doc: parser.parse() };\n } catch (error) {\n if (error instanceof Stop) return { ok: false, issues: [error.issue] };\n if (isStackOverflow(error)) return { ok: false, issues: [{ offset: parser.position(), length: 0, message: \"The text is too deep for the stack of the host.\" }] };\n throw error;\n }\n}\n\n// === Print ===\n\n/** The text of a part, from its document and its path in the value of the parent. */\ntype SubText = (child: unknown, path: readonly Key[]) => Result<string>;\n\ntype Shape =\n | { readonly tag: \"text\"; readonly text: string }\n | { readonly tag: \"op\"; readonly op: Op; readonly terms: readonly unknown[] }\n | { readonly tag: \"call\"; readonly name: string; readonly args: readonly (readonly [Key, unknown])[] }\n | { readonly tag: \"none\"; readonly reason: string };\n\nfunction none(reason: string): Shape {\n return { tag: \"none\", reason };\n}\n\nfunction quoteName(name: string): string {\n return `\\`${name.replaceAll(\"`\", \"``\")}\\``;\n}\n\nfunction wordFor(syn: Compiled, value: unknown): string | undefined {\n for (const [word, held] of syn.words) if (Object.is(held, value)) return word;\n return undefined;\n}\n\nfunction textOfString(syn: Compiled, value: string): string | undefined {\n const quote = syn.quote;\n if (quote === undefined) return undefined;\n if (syn.doubled) return `${quote}${value.replaceAll(quote, quote + quote)}${quote}`;\n const json = JSON.stringify(value);\n return quote === '\"' ? json : `'${json.slice(1, -1).replaceAll('\\\\\"', '\"').replaceAll(\"'\", \"\\\\'\")}'`;\n}\n\nfunction textOfNumber(syn: Compiled, value: number): string | undefined {\n if (!syn.numbers) return wordFor(syn, value);\n const negative = value < 0 || Object.is(value, -0);\n if (negative && !syn.signed) return wordFor(syn, value);\n if (Number.isFinite(value)) return negative ? `-${String(-value)}` : String(value);\n return wordFor(syn, value) ?? (Number.isNaN(value) ? undefined : negative ? \"-1e999\" : \"1e999\");\n}\n\nfunction literalShape(syn: Compiled, value: unknown): Shape {\n const text = typeof value === \"string\" ? textOfString(syn, value) : typeof value === \"number\" ? textOfNumber(syn, value) : wordFor(syn, value);\n return text === undefined ? none(`This syntax has no text for the literal ${describe(value)}.`) : { tag: \"text\", text };\n}\n\nfunction plainSegment(syn: Compiled, name: string): boolean {\n return NAME.test(name) && !syn.reserved.has(name) && !syn.patterns.some((p) => p.whole.test(name));\n}\n\nfunction laterSegment(step: unknown): string | undefined {\n if (typeof step === \"string\") return NAME.test(step) ? step : quoteName(step);\n return typeof step === \"number\" && Number.isSafeInteger(step) && step >= 0 ? String(step) : undefined;\n}\n\nfunction refShape(syn: Compiled, value: unknown): Shape {\n if (!Array.isArray(value) || value.length === 0) return none(\"The path of the reference is empty.\");\n for (const pattern of syn.patterns) {\n const text = pattern.write(value);\n if (text !== undefined) return { tag: \"text\", text };\n }\n const [root, ...rest] = value as readonly unknown[];\n const many = rest.length > 1 || (root !== syn.bare && rest.length > 0);\n if (many && !syn.fields) return none(\"This syntax has no field steps.\");\n const later = rest.slice(1).map(laterSegment);\n let first: string | undefined;\n let tail = later;\n if (root === syn.bare && typeof rest[0] === \"string\") first = plainSegment(syn, rest[0]) ? rest[0] : quoteName(rest[0]);\n else if (typeof root === \"string\" && syn.roots.has(root) && !syn.patterns.some((p) => p.whole.test(root))) {\n first = root;\n tail = rest.map(laterSegment);\n }\n if (first === undefined || tail.includes(undefined)) return none(\"This syntax has no text for the path of the reference.\");\n return { tag: \"text\", text: [first, ...tail].join(\".\") };\n}\n\nfunction callName(syn: Compiled, keys: readonly Key[]): string | undefined {\n if (keys.length === 0 || !keys.every((key) => typeof key === \"string\" && NAME.test(key))) return undefined;\n const name = keys.join(\".\");\n if (syn.forms.has(name) || syn.opWords.has(keys[0] as string)) return undefined;\n return syn.ops === true || syn.ops.has(name) ? name : undefined;\n}\n\nfunction formShape(form: Form, value: unknown): Shape | undefined {\n if (form.fields === undefined) {\n if (!Array.isArray(value) || value.length < form.min) return undefined;\n return { tag: \"call\", name: form.name, args: value.map((item, index) => [index, item] as const) };\n }\n if (!isRecord(value)) return undefined;\n // The fields that the value holds must be the first fields of the form, because the arguments go in order.\n const count = Object.keys(value).length;\n const present = form.fields.slice(0, count);\n if (count < form.min || present.length < count || !present.every((key) => Object.hasOwn(value, key))) return undefined;\n return { tag: \"call\", name: form.name, args: present.map((key) => [key, value[key]] as const) };\n}\n\nfunction opShape(syn: Compiled, key: string, terms: readonly unknown[]): Shape | undefined {\n for (const op of syn.byKind.get(key) ?? []) {\n const fits = op.fixity === \"infix\" ? terms.length === 2 || (op.assoc === \"flat\" && terms.length > 2) : terms.length === 1;\n if (fits) return { tag: \"op\", op, terms };\n }\n return undefined;\n}\n\n/** This function gives the shape of a document: a literal or a reference, an operator, a call, or no text. */\nfunction shapeOf(syn: Compiled, doc: unknown): Shape {\n if (!isEnvelope(doc)) return Array.isArray(doc) || isRecord(doc) ? none(\"This syntax has no text for a list or a record literal.\") : literalShape(syn, doc);\n if (doc.name !== undefined || doc.own !== undefined) return none(\"This syntax has no text for the header of a document.\");\n const path = typePath(doc.type);\n if (path === undefined) return none(\"This syntax has no text for a computed type.\");\n const value: unknown = doc.value;\n const name = path.join(\".\");\n if (name === \"lit\") return isEnvelope(value) || Array.isArray(value) || isRecord(value) ? none(\"This syntax has no text for a list or a record literal.\") : literalShape(syn, value);\n if (name === \"ext.undefined\") return literalShape(syn, undefined);\n if (name === \"ext.number\") {\n const numbers: Readonly<Record<string, number>> = { NaN: Number.NaN, Infinity: Number.POSITIVE_INFINITY, \"-Infinity\": Number.NEGATIVE_INFINITY, \"-0\": -0 };\n return typeof value === \"string\" && Object.hasOwn(numbers, value) ? literalShape(syn, numbers[value]) : none(\"The value of ext.number is not valid.\");\n }\n if (name === \"ref\") return refShape(syn, value);\n const key = JSON.stringify(path);\n const op = Array.isArray(value) ? opShape(syn, key, value) : undefined;\n if (op !== undefined) return op;\n for (const form of syn.formsByKind.get(key) ?? []) {\n const shape = formShape(form, value);\n if (shape !== undefined) return shape;\n }\n const called = path[0] === \"ops\" && Array.isArray(value) ? callName(syn, path.slice(1)) : undefined;\n if (called !== undefined) return { tag: \"call\", name: called, args: (value as readonly unknown[]).map((item, index) => [index, item] as const) };\n return none(`This syntax has no text for the kind ${name}.`);\n}\n\nfunction levelOf(syn: Compiled, doc: unknown): number {\n const shape = shapeOf(syn, doc);\n return shape.tag === \"op\" ? shape.op.prec : Number.POSITIVE_INFINITY;\n}\n\n/** This function tells if a term needs parentheses in its position, so that `parse` reads the same tree. */\nfunction needsGroup(op: Op, index: number, level: number): boolean {\n if (op.fixity === \"postfix\") return level < op.prec;\n if (op.fixity === \"prefix\" || op.assoc === \"none\" || op.assoc === \"flat\") return level <= op.prec;\n const looser = op.assoc === \"left\" ? index === 0 : index !== 0;\n return looser ? level < op.prec : level <= op.prec;\n}\n\nfunction opText(syn: Compiled, op: Op, terms: readonly unknown[], sub: SubText): Result<string> {\n const texts: string[] = [];\n for (let index = 0; index < terms.length; index += 1) {\n const term = terms[index];\n const result = sub(term, [index]);\n if (!result.ok) return result;\n let text = result.value;\n const signedDigit = op.fixity === \"prefix\" && op.symbol === \"-\" && syn.signed && /^[0-9]/.test(text);\n if (needsGroup(op, index, levelOf(syn, term)) || signedDigit) text = `(${text})`;\n texts.push(text);\n }\n const [only = \"\"] = texts;\n if (op.fixity === \"prefix\") return ok(op.word || /^[^A-Za-z0-9_(\"'`$]/.test(only) ? `${op.symbol} ${only}` : `${op.symbol}${only}`);\n if (op.fixity === \"postfix\") return ok(op.word ? `${only} ${op.symbol}` : `${only}${op.symbol}`);\n return ok(texts.join(` ${op.symbol} `));\n}\n\n/** This function writes one document. `sub` gives the text of each part. */\nfunction printNode(syn: Compiled, doc: unknown, sub: SubText): Result<string> {\n const shape = shapeOf(syn, doc);\n if (shape.tag === \"text\") return ok(shape.text);\n if (shape.tag === \"none\") return fail(\"#VALUE!\", shape.reason);\n if (shape.tag === \"op\") return opText(syn, shape.op, shape.terms, sub);\n const texts: string[] = [];\n for (const [key, arg] of shape.args) {\n const result = sub(arg, [key]);\n if (!result.ok) return result;\n texts.push(result.value);\n }\n return ok(`${shape.name}(${texts.join(`${syn.separator} `)})`);\n}\n\nfunction printTree(syn: Compiled, doc: unknown, place: readonly Key[]): Result<string> {\n const result = printNode(syn, doc, (child, path) => printTree(syn, child, [...place, ...path]));\n return result.ok || result.error.place !== undefined ? result : fail(result.error.code, result.error.reason, { place });\n}\n\n/**\n * This function writes a document as text with the rules of a profile (SYNTAX.PRINT). It writes the fewest\n * parentheses that keep the tree. `parse` reads the text back to the same document (SYNTAX.ROUNDTRIP).\n *\n * @param profile - The syntax profile.\n * @param doc - The document.\n * @returns The text, or `#VALUE!` at the place of a document that the profile cannot write.\n * @throws {TypeError} The profile is not valid.\n */\nexport function print(profile: SyntaxProfile, doc: unknown): Result<string> {\n const syn = compileProfile(profile);\n try {\n return printTree(syn, doc, []);\n } catch (error) {\n if (isStackOverflow(error)) return fail(\"#DEPTH!\", \"The document is too deep for the stack of the host.\", { cause: error });\n throw error;\n }\n}\n\n/**\n * This function makes the part of a merge that adds the verb `format` to a machine (D23, D41). Its default writes\n * each document with the printer of the profile. A part gives its own text through the ladder, thus an own entry or\n * a kind entry of `format` still wins.\n *\n * @param profile - The syntax profile.\n * @returns The part for `mergeMachines`.\n */\nexport function syntaxFormat(profile: SyntaxProfile): MachinePart {\n const syn = compileProfile(profile);\n const code: EvalFn = ({ doc, parts, place }) => {\n const byPath = new Map<string, Part>(parts.map((part) => [JSON.stringify(part.path), part]));\n return printNode(syn, doc, (child, path) => {\n const part = byPath.get(JSON.stringify(path));\n if (part === undefined) return printTree(syn, child, [...place, ...path]);\n const result = part.evaluate();\n if (!result.ok) return result;\n return typeof result.value === \"string\" ? ok(result.value) : fail(\"#VALUE!\", `The verb format of a part gave ${describe(result.value)}, not a text.`, { place: [...place, ...path] });\n });\n };\n return { world: { defaults: { format: \"syntax.format\" } }, evaluators: { \"syntax.format\": code } };\n}\n","import { type Envelope, type Json, type Key, isEnvelope, isRecord, typeName } from \"./doc.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type AttributeDeclaration, type CapsRule, type Kind, type TreeContract, equationType, lookupKind } 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 { type AttributeRung, STD_EVALUATORS } from \"./stdlib.ts\";\nimport { type EvalError, type Failed, type Result, Failure, describe, 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 Perform,\n type RunFn,\n type RunInput,\n type RunPart,\n type Steps,\n makeContext,\n permits,\n placeText,\n waitedReason,\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 /** The mock of the host (RUN.MOCK). It answers each effect at once. Without it, an effect gives its payload. */\n readonly perform?: Perform;\n /**\n * The verb that goes up the ladder at each document, as in `prepare`. The default is `eval`. The reference reads\n * each verb by the same rules (VERB.AGREE).\n */\n readonly verb?: string;\n}\n\n/** The scope of the addresses of effects (RUN.ADDRESS): the root of the evaluation, or one item of `all`. */\ninterface Scope {\n /** The text before each address of the scope. */\n readonly prefix: string;\n /** The number of earlier effects at each place of the scope, by the text of the place. */\n readonly counts: Map<string, number>;\n /** The number of earlier uses of `all` in the scope. */\n alls: number;\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 readonly perform: Perform | undefined;\n /** The verb that goes up the ladder at each document. Each part evaluates with the same verb. */\n readonly verb: string;\n /** The scope of the code that evaluates at this time. `all` changes it for each item. */\n scope: Scope;\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 of the verb (LADDER.*, VERB.LADDER), an\n * evaluator and the shape 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, env.verb, 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/**\n * This function gives the effects that two lists of capabilities both permit (CAP.ONLY). The reference reads the rule\n * from SPEC directly, and not from the intersection of the plan. Thus `agree` finds a bug in either one (D15).\n */\nfunction bothPermit(a: readonly Cap[], b: readonly Cap[]): readonly Cap[] {\n const out: Cap[] = [];\n for (const cap of [...a, ...b]) if (permits(a, cap) && permits(b, cap) && !permits(out, cap)) out.push(cap);\n return out;\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 = bothPermit(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/**\n * This function causes an effect when the capabilities permit it (RUN.CAP, CAP.HOOK). It records the effect with its\n * address (RUN.ADDRESS) and its outcome (RUN.OUTCOME). The mock answers the effect at once (RUN.MOCK). Without a\n * mock, the effect gives its payload (RUN.EVAL).\n */\nfunction cause(env: Env, ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\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 const at = placeText(place);\n const count = env.scope.counts.get(at) ?? 0;\n env.scope.counts.set(at, count + 1);\n const effect: { -readonly [K in keyof Effect]: Effect[K] } = {\n index: env.effects.length,\n kind: text,\n path: keys,\n payload,\n node: -1,\n at: 0,\n place,\n context: ctx,\n address: `${env.scope.prefix}${at}#${count}`,\n };\n env.effects.push(effect);\n effect.outcome = answer(env.perform, effect, place);\n return effect.outcome;\n}\n\n/**\n * This function gives the answer of the mock to an effect. A throw gives `#CALC!` with the cause, and a `Failure`\n * gives its own error value. A promise gives `#CALC!`, because an evaluation does not wait.\n */\nfunction answer(perform: Perform | undefined, effect: Effect, place: readonly Key[]): Result {\n if (perform === undefined) return ok(effect.payload);\n let given: unknown;\n try {\n given = perform(effect);\n } catch (error) {\n if (error instanceof Failure) return placed({ ok: false, error: error.error }, place);\n return fail(\"#CALC!\", `The host failed the effect ${effect.kind}: ${describe(error)}`, { place, cause: error });\n }\n if (!(given instanceof Promise)) return ok(given);\n void given.catch(() => undefined);\n return fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place });\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, seen.kindText);\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[], kindText: string): 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!\", waitedReason(kindText), { 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 machine: env.machine,\n ...(at.address ? { address: true } : {}),\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: (kind, payload) => cause(env, at.ctx, kind, payload, at.place),\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 machine: env.machine,\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: function* (kind, payload) {\n return cause(env, at.ctx, kind, payload, at.place);\n },\n all: (list, options) => together(env, 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 *\n * Each part has its own scope of addresses. Its prefix names the use of `all` in the scope around it, and the part\n * (RUN.ADDRESS).\n */\nfunction* together(env: Env, 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 const outer = env.scope;\n const address = `${outer.prefix}all${outer.alls}`;\n outer.alls += 1;\n let failed = false;\n for (let index = 0; index < list.length && !failed && waiting.length < limit; index += 1) {\n let result: Result | undefined;\n env.scope = { prefix: `${address}.${index}/`, counts: new Map(), alls: 0 };\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 } finally {\n env.scope = outer;\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 the answer of the mock or its payload, and a part that waits gives `#CALC!`.\n *\n * The verb of the options goes up the ladder at each document, as in `prepare`. Each verb has the same rules: the\n * ladder, the contract of the kind and the sealed parts (VERB.AGREE).\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, a list for the effects, a mock and the verb.\n * @returns The result.\n */\nexport function reference(machine: Machine, doc: unknown, context: Context = makeContext(), options: ReferenceOptions = {}): Result {\n const env: Env = {\n machine,\n definitions: options.definitions ?? {},\n effects: options.effects ?? [],\n maxDepth: machine.maxDepth ?? 1000,\n perform: options.perform,\n verb: options.verb ?? \"eval\",\n scope: { prefix: \"\", counts: new Map(), alls: 0 },\n };\n const ctx = context.world === null ? { ...context, world: worldThing(machine.world) } : context;\n // A node of a tree reads the definitions of this evaluation for its equations (TREE.LADDER).\n activeEnvs.push(env);\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 } finally {\n activeEnvs.pop();\n }\n}\n\n/** The evaluations of the reference that run at this time, the innermost last. */\nconst activeEnvs: Env[] = [];\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 tree contract of the kind of the node (D42). */\n readonly contract: TreeContract | undefined;\n /** The type of a bare equation: the type `of` of the parts of the kind. */\n readonly of: string | undefined;\n /** The parent node in the same tree, for the rungs `parent` and `copy`. */\n readonly up: RefNode | undefined;\n /** The evaluation of the reference that made the node. Its equations evaluate with its definitions. */\n readonly env: Env | undefined;\n /** The host thing of the node. */\n thing: HostThing;\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 = /* @__PURE__ */ 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/**\n * TREE.LADDER: an equation of the kind of a node evaluates in the reference. It gets the node as `self`, the names of\n * its rung and no capabilities. A bare equation gets the type `of` of the parts of the kind.\n */\nfunction equationOf(node: RefNode, term: Json, names: Readonly<Record<string, unknown>>): Result {\n const env = node.env;\n if (env === undefined) return fail(\"#NOEVAL\", \"The evaluation of an equation needs the machine.\");\n const ctx: Context = { ...node.ctx, names, caps: [], self: node.thing };\n return reference(env.machine, term, ctx, { definitions: env.definitions, ...(node.of === undefined ? {} : { declaredType: node.of }) });\n}\n\nfunction termIn<T>(table: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return table === undefined || !Object.hasOwn(table, name) ? undefined : table[name];\n}\n\n/** TREE.DOWN: the names of a child for an equation of `down` of its parent: `child`, `index` and `prev`. */\nfunction namesOfChild(up: RefNode, child: RefNode): Result {\n const children = attributeOf(up, \"children\");\n if (children !== undefined && !children.ok) return children;\n const list: readonly unknown[] = children !== undefined && Array.isArray(children.value) ? children.value : [];\n const index = list.indexOf(child.thing);\n return ok({ child: child.thing, index: index < 0 ? null : index, prev: index > 0 ? list[index - 1] : null });\n}\n\n/** TREE.FOLD: the unit, then `combine` with the attribute of each node of this tree in the list `children`. */\nfunction foldOf(node: RefNode, name: string, fold: NonNullable<AttributeDeclaration[\"fold\"]>): Result {\n let acc = equationOf(node, fold.unit, {});\n if (!acc.ok) return acc;\n const children = attributeOf(node, \"children\");\n if (children === undefined) return acc;\n if (!children.ok) return children;\n if (!Array.isArray(children.value)) return fail(\"#VALUE!\", `The fold of ${name} needs a list in children.`);\n for (const item of children.value) {\n const child = refNodeOf(item);\n if (child === undefined || child.tree !== node.tree) continue;\n const value = attributeOf(child, name);\n if (value === undefined) return fail(\"#N/A\", `No rung gives ${nameOfAttribute(child, name)}.`);\n if (!value.ok) return value;\n acc = equationOf(node, fold.combine, { acc: acc.value, item: value.value });\n if (!acc.ok) return acc;\n }\n return acc;\n}\n\n/**\n * TREE.LADDER: the rungs of the ladder of an attribute, in their order. A rung gives `undefined` when it does not\n * answer, and the next rung then tries.\n */\nconst REF_RUNGS: readonly (readonly [AttributeRung, (node: RefNode, name: string) => Result | undefined])[] = [\n [\"own\", (node, name) => node.parts.find((item) => item.key === name)?.evaluate({ ...node.ctx, self: node.thing })],\n [\n \"kind\",\n (node, name) => {\n const term = termIn(node.contract?.equations, name);\n return term === undefined ? undefined : equationOf(node, term, {});\n },\n ],\n [\n \"parent\",\n (node, name) => {\n const up = node.up;\n const term = up === undefined ? undefined : termIn(up.contract?.down, name);\n if (up === undefined || term === undefined) return undefined;\n const names = namesOfChild(up, node);\n return names.ok ? equationOf(up, term, names.value as Readonly<Record<string, unknown>>) : names;\n },\n ],\n [\"copy\", (node, name) => (node.up !== undefined && termIn(node.contract?.attributes, name)?.copy === true ? attributeOf(node.up, name) : undefined)],\n [\n \"default\",\n (node, name) => {\n const declared = termIn(node.contract?.attributes, name);\n if (declared?.fold !== undefined) return foldOf(node, name, declared.fold);\n return declared?.default === undefined ? undefined : equationOf(node, declared.default, {});\n },\n ],\n];\n\n/** TREE.ONCE, TREE.MEMO and TREE.CYCLE: the result of one attribute, or `undefined` when no rung of its ladder answers. */\nfunction attributeOf(node: RefNode, 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 node.pending.add(name);\n inEvaluation.push({ node, name });\n try {\n for (const [, rung] of REF_RUNGS) {\n const result = rung(node, name);\n if (result === undefined) continue;\n node.values.set(name, result);\n return result;\n }\n return undefined;\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, 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. The node\n * reads `self` only through `resolve` (C4, TREE.SELF).\n */\nconst treeDefinition: EvalFn = ({ parts, context, kind, place, machine, typePath, resolve: walk }) => {\n const reached = walk([\"self\"]);\n const parent: Thing | undefined = reached.ok ? reached.thing : undefined;\n const outer = refNodeOf(parent);\n const nested = outer !== undefined && outer.tree.open;\n const found = machine === undefined || typePath.length === 0 ? undefined : lookupKind(machine.world, typePath);\n const contract = found?.ok === true ? found.kind.tree : undefined;\n const of = contract === undefined || found?.ok !== true ? undefined : equationType(found.kind);\n const node: RefNode = {\n tree: nested ? outer.tree : { open: true },\n kind,\n place,\n parts,\n ctx: context,\n contract,\n of,\n up: nested ? outer : undefined,\n env: activeEnvs[activeEnvs.length - 1],\n thing: null as unknown as HostThing,\n values: new Map(),\n pending: new Set(),\n };\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 parent;\n if (key === \"type\") return kind;\n const result = attributeOf(node, String(key));\n if (result === undefined || result.ok) return result?.ok === true ? result.value : undefined;\n throw new Failure(result.error);\n },\n has: (key) => key === \"parent\" || key === \"type\" || parts.some((part) => part.key === String(key)) || node.values.has(String(key)),\n toJson: () => {\n const result = jsonOfNode(node, self, []);\n if (result.ok) return result.value;\n throw new Failure(result.error);\n },\n };\n node.thing = self;\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 = /* @__PURE__ */ 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, machine }) => {\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, machine?.domains);\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 = /* @__PURE__ */ 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, equalWith } from \"./doc.ts\";\nimport type { Context } from \"./deref.ts\";\nimport { type EvalError, type Result, isStackOverflow, thrown } from \"./errors.ts\";\nimport { type Effect, type Machine, type Perform, 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 * - `folds`: a second plan with the other choice of folds (PLAN.FOLD). It has no folds when the plan has them, and\n * it has folds when the option `observe` stops the folds of the plan.\n * - `other`: the second tier of a language, from the option `other`.\n */\nexport type Tier = \"reference\" | \"traced\" | \"again\" | \"folds\" | \"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/** What `agree` gives the second tier of a language beside the document and the context. */\nexport interface TierInput {\n /** The mock of the host, when `agree` has one (AGREE.MOCK). The tier answers each effect with it. */\n readonly perform?: Perform;\n /** The verb of `agree`, when its options name one (VERB.AGREE). A tier that does not serve the verb fails. */\n readonly verb?: string;\n}\n\n/** The options of `agree`. */\nexport interface AgreeOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The verb of each tier, as in `prepare`. The default is `eval`. The plan, the reference, the traced evaluation and a\n * second evaluation each ask the ladder for this verb (VERB.AGREE). The second tier of a language gets it in its\n * input.\n */\n readonly verb?: string;\n /** The definitional code of the compiled evaluators of the machine, for the reference. */\n readonly definitions?: Definitions;\n /**\n * The tiers to compare with the plan. The default is the reference, the traced evaluation, a second evaluation and\n * the plan with the other choice of folds.\n */\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 * @param input - The mock of the host and the verb, when `agree` has them.\n * @returns The result, or the result with the effects.\n */\n readonly other?: (doc: unknown, context: Context, input: TierInput) => Result | TierResult;\n /**\n * The mock of the host (RUN.MOCK, AGREE.MOCK). Each tier gets it, thus the tiers agree on documents with effects. A\n * mock must give the same answer to the same effect, because each tier asks it again.\n */\n readonly perform?: Perform;\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. A fold moves the calls of a part to the compilation, thus with this option the plan has\n * no folds. The tier `folds` then has folds, and `agree` does not compare its calls.\n *\n * @returns What the host saw.\n */\n readonly observe?: () => unknown;\n}\n\n/** The tiers that `agree` compares when its options name none. */\nconst DEFAULT_TIERS: readonly Exclude<Tier, \"other\">[] = /* @__PURE__ */ Object.freeze([\"reference\", \"traced\", \"again\", \"folds\"]);\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` and `sameResult` use the same walk (D20). `docEquals` has no rules for closures, for `Held` values and\n * for a rule of the caller. `sameResult` is for an early cutoff, thus a closure is the same there only as itself, and\n * two errors also need the same reason.\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 return equalWith(a, b, equal === undefined ? sameInTiers : (x, y) => equal(x, y) ?? sameInTiers(x, y));\n}\n\n/** The rules of `sameValue` for the values that two tiers make again: closures and held errors. */\nfunction sameInTiers(x: unknown, y: unknown): boolean | undefined {\n if (isClosure(x) || isClosure(y)) return isClosure(x) && isClosure(y) && docEquals(closureParams(x), closureParams(y));\n if (x instanceof Held || y instanceof Held) return x instanceof Held && y instanceof Held && errorDiffers(x.error, y.error, false) === undefined;\n return undefined;\n}\n\nconst CLOSURE = /* @__PURE__ */ 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/**\n * This function gives the difference of two lists of effects, or `undefined` when they agree (EFFECT.ORDER). When both\n * tiers record the address or the outcome of an effect, these must agree too (AGREE.MOCK).\n */\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 if (x.address !== undefined && y.address !== undefined && x.address !== y.address) {\n return `The effect ${index} has the address ${x.address} in the plan, and ${y.address} in the tier.`;\n }\n const why = x.outcome !== undefined && y.outcome !== undefined ? resultDiffers(x.outcome, y.outcome, options) : undefined;\n if (why !== undefined) return `The outcome of the effect ${index} differs. ${why}`;\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`. Each tier gets the mock of the option `perform` (AGREE.MOCK).\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, the second tier and the mock.\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 = {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n };\n const mock = options.perform === undefined ? {} : { perform: options.perform };\n const tierInput: TierInput = { ...mock, ...(options.verb === undefined ? {} : { verb: options.verb }) };\n const observe = options.observe;\n observe?.();\n // A fold moves host calls to the compilation, thus a plan whose calls the host compares has no folds (PLAN.FOLD).\n const folds = observe === undefined;\n const plan = prepare(machine, doc, { ...declared, fold: folds });\n const effects: Effect[] = [];\n const result = plan.evaluate(context, { effects, ...mock });\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 ?? DEFAULT_TIERS) {\n let other: Result;\n let otherEffects: Effect[] = [];\n if (tier === \"reference\") {\n other = reference(machine, doc, context, { ...declared, ...mock, effects: otherEffects, ...(options.definitions === undefined ? {} : { definitions: options.definitions }) });\n } else if (tier === \"traced\") {\n const traced = evaluate(machine, doc, context, { ...declared, ...mock });\n other = traced.result;\n otherEffects = [...traced.effects];\n } else if (tier === \"folds\") {\n other = prepare(machine, doc, { ...declared, fold: !folds }).evaluate(context, { effects: otherEffects, ...mock });\n if (observe !== undefined) {\n // The folds of this tier call the host when it compiles. Thus only the result and the effects compare.\n observe();\n if (overflowed(result) || overflowed(other)) continue;\n const why = resultDiffers(result, other, options) ?? effectsDiffer(effects, otherEffects, options);\n if (why !== undefined) return { ok: false, tier, plan: result, other, reason: why };\n continue;\n }\n } else {\n other = plan.evaluate(context, { effects: otherEffects, ...mock });\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, tierInput);\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","import { type Envelope, type Json, type Key, type TypeRef, docEquals, isEnvelope, isKey, typeName } from \"./doc.ts\";\nimport { type Cap, type Context, type Resolution, type ResolveOptions, resolve } from \"./deref.ts\";\nimport { type Result, describe, fail, ok, placed, thrown } from \"./errors.ts\";\nimport {\n type AllOptions,\n type Code,\n type CompileInput,\n type CompiledEvaluator,\n type CompiledPart,\n type CompiledRunner,\n type Effect,\n type EvalFn,\n type EvalInput,\n type Evaluator,\n type Machine,\n type Part,\n type Perform,\n type RunCode,\n type RunFn,\n type RunInput,\n type RunPart,\n type Runner,\n type Runtime,\n type Steps,\n capKeys,\n makeContext,\n permits,\n rootContext,\n} from \"./evaluate.ts\";\nimport { type PartSlot, type Split, pathMatches, scopesOf, splitParts } from \"./parts.ts\";\nimport { type Definitions, STD_DEFINITIONS } from \"./reference.ts\";\nimport { STD_EVALUATORS } from \"./stdlib.ts\";\nimport { sameValue } from \"./agree.ts\";\nimport { type Random, random } from \"./generate.ts\";\nimport { type Kind, type LazyRule, type Shape, type World, type WorldEntry, effectsOfVerb, isKind, isNamespace, lookupKind } from \"./world.ts\";\n\n/*\n * The conformance tests of one evaluator (K92, R7 P3, D36). `conforms` calls the code of one evaluator or runner\n * directly, without the kernel. It gives the code probe parts and a probe runtime. A probe part records each call, its\n * context and its order, and it gives a chosen result. The probe runtime records each resolution and each effect. The\n * checks compare these records with the contract of the kind and with the obligations C1 to C8 of SEMANTICS.md.\n */\n\n/**\n * An obligation that `conforms` checks. `C1` to `C8` are the obligations of host code in `docs/SEMANTICS.md`. `local`\n * and `agree` are two premises of the simulation of the plan (SIM-PLAN).\n *\n * - `C1`: each context that the code gives a part, or an effect, has only the capabilities of its document.\n * - `C2`: the code causes only the effects that the contract of the kind declares.\n * - `C3`: each eager part evaluates when the result is a value, and a lazy part evaluates only when its result counts.\n * - `C4`: the code of a pure kind causes no effect, and it reads the context only through `resolve`.\n * - `C5`: the code reads its parts only through their handles, not through the JSON of the document.\n * - `C6`: only a runner waits, and a runner passes each wait of its parts and its effects through.\n * - `C7`: the code binds for a part each name that the scope rules give the part, and no other name.\n * - `C8`: compiled code gives the result of code that compiles again at the time of the evaluation.\n * - `local`: the code keeps no state from one call to the next.\n * - `agree`: compiled code gives the result of its definition for the reference interpreter.\n */\nexport type Obligation = \"C1\" | \"C2\" | \"C3\" | \"C4\" | \"C5\" | \"C6\" | \"C7\" | \"C8\" | \"local\" | \"agree\";\n\n/** The probe of a finding: the document, the result of each probe part, the capabilities and the handler. */\nexport interface ConformProbe {\n /** The text of the type of the document. */\n readonly type: string;\n /** The document. A probe document takes the place of each part. */\n readonly doc: Envelope;\n /** The result of each probe part, by the key of the part. */\n readonly results: Readonly<Record<string, Result>>;\n /** The keys of the probe parts that wait for the host before they give their result. Only a run has them. */\n readonly waits: readonly string[];\n /** The capabilities of the context of the document. */\n readonly caps: readonly Cap[];\n /** `true` in a run, in which the host does each effect and a part can wait. */\n readonly running: boolean;\n}\n\n/** One obligation that the code breaks, with the reason and the first probe that shows it. */\nexport interface Finding {\n readonly obligation: Obligation;\n /** One or two sentences that tell what the code did. */\n readonly reason: string;\n readonly probe: ConformProbe;\n}\n\n/** The options of `conforms`. */\nexport interface ConformOptions {\n /**\n * The verb that the evaluator serves. The default is `eval`. The facts `pure` and `lazy` of a contract describe only\n * `eval`, thus `conforms` checks C3 and C4 only for `eval` (D23). `conforms` checks C2 for each verb that the\n * contract declares effects for: `eval`, and each verb with an entry in `verbEffects` (D49).\n */\n readonly verb?: string;\n /**\n * The types of the probe documents. The default is each kind of the world whose verb names the evaluator. A fallback\n * kind gives the key `probe`, for example `[\"ops\", \"probe\"]`. The contract of the kind of each type applies.\n */\n readonly types?: readonly TypeRef[];\n /**\n * More values of probe documents, by the text of their type. A probe document takes the place of each part of such a\n * value. Use them for data that the code needs, for example the key of `write`.\n */\n readonly values?: Readonly<Record<string, readonly Json[]>>;\n /**\n * The results that a probe part can give. The default holds numbers, truth values, a text, `null`, a list, a\n * record, a function and two errors.\n */\n readonly results?: readonly Result[];\n /**\n * The definitional code of the compiled evaluators and runners, as for `reference`. A standard evaluator gets its\n * definition from `STD_DEFINITIONS`.\n */\n readonly definitions?: Definitions;\n /** The capabilities of half of the probes. The other half has none. The default is the declared effects and `probe`. */\n readonly caps?: readonly Cap[];\n /** The names of the context of each probe. */\n readonly names?: Readonly<Record<string, unknown>>;\n /** The seed of the random results. The same seed gives the same probes. The default is 1. */\n readonly seed?: number;\n /** The count of probes with random results for each probe document. The default is 12. */\n readonly runs?: number;\n /** The mock of the host (RUN.MOCK). It answers each effect at once. Without it, an effect gives its payload. */\n readonly perform?: Perform;\n /**\n * This function compares two values that the rules of `sameValue` do not know, as in `agree`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @returns `true` or `false`, or `undefined` for the rules of `sameValue`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n}\n\n/** The order of the obligations in the list of findings. */\nconst ORDER: readonly Obligation[] = [\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"local\", \"agree\"];\n\n/** A function in the results of the probe parts. It gives the count of its arguments. */\nconst PROBE_FN = (...args: readonly unknown[]): number => args.length;\n\n/** The arguments of a call of a function that a result gives. */\nconst PROBE_ARGS: readonly unknown[] = [1, 2];\n\n/** The default results of the probe parts. */\nconst RESULTS: readonly Result[] = [\n { ok: true, value: 1 },\n { ok: true, value: 2 },\n { ok: true, value: true },\n { ok: true, value: false },\n { ok: true, value: \"a\" },\n { ok: true, value: null },\n { ok: true, value: [1, 2] },\n { ok: true, value: { a: 1 } },\n { ok: true, value: PROBE_FN },\n { ok: false, error: { code: \"#VALUE!\", reason: \"The probe part fails.\" } },\n { ok: false, error: { code: \"#N/A\", reason: \"The probe part has no value.\" } },\n];\n\n/** The result of a probe part without a chosen result. */\nconst NO_RESULT: Result = { ok: true, value: null };\n\n/** The result of a runner that the probe driver stops. */\nconst STOPPED: Result = { ok: false, error: { code: \"#CALC!\", reason: \"The probe driver stopped the runner.\" } };\n\n/** The result of an item of `all` after a failure with `failFast`. */\nconst ABORTED: Result = { ok: false, error: { code: \"#ABORT\", reason: \"The part stopped: a part before it failed, and the parts run with failFast.\" } };\n\n/** The default names of the context of each probe. The generated names of a value (`a`, `b` and `c`) are other names. */\nconst NAMES: Readonly<Record<string, unknown>> = { x: \"outer x\", y: 2.5, z: [\"outer\"] };\n\n/** The values of a document whose kind has no parts. */\nconst DATA: readonly Json[] = [1, \"a\", true, null, [\"names\", \"x\"], { a: 1 }, [\"names\", \"y\", \"c\"]];\n\n/** The count of generated values of each type. */\nconst VARIANTS = 8;\n\n/** The lengths of a generated list. */\nconst LENGTHS: readonly number[] = [2, 0, 1, 3];\n\n/** The texts of generated data. */\nconst TEXTS: readonly string[] = [\"a\", \"b\", \"c\"];\n\n/** The place of each probe document. */\nconst PLACE: readonly Key[] = [];\n\n/** No capabilities: the context of half of the probes. */\nconst NO_CAPS: readonly Cap[] = [];\n\n/** The code under test, in one of its four forms. */\ntype Under =\n | { readonly form: \"eval\"; readonly fn: EvalFn }\n | { readonly form: \"compile\"; readonly compile: (input: CompileInput) => Code }\n | { readonly form: \"run\"; readonly fn: RunFn }\n | { readonly form: \"compileRun\"; readonly compile: (input: CompileInput) => RunCode };\n\n/** The split of a value that has the shape of its kind. */\ntype SplitOk = Extract<Split, { readonly ok: true }>;\n\n/** One probe document, with what its contract tells about each part. */\ninterface Sample {\n readonly type: string;\n readonly typePath: readonly Key[];\n readonly kind: Kind;\n /** The document, with a probe document at the place of each part. */\n readonly doc: Envelope;\n readonly split: SplitOk;\n /** The same document with other JSON in each probe document (C5). */\n readonly other: Envelope;\n readonly otherSplit: SplitOk;\n /** `true` for each part that a lazy rule covers. */\n readonly lazy: readonly boolean[];\n /** The names that the scope rules give each part. */\n readonly names: readonly (readonly string[])[];\n}\n\n/** The results, the waits and the capabilities of one evaluation of a probe document. */\ninterface Scenario {\n readonly results: readonly Result[];\n readonly waits: readonly boolean[];\n readonly caps: readonly Cap[];\n readonly running: boolean;\n}\n\n/** One call of a probe part. */\ninterface Call {\n readonly part: number;\n /** The function that the code called: `evaluate` of a handle, or `code` or `run` of a compiled part. */\n readonly via: \"evaluate\" | \"code\" | \"run\";\n /** The context that the code gave the part. */\n readonly context: Context;\n /** `true` for a call in a function that the result gives, after the evaluation. */\n readonly later: boolean;\n}\n\n/** One effect that the code caused. */\ninterface Caused {\n readonly kind: string;\n readonly payload: unknown;\n readonly context: Context;\n}\n\n/** One resolution that the code asked for. */\ninterface Asked {\n readonly path: readonly unknown[];\n readonly found: Resolution;\n}\n\n/** One wait of a probe part or of an effect in a run. */\ninterface Wait {\n readonly what: string;\n readonly answer: unknown;\n /** `true` after the runner gave the promise to the driver. */\n seen: boolean;\n /** `true` after the probe got its answer. */\n done: boolean;\n}\n\n/** The state of `conforms` for one evaluator. */\ninterface Env {\n readonly machine: Machine;\n readonly name: string;\n readonly verb: string;\n readonly under: Under;\n readonly definition: Under | undefined;\n readonly runner: boolean;\n readonly results: readonly Result[];\n readonly names: Readonly<Record<string, unknown>>;\n readonly runs: number;\n readonly random: Random;\n readonly perform: Perform | undefined;\n readonly equal: ((a: unknown, b: unknown) => boolean | undefined) | undefined;\n readonly found: Map<Obligation, Finding>;\n}\n\n/** The facts of the kind of one type, as the contract and the hook `facts` of the machine give them. */\ninterface Contract {\n readonly declared: readonly Cap[];\n readonly pure: boolean;\n readonly lazy: readonly LazyRule[] | undefined;\n /** `true` when the facts describe the verb: they describe only `eval`. */\n readonly describes: boolean;\n /** `true` when the contract declares the effects of the verb: for `eval`, and for a verb in `verbEffects`. */\n readonly declares: boolean;\n readonly caps: readonly Cap[];\n}\n\n/**\n * The probe runtime of one evaluation, and its record. It records each call of a part, each effect and each\n * resolution. In a run, a probe part and an effect wait with a promise that the probe driver answers at once.\n */\nclass Shot implements Runtime {\n readonly calls: Call[] = [];\n readonly caused: Caused[] = [];\n readonly asked: Asked[] = [];\n /** The problems of the waits (C6). */\n readonly problems: string[] = [];\n readonly waits = new Map<Promise<unknown>, Wait>();\n /** The results of the calls of a function that the result gives. */\n readonly later: Result[] = [];\n result: Result = NO_RESULT;\n private afterwards = false;\n readonly running: boolean;\n\n constructor(\n readonly machine: Machine,\n /** `true` when the code under test is a runner. */\n readonly runner: boolean,\n readonly scenario: Scenario,\n /** The context of the document. */\n readonly context: Context,\n /** The key of each part, for the reasons. */\n readonly keys: readonly string[],\n private readonly perform: Perform | undefined,\n /** The resolutions of an earlier evaluation. Each resolution with the same path gets the same answer (C4). */\n private readonly replay: readonly Asked[] | undefined,\n ) {\n this.running = scenario.running;\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const old = this.replay?.[this.asked.length];\n const found = old !== undefined && docEquals(old.path, path) ? old.found : resolve(this.machine, ctx, path, options);\n this.asked.push({ path, found });\n return found;\n }\n\n /** This function records a call of a part, and gives the result that the probe part gives. */\n call(part: number, via: Call[\"via\"], ctx: Context): Result {\n this.calls.push({ part, via, context: ctx, later: this.afterwards });\n const key = this.keys[part] ?? String(part);\n if (via === \"run\" && !this.runner) this.problems.push(`The code of an evaluator starts the steps of the part ${key}. Only a runner waits.`);\n if (via === \"code\" && this.runner && this.running) {\n this.problems.push(`The runner evaluates the part ${key} with its code, and that code cannot wait. A runner evaluates a part with its steps (K65).`);\n }\n return this.scenario.results[part] ?? NO_RESULT;\n }\n\n /** This function records a call of a part, and gives the steps of the probe part. In a run, the part can wait. */\n *steps(part: number, via: Call[\"via\"], ctx: Context): Steps {\n const result = this.call(part, via, ctx);\n if (this.running && this.scenario.waits[part] === true) yield* this.wait(`the part ${this.keys[part] ?? String(part)}`);\n return result;\n }\n\n /** This function gives the steps of one wait. The probe driver answers the promise with a new object. */\n private *wait(what: string): Generator<Promise<unknown>, void, unknown> {\n const answer = { answer: what };\n const promise = new Promise<unknown>(() => undefined);\n const wait: Wait = { what, answer, seen: false, done: false };\n this.waits.set(promise, wait);\n const got = yield promise;\n wait.done = true;\n if (got !== answer) this.problems.push(`The runner gives ${what} another answer than the answer of the host.`);\n }\n\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const text = capKeys(kind).join(\".\");\n this.caused.push({ kind: text, payload, context: ctx });\n if (this.running) return fail(\"#CALC!\", `The effect ${text} needs a runner: in a run, the host does each effect.`, { place });\n return this.answer(ctx, kind, payload, place);\n }\n\n *runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps {\n const text = capKeys(kind).join(\".\");\n this.caused.push({ kind: text, payload, context: ctx });\n if (!this.runner) this.problems.push(`The code of an evaluator starts the steps of the effect ${text}. Only a runner waits.`);\n const answered = this.answer(ctx, kind, payload, place);\n if (!answered.ok || !this.running) return answered;\n yield* this.wait(`the effect ${text}`);\n return answered;\n }\n\n /** This function answers an effect as the kernel does: it checks the capability, and it asks the mock. */\n private answer(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const keys = capKeys(kind);\n // The kernel keeps only the capabilities that the document permits (H-GRANT).\n const caps = ctx.caps.filter((cap) => permits(this.context.caps, cap));\n const allowed = this.machine.permits === undefined ? permits(caps, keys) : this.machine.permits(caps, keys, { ...ctx, caps });\n if (!allowed) return fail(\"#CAP!\", `The context has no capability for the effect ${keys.join(\".\")}.`, { place });\n if (this.perform === undefined) return ok(payload);\n const effect: Effect = { index: this.caused.length - 1, kind: keys.join(\".\"), path: keys, payload, node: -1, at: 0, place, context: { ...ctx, caps } };\n let answer: unknown;\n try {\n answer = this.perform(effect);\n } catch (error) {\n return placed(thrown(error, `the mock of the effect ${effect.kind}`), place);\n }\n if (!(answer instanceof Promise)) return ok(answer);\n void answer.catch(() => undefined);\n return fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place });\n }\n\n *all(list: readonly (() => Steps)[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n if (!this.runner) this.problems.push(\"The code of an evaluator starts the steps of all. Only a runner waits.\");\n // The probe runtime starts the items one after the other. Each wait of an item passes through, as in the kernel.\n const results: Result[] = [];\n let failed = false;\n for (const begin of list) {\n if (failed) {\n results.push(ABORTED);\n continue;\n }\n let result: Result;\n try {\n result = yield* begin();\n } catch (error) {\n result = thrown(error, \"a part\");\n }\n results.push(result);\n if (options.failFast === true && !result.ok) failed = true;\n }\n return results;\n }\n\n keepsContext(): void {\n // The probe runtime records no reads, thus a closure needs no read of the roots.\n }\n\n /** This function starts a function that the result gives, with probe arguments. The calls of the parts are later calls. */\n callLater(): void {\n const result = this.result;\n if (!result.ok || typeof result.value !== \"function\") return;\n this.afterwards = true;\n try {\n this.later.push(ok((result.value as (...args: readonly unknown[]) => unknown)(...PROBE_ARGS)));\n } catch (error) {\n this.later.push(thrown(error, \"the function of the result\"));\n } finally {\n this.afterwards = false;\n }\n }\n}\n\n/** The code of one probe document, made one time. It evaluates the document in each shot. */\ntype Instance = (shot: Shot) => Result;\n\n/** This function sets an own field, also the field `__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 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/** This function gives the form of an evaluator or of a runner. */\nfunction underOf(code: Evaluator | Runner, runner: boolean): Under {\n if (runner) {\n if (typeof code === \"function\") return { form: \"run\", fn: code as RunFn };\n return { form: \"compileRun\", compile: (input) => (code as CompiledRunner).compileRun(input) };\n }\n if (typeof code === \"function\") return { form: \"eval\", fn: code as EvalFn };\n return { form: \"compile\", compile: (input) => (code as CompiledEvaluator).compile(input) };\n}\n\nfunction compiledForm(under: Under): boolean {\n return under.form === \"compile\" || under.form === \"compileRun\";\n}\n\n/** This function gives the definition of the code for the reference, when it has one that is other code. */\nfunction definitionOf(machine: Machine, name: string, runner: boolean, definitions: Definitions | undefined): Under | undefined {\n if (runner) {\n const defined = own(definitions?.runners, name);\n return defined === undefined || defined === own(machine.runners, name) ? undefined : { form: \"run\", fn: defined };\n }\n const evaluator = own(machine.evaluators, name);\n const standard = evaluator !== undefined && evaluator === own(STD_EVALUATORS, name) ? own(STD_DEFINITIONS.evaluators, name) : undefined;\n const defined = own(definitions?.evaluators, name) ?? standard;\n return defined === undefined || defined === evaluator ? undefined : { form: \"eval\", fn: defined };\n}\n\n/** This function gives the type of each kind of the world whose verb names the evaluator. */\nfunction typesNaming(world: World, name: string, verb: string): readonly TypeRef[] {\n const out: (readonly Key[])[] = [];\n const names = (kind: Kind | undefined): boolean => kind !== undefined && own(kind.verbs, verb) === name;\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)) {\n if (names(entry)) out.push([...prefix, key]);\n } else if (isNamespace(entry)) {\n visit(entry.kinds, [...prefix, key]);\n if (names(entry.fallback)) out.push([...prefix, key, \"probe\"]);\n }\n }\n };\n visit(world.kinds, []);\n if (names(world.fallback)) out.push([\"probe\"]);\n return out;\n}\n\n/** This function gives the facts of the kind of a type. The hook `facts` of the machine wins over the contract. */\nfunction contractOf(env: Env, kind: Kind, typePath: readonly Key[], caps: readonly Cap[] | undefined): Contract {\n const facts = env.machine.facts?.(typePath, env.name);\n // A verb without a declaration keeps the effects of eval for the capabilities of the probes, as before D49.\n const own = effectsOfVerb(kind, env.verb);\n const effects = own ?? kind.effects;\n const declared: readonly Cap[] = effects === undefined ? [] : effects === \"type\" ? [typePath] : effects;\n return {\n declared,\n pure: (facts?.pure ?? kind.pure) === true,\n lazy: facts?.lazy ?? kind.lazy,\n describes: env.verb === \"eval\",\n declares: own !== undefined,\n caps: caps ?? [...declared, \"probe\"],\n };\n}\n\n/** This function tells if a lazy rule covers the part with an index, as `factsOf` reads the rule. */\nfunction covers(rule: LazyRule, slots: readonly PartSlot[], index: number): boolean {\n const matches = (slot: PartSlot): boolean => rule.in === undefined || rule.in.some((pattern) => pathMatches(slot.path, pattern));\n const slot = slots[index] as PartSlot;\n if (!matches(slot)) return false;\n const after = rule.after ?? 0;\n if (after <= 0) return true;\n let position = 0;\n for (let at = 0; at < index; at += 1) if (matches(slots[at] as PartSlot)) position += 1;\n return position >= after;\n}\n\n/** The counter of the probe documents of one value. */\ninterface Counter {\n next: number;\n}\n\n/** This function gives the JSON of a probe document. A position that permits only some kinds gets the first of them. */\nfunction probeJson(counter: Counter, kinds: readonly (readonly Key[])[] | undefined, named: boolean): Json {\n const id = counter.next;\n counter.next += 1;\n const first = kinds?.[0];\n return { type: first === undefined ? \"probe\" : (first as readonly Json[]), value: { probe: id }, ...(named ? { name: `p${id}` } : {}) };\n}\n\n/** This function gives a number that a number shape permits. */\nfunction numberIn(shape: Extract<Shape, { readonly shape: \"number\" }>, variant: number): number {\n const start = shape.min ?? (shape.max === undefined ? 1 : shape.max - 2);\n const base = shape.whole === true ? Math.ceil(start) : start;\n const value = base + (variant % 3);\n return shape.max !== undefined && value > shape.max ? shape.max : value;\n}\n\n/**\n * This function generates a value of a shape, with a probe document at the place of each part. The variant selects the\n * length of each list, the fields of a record that are absent, and the binding names of the probe documents.\n */\nfunction valueOf(shape: Shape | undefined, variant: number, counter: Counter, named: boolean): Json {\n if (shape === undefined || shape.shape === \"none\") return DATA[variant % DATA.length] as Json;\n switch (shape.shape) {\n case \"text\":\n return TEXTS[variant % TEXTS.length] as string;\n case \"number\":\n return numberIn(shape, variant);\n case \"one\":\n return shape.values[variant % Math.max(1, shape.values.length)] ?? null;\n case \"term\":\n return probeJson(counter, shape.kinds, named);\n case \"deep\": {\n const pick = variant % 4;\n if (pick === 0) return [probeJson(counter, undefined, named)];\n if (pick === 1) return { a: probeJson(counter, undefined, named), b: [probeJson(counter, undefined, named)] };\n if (pick === 2) return [\"names\", probeJson(counter, undefined, named)];\n return [\"names\", \"a\"];\n }\n case \"list\": {\n const item: Shape = shape.item ?? { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) };\n const length = LENGTHS[variant % LENGTHS.length] as number;\n // The index selects the data of each item, thus the items of a list of data are different.\n return Array.from({ length }, (_unused, index) => valueOf(item, item.shape === \"term\" ? variant : index, counter, named));\n }\n case \"map\": {\n const item: Shape = shape.item ?? { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) };\n const out: Record<string, Json> = {};\n for (const key of TEXTS.slice(0, [2, 0, 1][variant % 3])) setField(out, key, valueOf(item, variant, counter, named));\n return out;\n }\n case \"record\": {\n const fields: Readonly<Record<string, Shape>> = Array.isArray(shape.fields)\n ? Object.fromEntries((shape.fields as readonly string[]).map((key) => [key, { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) } as Shape]))\n : (shape.fields as Readonly<Record<string, Shape>>);\n const keys = Object.keys(fields);\n const required = new Set(shape.required ?? []);\n const optional = keys.filter((key) => !required.has(key));\n // The variant 0 has each field. Each other variant leaves out one optional field.\n const absent = variant === 0 || optional.length === 0 ? undefined : optional[(variant - 1) % optional.length];\n const out: Record<string, Json> = {};\n for (const key of keys) if (key !== absent) setField(out, key, valueOf(fields[key], variant, counter, named));\n return out;\n }\n }\n}\n\n/** This function gives the JSON of a probe document with other JSON: another value, and another type where it can. */\nfunction otherJson(item: Json): Json {\n if (!isEnvelope(item)) return item;\n return { ...item, type: item.type === \"probe\" ? [\"probe\", \"other\"] : item.type, value: { other: [true, \"json\"], was: item.value } };\n}\n\n/** This function gives a probe document for a part of a value of the options. It keeps the type and the name of an envelope. */\nfunction probeFor(counter: Counter, item: Json): Json {\n if (!isEnvelope(item)) return probeJson(counter, undefined, false);\n const id = counter.next;\n counter.next += 1;\n return { ...item, value: { probe: id } };\n}\n\n/** This function gives the probe documents of a type: generated values and the values of the options. */\nfunction samplesOf(type: TypeRef, typePath: readonly Key[], kind: Kind, contract: Contract, extra: readonly Json[]): readonly Sample[] {\n const values: Json[] = [];\n for (let variant = 0; variant < VARIANTS; variant += 1) values.push(valueOf(kind.parts, variant, { next: 0 }, variant % 2 === 1));\n for (const value of extra) {\n const split = splitParts(kind.parts, value);\n if (!split.ok) continue;\n const counter: Counter = { next: 0 };\n values.push(split.fill(split.parts.map((slot) => probeFor(counter, slot.item))) as Json);\n }\n const out: Sample[] = [];\n const seen: Json[] = [];\n for (const value of values) {\n if (seen.some((other) => docEquals(other, value))) continue;\n seen.push(value);\n const split = splitParts(kind.parts, value);\n if (!split.ok) continue;\n const otherValue = split.parts.length === 0 ? value : (split.fill(split.parts.map((slot) => otherJson(slot.item))) as Json);\n const otherSplit = splitParts(kind.parts, otherValue);\n if (!otherSplit.ok || otherSplit.parts.length !== split.parts.length) continue;\n out.push({\n type: typeName(type),\n typePath,\n kind,\n doc: { type, value },\n split,\n other: { type, value: otherValue },\n otherSplit,\n lazy: split.parts.map((_slot, index) => contract.lazy?.some((rule) => covers(rule, split.parts, index)) === true),\n names: scopesOf(kind.scope, value, split.parts).sees,\n });\n }\n return out;\n}\n\n/** This function gives the handle fields of a part: its key, its path and its binding name. */\nfunction handleOf(slot: PartSlot): { readonly key: string; readonly path: readonly Key[]; readonly name?: string } {\n const item = slot.item;\n const name = isEnvelope(item) && typeof (item as { readonly name?: unknown }).name === \"string\" ? (item as { readonly name: string }).name : undefined;\n return name === undefined ? { key: slot.key, path: slot.path } : { key: slot.key, path: slot.path, name };\n}\n\n/**\n * This function drives the steps of a runner. It answers each wait of a probe part or of an effect at once. A promise\n * that no probe gave, or a wait that the runner gives two times, stops the steps (C6).\n */\nfunction drive(shot: Shot, steps: Steps): Result {\n let input: unknown;\n for (;;) {\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = steps.next(input);\n } catch (error) {\n return thrown(error, \"the runner\");\n }\n if (step.done === true) return step.value;\n const wait = shot.waits.get(step.value);\n if (wait === undefined || wait.seen) {\n shot.problems.push(\n wait === undefined\n ? \"The runner yields a promise that no part and no effect gave. A runner passes on only the waits of its parts and its effects.\"\n : `The runner yields the wait of ${wait.what} two times.`,\n );\n if (step.value instanceof Promise) void step.value.catch(() => undefined);\n try {\n steps.return(STOPPED);\n } catch {\n // The finally code of the runner threw. The probe stops the runner.\n }\n return STOPPED;\n }\n wait.seen = true;\n input = wait.answer;\n }\n}\n\n/** This function ends one evaluation: it keeps the result, calls a function that the result gives, and finds the waits that the runner dropped. */\nfunction finish(shot: Shot, start: () => Result, who: string): Result {\n let result: Result;\n try {\n result = placed(start(), PLACE);\n } catch (error) {\n result = placed(thrown(error, who), PLACE);\n }\n for (const wait of shot.waits.values()) if (!wait.done) shot.problems.push(`The runner drops the wait of ${wait.what}.`);\n shot.result = result;\n shot.callLater();\n return result;\n}\n\n/**\n * This function makes the code of one probe document. A compiler compiles the document one time, with compiled probe\n * parts. Each call of the code then evaluates the document in one shot.\n */\nfunction instanceOf(env: Env, under: Under, doc: Envelope, split: SplitOk, sample: Sample): Instance {\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n const base = { kind: sample.type, typePath: sample.typePath, doc, data: split.data, place: PLACE, machine: env.machine, fill };\n const who = `the ${env.runner ? \"runner\" : \"evaluator\"} ${env.name}`;\n if (under.form === \"eval\" || under.form === \"run\") {\n if (under.form === \"eval\") {\n const fn = under.fn;\n return (shot) => {\n const ctx = shot.context;\n const parts: Part[] = split.parts.map((slot, index) => ({ ...handleOf(slot), evaluate: (given?: Context) => shot.call(index, \"evaluate\", given ?? ctx) }));\n const input: EvalInput = {\n ...base,\n value: fill(parts),\n parts,\n context: ctx,\n resolve: (path, options) => shot.resolve(ctx, path, options),\n effect: (kind, payload) => shot.effect(ctx, kind, payload, PLACE),\n };\n return finish(shot, () => fn(input), who);\n };\n }\n const fn = under.fn;\n return (shot) => {\n const ctx = shot.context;\n const parts: RunPart[] = split.parts.map((slot, index) => ({ ...handleOf(slot), evaluate: (given?: Context) => shot.steps(index, \"evaluate\", given ?? ctx) }));\n const input: RunInput = {\n ...base,\n value: fill(parts),\n parts,\n context: ctx,\n resolve: (path, options) => shot.resolve(ctx, path, options),\n effect: (kind, payload) => shot.runEffect(ctx, kind, payload, PLACE),\n all: (list, options) => shot.all(list.map((part) => () => part.evaluate()), options),\n };\n return finish(shot, () => drive(shot, fn(input)), who);\n };\n }\n // A compiled part finds the shot of the evaluation through this holder, because the parts exist before each shot.\n const holder: { shot: Shot | undefined } = { shot: undefined };\n const early = fail(\"#CALC!\", \"The compiler evaluated a part before an evaluation.\");\n const parts: CompiledPart[] = split.parts.map((slot, index) => ({\n ...handleOf(slot),\n code: (ctx) => holder.shot?.call(index, \"code\", ctx) ?? early,\n *run(ctx) {\n const shot = holder.shot;\n return shot === undefined ? early : yield* shot.steps(index, \"run\", ctx);\n },\n }));\n const input: CompileInput = { ...base, value: fill(parts), parts, machine: env.machine };\n let made: Code | RunCode | Result;\n try {\n made = under.compile(input);\n } catch (error) {\n made = placed(thrown(error, who), PLACE);\n }\n const compiled = made;\n return (shot) => {\n holder.shot = shot;\n if (typeof compiled !== \"function\") return finish(shot, () => compiled, who);\n if (under.form === \"compile\") return finish(shot, () => (compiled as Code)(shot.context, shot), who);\n return finish(shot, () => drive(shot, (compiled as RunCode)(shot.context, shot)), who);\n };\n}\n\n/** This function evaluates a probe document one time in a new shot. */\nfunction shoot(env: Env, instance: Instance, sample: Sample, scenario: Scenario, more: { readonly context?: Context; readonly replay?: readonly Asked[] } = {}): Shot {\n const context = more.context ?? rootContext(env.machine, makeContext(env.names, scenario.caps));\n const shot = new Shot(env.machine, env.runner, scenario, context, sample.split.parts.map((slot) => slot.key), env.perform, more.replay);\n instance(shot);\n return shot;\n}\n\n/** This function gives the scenarios of a probe document: each result of the palette in each part, then random results. */\nfunction scenariosOf(env: Env, sample: Sample, contract: Contract, running: boolean): readonly Scenario[] {\n const count = sample.split.parts.length;\n const palette = env.results;\n const capsAt = (index: number): readonly Cap[] => (index % 2 === 0 ? contract.caps : NO_CAPS);\n const out: Scenario[] = [];\n const add = (results: readonly Result[], waits: readonly boolean[]): void => {\n out.push({ results, waits, caps: capsAt(out.length), running });\n };\n if (count === 0) {\n add([], []);\n add([], []);\n return out;\n }\n const all = Array.from({ length: count }, () => true);\n for (const result of palette) add(Array.from({ length: count }, () => result), all);\n for (let run = 0; run < env.runs; run += 1) {\n add(\n Array.from({ length: count }, () => env.random.pick(palette)),\n Array.from({ length: count }, () => env.random.chance(0.5)),\n );\n }\n return out;\n}\n\n/** This function gives a short text of a value for a reason. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"function\") return \"a function\";\n let text: string;\n try {\n text = JSON.stringify(value) ?? describe(value);\n } catch {\n text = describe(value);\n }\n return text.length > 40 ? `${text.slice(0, 37)}...` : text;\n}\n\nfunction resultText(result: Result): string {\n return result.ok ? `the value ${valueText(result.value)}` : `the error ${result.error.code}`;\n}\n\nfunction capsText(caps: readonly Cap[]): string {\n return caps.length === 0 ? \"no capabilities\" : `the capabilities ${caps.map((cap) => capKeys(cap).join(\".\")).join(\", \")}`;\n}\n\n/** This function tells if two results agree, as in `agree`: the same value, or errors with the same code and place. */\nfunction sameOutcome(a: Result, b: Result, equal: Env[\"equal\"]): boolean {\n if (a.ok && b.ok) return sameValue(a.value, b.value, equal);\n if (a.ok || b.ok) return false;\n if (a.error.code !== b.error.code) return false;\n return a.error.place === undefined || b.error.place === undefined || docEquals(a.error.place as readonly Key[], b.error.place as readonly Key[]);\n}\n\n/** This function tells if two shots give the same result and the same results of a later call. */\nfunction sameResults(a: Shot, b: Shot, equal: Env[\"equal\"]): boolean {\n return sameOutcome(a.result, b.result, equal) && a.later.length === b.later.length && a.later.every((result, index) => sameOutcome(result, b.later[index] as Result, equal));\n}\n\n/**\n * This function gives the difference of two shots of the same probe, or `undefined` when they agree. Two shots agree\n * when they give the same results, use the parts in the same order and cause the same effects. Without `paths`, the\n * resolutions do not count, as in the simulation of the plan.\n */\nfunction differs(a: Shot, b: Shot, equal: Env[\"equal\"], paths = true): string | undefined {\n if (!sameOutcome(a.result, b.result, equal)) return `The first evaluation gives ${resultText(a.result)}, and the second gives ${resultText(b.result)}.`;\n if (!sameResults(a, b, equal)) return \"The function that the result gives returns another result.\";\n const order = (shot: Shot): string => shot.calls.map((call) => `${call.later ? \"later \" : \"\"}${shot.keys[call.part] ?? String(call.part)}`).join(\", \");\n if (order(a) !== order(b)) return `The parts evaluate in another order: [${order(a)}] and [${order(b)}].`;\n const effects = (shot: Shot): string => shot.caused.map((effect) => effect.kind).join(\", \");\n if (a.caused.length !== b.caused.length || a.caused.some((effect, index) => effect.kind !== b.caused[index]?.kind || !sameValue(effect.payload, b.caused[index]?.payload, equal))) {\n return `The effects differ: [${effects(a)}] and [${effects(b)}].`;\n }\n if (!paths) return undefined;\n const asked = (shot: Shot): string => shot.asked.map((each) => valueText(each.path)).join(\", \");\n if (a.asked.length !== b.asked.length || a.asked.some((each, index) => !docEquals(each.path, b.asked[index]?.path))) return `The resolutions differ: [${asked(a)}] and [${asked(b)}].`;\n return undefined;\n}\n\n/** This function gives the probe of a finding. */\nfunction probeOf(sample: Sample, scenario: Scenario, doc: Envelope = sample.doc): ConformProbe {\n const results: Record<string, Result> = {};\n sample.split.parts.forEach((slot, index) => setField(results, slot.key, scenario.results[index] ?? NO_RESULT));\n const waits = scenario.running ? sample.split.parts.filter((_slot, index) => scenario.waits[index] === true).map((slot) => slot.key) : [];\n return { type: sample.type, doc, results, waits, caps: scenario.caps, running: scenario.running };\n}\n\n/** This function keeps the first finding of each obligation. */\nfunction report(env: Env, obligation: Obligation, reason: string, probe: () => ConformProbe): void {\n if (!env.found.has(obligation)) env.found.set(obligation, { obligation, reason, probe: probe() });\n}\n\nfunction thenable(value: unknown): boolean {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null && typeof (value as { readonly then?: unknown }).then === \"function\";\n}\n\n/** This function checks the record of one shot: the capabilities, the effects, the eager parts, the waits and the names. */\nfunction checkShot(env: Env, sample: Sample, contract: Contract, scenario: Scenario, shot: Shot): void {\n const probe = (): ConformProbe => probeOf(sample, scenario);\n const docCaps = shot.context.caps;\n const keyOf = (part: number): string => shot.keys[part] ?? String(part);\n // C1: each context that the code gives a part or an effect has only the capabilities of its document.\n for (const call of shot.calls) {\n if (!call.context.caps.every((cap) => permits(docCaps, cap))) {\n report(env, \"C1\", `The code gives the part ${keyOf(call.part)} ${capsText(call.context.caps)}, and its document has ${capsText(docCaps)}.`, probe);\n }\n }\n for (const effect of shot.caused) {\n if (!effect.context.caps.every((cap) => permits(docCaps, cap))) {\n report(env, \"C1\", `The code gives its effect ${effect.kind} ${capsText(effect.context.caps)}, and its document has ${capsText(docCaps)}.`, probe);\n }\n }\n if (contract.declares) {\n // C2: only the declared effects of the verb (VERB.EFFECTS).\n for (const effect of shot.caused) {\n if (!permits(contract.declared, effect.kind)) {\n report(env, \"C2\", `The code causes the effect ${effect.kind}, and the contract of ${sample.type} declares ${contract.declared.length === 0 ? \"no effects\" : capsText(contract.declared)}${env.verb === \"eval\" ? \"\" : ` for the verb ${env.verb}`}.`, probe);\n }\n }\n }\n if (contract.describes) {\n // C4: a pure kind causes no effect.\n const first = shot.caused[0];\n if (contract.pure && first !== undefined) report(env, \"C4\", `The kind ${sample.type} is pure, and the code causes the effect ${first.kind}.`, probe);\n // C3: each eager part evaluates when the result is a value.\n if (shot.result.ok) {\n sample.split.parts.forEach((_slot, index) => {\n if (sample.lazy[index] === true || shot.calls.some((call) => call.part === index && !call.later)) return;\n report(env, \"C3\", `The result is a value, and the code does not evaluate the part ${keyOf(index)}. No lazy rule of ${sample.type} covers the part.`, probe);\n });\n }\n }\n // C6: only a runner waits, and it passes each wait through.\n for (const problem of shot.problems) report(env, \"C6\", problem, probe);\n if (!env.runner && shot.result.ok && thenable(shot.result.value)) {\n report(env, \"C6\", \"The code of an evaluator gives a promise. Only a runner waits, with the steps of its parts and its effects.\", probe);\n }\n // C7: the names of each part are the names of the scope rules.\n const outer = shot.context.names;\n for (const call of shot.calls) {\n const given = call.context.names;\n const allowed = new Set(sample.names[call.part] ?? []);\n const bound = Object.keys(given).filter((key) => !Object.hasOwn(outer, key) || !Object.is(given[key], outer[key]));\n const extra = bound.filter((key) => !allowed.has(key));\n const lost = Object.keys(outer).filter((key) => !Object.hasOwn(given, key));\n const missing = [...allowed].filter((key) => !Object.hasOwn(given, key));\n const part = keyOf(call.part);\n if (extra.length > 0) {\n report(env, \"C7\", `The code binds ${extra.join(\", \")} for the part ${part}, and the scope rules of ${sample.type} give it ${allowed.size === 0 ? \"no names\" : [...allowed].join(\", \")}.`, probe);\n } else if (missing.length > 0) {\n report(env, \"C7\", `The scope rules of ${sample.type} give the part ${part} the names ${missing.join(\", \")}, and the code does not bind them.`, probe);\n } else if (lost.length > 0) {\n report(env, \"C7\", `The part ${part} does not see the names ${lost.join(\", \")} of its document.`, probe);\n }\n }\n}\n\n/**\n * This function gives a context with other values in each name and root that no resolution read (C4). The world and the\n * capabilities stay. A value that the code resolves keeps its value, because the list of reads holds that read.\n */\nfunction variedContext(ctx: Context, asked: readonly Asked[]): Context {\n const read = new Set<string>();\n for (const { path } of asked) {\n const root = path[0];\n read.add(root === \"names\" && isKey(path[1]) ? `names.${String(path[1])}` : String(root));\n }\n const names: Record<string, unknown> = {};\n for (const key of Object.keys(ctx.names)) setField(names, key, read.has(\"names\") || read.has(`names.${key}`) ? ctx.names[key] : { other: key });\n return { ...ctx, names, self: read.has(\"self\") ? ctx.self : { other: \"self\" }, event: read.has(\"event\") ? ctx.event : { other: \"event\" } };\n}\n\n/** This function examines one probe document with each check. */\nfunction examine(env: Env, sample: Sample, contract: Contract): void {\n const { under } = env;\n const fresh = (): Instance => instanceOf(env, under, sample.doc, sample.split, sample);\n const scenarios = scenariosOf(env, sample, contract, false);\n const code = fresh();\n const first = scenarios.map((scenario) => shoot(env, code, sample, scenario));\n scenarios.forEach((scenario, index) => checkShot(env, sample, contract, scenario, first[index] as Shot));\n\n // local: the same code gives the same record in the other order of the probes.\n const second: Shot[] = new Array<Shot>(scenarios.length);\n for (let index = scenarios.length - 1; index >= 0; index -= 1) second[index] = shoot(env, code, sample, scenarios[index] as Scenario);\n let clean = true;\n scenarios.forEach((scenario, index) => {\n const why = differs(first[index] as Shot, second[index] as Shot, env.equal);\n if (why === undefined) return;\n clean = false;\n report(env, \"local\", `The code keeps state from one call to the next. The same probe gives another record in a later call. ${why}`, () => probeOf(sample, scenario));\n });\n // C8: code that compiles again at the time of the evaluation gives the same record.\n if (clean && compiledForm(under)) {\n scenarios.forEach((scenario, index) => {\n const why = differs(second[index] as Shot, shoot(env, fresh(), sample, scenario), env.equal);\n if (why === undefined) return;\n clean = false;\n report(env, \"C8\", `The code reads a table of the machine or of the profile when it compiles, and the answer changes later. The code of an earlier compilation and new code differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n // The other comparisons need code without state, because each of them evaluates the probes again.\n if (!clean) return;\n\n // C5: other JSON in each part, and the same results of the parts, give the same record.\n if (sample.split.parts.length > 0) {\n const other = instanceOf(env, under, sample.other, sample.otherSplit, sample);\n const again = compiledForm(under) ? fresh() : code;\n scenarios.forEach((scenario) => {\n const why = differs(shoot(env, again, sample, scenario), shoot(env, other, sample, scenario), env.equal);\n if (why !== undefined) report(env, \"C5\", `The code reads the JSON of its parts. Two documents whose parts have other JSON and the same results differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n\n if (contract.describes) {\n // C4: a pure kind gives the same record in a context with other values, when each resolution gives the same answer.\n if (contract.pure) {\n scenarios.forEach((scenario, index) => {\n const before = first[index] as Shot;\n const varied = shoot(env, code, sample, scenario, { context: variedContext(before.context, before.asked), replay: before.asked });\n const why = differs(before, varied, env.equal);\n if (why !== undefined) {\n report(env, \"C4\", `The kind ${sample.type} is pure, and the code reads the context outside resolve. Other values in the roots, with the same answers of resolve, change the record. ${why}`, () => probeOf(sample, scenario));\n }\n });\n }\n // C3: a lazy part evaluates only when its result counts.\n scenarios.forEach((scenario, index) => {\n const before = first[index] as Shot;\n const evaluated = new Set(before.calls.filter((call) => !call.later && sample.lazy[call.part] === true).map((call) => call.part));\n for (const part of evaluated) {\n const counts = env.results.some((result) => {\n if (result === scenario.results[part]) return false;\n const results = scenario.results.map((each, at) => (at === part ? result : each));\n return !sameResults(before, shoot(env, code, sample, { ...scenario, results }), env.equal);\n });\n if (!counts) {\n report(env, \"C3\", `The code evaluates the lazy part ${before.keys[part] ?? String(part)}, and no result of that part changes the result. A lazy part evaluates only when its result counts.`, () => probeOf(sample, scenario));\n }\n }\n });\n }\n\n // agree: the compiled code and its definition give the same record (the local lemma of SIM-PLAN).\n const definition = env.definition;\n if (definition !== undefined) {\n const defined = instanceOf(env, definition, sample.doc, sample.split, sample);\n scenarios.forEach((scenario, index) => {\n const why = differs(first[index] as Shot, shoot(env, defined, sample, scenario), env.equal, false);\n if (why !== undefined) report(env, \"agree\", `The code and its definition for the reference differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n\n // C6 and the other checks of one shot in a run: each probe part can wait.\n if (env.runner) {\n for (const scenario of scenariosOf(env, sample, contract, true)) checkShot(env, sample, contract, scenario, shoot(env, code, sample, scenario));\n }\n}\n\n/**\n * This function examines one evaluator or runner of a machine against the obligations of host code (K92, D36). It\n * starts the code directly, without the kernel, with probe parts and a probe runtime. It generates probe documents from\n * the contract of each kind that names the code, and it gives the probe parts chosen and random results.\n *\n * The checks follow the obligations C1 to C8 of `docs/SEMANTICS.md`. Two more checks follow the premises of the\n * simulation of the plan. The check `local` finds state that stays from one call to the next. The check `agree` compares\n * compiled code with its definition. The\n * finding of an obligation names the first probe that breaks it. An empty list means that each probe conforms.\n *\n * @param machine - The machine with the code and the world of the kinds.\n * @param name - The name of the evaluator or of the runner. A runner wins over an evaluator of the same name.\n * @param options - The verb, the types and the values of the probe documents, and the results of the probe parts. Also\n * the definitions, the capabilities, the names, the seed, the mock and the rule of equality.\n * @returns The first finding of each obligation that the code breaks, in the order of the obligations.\n * @throws {Error} The machine has no code with the name, or no kind names it and the options give no types.\n */\nexport function conforms(machine: Machine, name: string, options: ConformOptions = {}): readonly Finding[] {\n const verb = options.verb ?? \"eval\";\n const runnerCode = own(machine.runners, name);\n const code = runnerCode ?? own(machine.evaluators, name);\n if (code === undefined) throw new Error(`The machine has no evaluator and no runner with the name ${name}.`);\n const runner = runnerCode !== undefined;\n const env: Env = {\n machine,\n name,\n verb,\n under: underOf(code, runner),\n definition: definitionOf(machine, name, runner, options.definitions),\n runner,\n results: options.results ?? RESULTS,\n names: options.names ?? NAMES,\n runs: options.runs ?? 12,\n random: random(options.seed ?? 1),\n perform: options.perform,\n equal: options.equal,\n found: new Map(),\n };\n const types = options.types ?? typesNaming(machine.world, name, verb);\n if (types.length === 0) throw new Error(`No kind of the world names ${name} for the verb ${verb}. Give the types of the probe documents in the option types.`);\n for (const type of types) {\n const found = lookupKind(machine.world, type);\n if (!found.ok) throw new Error(`The world has no kind for the type ${typeName(type)}.`);\n const contract = contractOf(env, found.kind, found.path, options.caps);\n const extra = own(options.values, typeName(type)) ?? own(options.values, found.path.join(\".\")) ?? [];\n for (const sample of samplesOf(type, found.path, found.kind, contract, extra)) examine(env, sample, contract);\n }\n return ORDER.filter((obligation) => env.found.has(obligation)).map((obligation) => env.found.get(obligation) as Finding);\n}\n","import { type Key, docEquals, equalWith } from \"./doc.ts\";\nimport type { EvalError, Result } from \"./errors.ts\";\nimport { Held } from \"./formula.ts\";\n\n/**\n * This function tells if two results are the same for an early cutoff (RESULT.SAME). A schedule uses it to stop the\n * work when a part that evaluates again gives the same result. A wrong `true` keeps a stale value, but a wrong `false`\n * only costs work. Thus each rule gives `false` when it is not sure.\n *\n * - Two values compare by the rules of `docEquals`. Lists and plain records compare by their items and fields. Each\n * other value compares with `Object.is`.\n * - Thus `-0` is not `0`, and `NaN` is `NaN`. A date, a map and a closure of `fn` are the same only as themselves.\n * - Two errors are the same when they have the same code, reason and place (RESULT.SAME-ERROR). The cause is not\n * compared. A `Held` value compares its error by the same rule.\n * - A value and an error are not the same.\n *\n * `sameValue` of `agree` uses the same walk, with rules for two tiers (D20). It compares two closures by their\n * parameters, and two errors by their code and place.\n *\n * @param a - The earlier result.\n * @param b - The new result.\n * @param equal - The rule of the host for two values, for example two dates. It answers first, and `undefined` gives the rules above.\n * @returns `true` when the results are the same.\n */\nexport function sameResult(a: Result<unknown>, b: Result<unknown>, equal?: (a: unknown, b: unknown) => boolean | undefined): boolean {\n if (a.ok && b.ok) return equalWith(a.value, b.value, equal === undefined ? sameHeld : (x, y) => equal(x, y) ?? sameHeld(x, y));\n if (!a.ok && !b.ok) return sameError(a.error, b.error);\n return false;\n}\n\n/** The rule of `sameResult` for held errors. Two `Held` values are the same when their errors are the same. */\nfunction sameHeld(x: unknown, y: unknown): boolean | undefined {\n if (x instanceof Held || y instanceof Held) return x instanceof Held && y instanceof Held && sameError(x.error, y.error);\n return undefined;\n}\n\n/** Two errors are the same when they have the same code, reason and place. An error without a place has no place in both. */\nfunction sameError(a: EvalError, b: EvalError): boolean {\n if (a.code !== b.code || a.reason !== b.reason) return false;\n if (a.place === undefined || b.place === undefined) return a.place === b.place;\n return docEquals(a.place as readonly Key[], b.place as readonly Key[]);\n}\n","import { docEquals } from \"./doc.ts\";\nimport { type Result, ok } from \"./errors.ts\";\nimport type { Context, Hop } from \"./deref.ts\";\nimport { type Machine, type Plan, type Read, readAgain, rootContext } from \"./evaluate.ts\";\nimport { Held } from \"./formula.ts\";\nimport { sameResult } from \"./same.ts\";\n\n/*\n * The verifying trace of a schedule (R4 P3, D26). An evaluation with the option `reads` records each path that it\n * resolves, and what the path reached. A pure document is a function of its reads. Thus when each free read reaches\n * the same thing in a new context, the old result stays valid, and the schedule keeps it without an evaluation.\n */\n\n/** The answer of `verifyReads`: the old result stays valid, or the first read that reaches another thing. */\nexport type ReadsCheck =\n | { readonly same: true }\n | {\n readonly same: false;\n /** The index of the first changed read in the list. */\n readonly index: number;\n /** The first changed read, as the evaluation recorded it. */\n readonly read: Read;\n /** What the path of that read reaches in the new context. */\n readonly now: Result;\n };\n\n/** The options of `verifyReads`. */\nexport interface VerifyOptions {\n /**\n * The rule of the host for two things, as in `sameResult`. It answers first, and `undefined` gives the rules of\n * `sameResult`. An example is a rule for a host thing that keeps a version.\n *\n * @param a - The thing of the recorded read.\n * @param b - The thing in the new context.\n * @returns `true` when the two things are the same, or `undefined` for the rules of `sameResult`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n}\n\n/** One answer serves each list whose reads are all the same. */\nconst SAME: ReadsCheck = /* @__PURE__ */ Object.freeze({ same: true });\n\n/** This function tells if two lists of hops are the same: the same steps, rungs and things, in order. */\nfunction sameHops(a: readonly Hop[], b: readonly Hop[] | undefined, equal: VerifyOptions[\"equal\"]): boolean {\n if (b === undefined || a.length !== b.length) return false;\n for (let index = 0; index < a.length; index += 1) {\n const x = a[index] as Hop;\n const y = b[index] as Hop;\n if (x.by !== y.by || !docEquals(x.step, y.step) || !sameResult(ok(x.thing), ok(y.thing), equal)) return false;\n }\n return true;\n}\n\n/**\n * This function gives the error of a name that holds a held error and stops a longer path, or `undefined`. A\n * reference of the formula kit tests the binding of its first name before it resolves the rest of the path\n * (FORMULA.LET). The resolution of the whole path does not show that test.\n */\nfunction heldStop(root: Context, path: readonly unknown[]): Result | undefined {\n const name = path[1];\n if (path.length <= 2 || path[0] !== \"names\" || typeof name !== \"string\" || !Object.hasOwn(root.names, name)) return undefined;\n const bound = root.names[name];\n return bound instanceof Held ? { ok: false, error: bound.error } : undefined;\n}\n\n/**\n * This function tells if an old result stays valid in a new context (READS.VERIFY, D26). It resolves the path of\n * each free read again, in the order of the list, and it compares what the path reaches with `sameResult`. It stops at\n * the first read that reaches another thing, and it gives that read (READS.CHANGED).\n *\n * - A read that is not free reads a binding that a kind made from earlier reads, for example a name of `let`. The\n * function does not resolve it again.\n * - A thing compares as in `sameResult`. Thus a host thing or a date is the same only as itself. A host gives a new\n * object for a new state, or the option `equal`.\n * - A longer path through a name that holds a `Held` in the new context is a changed read. A reference of the formula\n * kit gives the error of that binding, and the resolution of the path does not show it.\n * - The answer is sound only for a pure document (FACTS.PURE). A document with an effect, a volatile operation or an\n * extension of a profile can read outside `resolve`. The schedule asks `factsOf` first.\n *\n * The values of the context must not change in place, as PLAN.CACHE says for the documents. A value that changed in\n * place is the same object, thus the function cannot see the change.\n *\n * @param target - The machine of the evaluation, or its plan.\n * @param reads - The reads of the evaluation, from the option `reads`.\n * @param context - The new context.\n * @param options - The rule of the host for two things.\n * @returns `{ same: true }` when each free read reaches the same thing, or else the first changed read.\n */\nexport function verifyReads(target: Machine | Plan, reads: readonly Read[], context: Context, options: VerifyOptions = {}): ReadsCheck {\n const machine = \"evaluators\" in target ? target : target.machine;\n const root = rootContext(machine, context);\n const equal = options.equal;\n for (let index = 0; index < reads.length; index += 1) {\n const read = reads[index] as Read;\n if (!read.free) continue;\n const stop = heldStop(root, read.path);\n if (stop !== undefined) return { same: false, index, read, now: stop };\n const asked = read.hops !== undefined;\n const now = readAgain(machine, root, read.path, asked);\n if (!sameResult(read.reached, now.reached, equal) || (read.hops !== undefined && !sameHops(read.hops, now.hops, equal))) {\n return { same: false, index, read, now: now.reached };\n }\n }\n return SAME;\n}\n","import type { Context } from \"./deref.ts\";\nimport type { Result } from \"./errors.ts\";\nimport { type Machine, type Plan, type PrepareOptions, type Read, prepare } from \"./evaluate.ts\";\nimport { type DocFacts, type FactsOptions, factsOf } from \"./facts.ts\";\nimport { type VerifyOptions, verifyReads } from \"./reads.ts\";\n\n/*\n * Two levels of durability (R4 P7, D30). The plan and the facts of a document depend only on the structure: the\n * machine and the documents. A result also depends on the data: the values that a context gives. A host keeps one\n * epoch for each level. Thus a change of data keeps each plan and each fact, and it only verifies or evaluates.\n */\n\n/** The two epochs of a host (DURABLE.EPOCHS). Each epoch counts the changes of its level. */\nexport interface Epochs {\n /** The count of the changes of the structure: a new machine, or an edit of a document. */\n readonly structure: number;\n /** The count of the changes of the data. A change of the structure is also a change of the data. */\n readonly data: number;\n}\n\n/** The work of a durable cache since its start. A schedule reads it as a measure, not as a rule (R4). */\nexport interface DurableCounts {\n /** The compilations: the calls of `prepare`. */\n readonly compiles: number;\n /** The calls of `factsOf`. */\n readonly facts: number;\n /** The evaluations of a plan. */\n readonly evaluations: number;\n /** The calls of `verifyReads`. */\n readonly verifications: number;\n /** The results that stayed without an evaluation. */\n readonly reuses: number;\n}\n\n/** The options of `durable`. */\nexport interface DurableOptions {\n /** The type of a bare root value, for each plan and each fact. */\n readonly declaredType?: string;\n /** The verb of each plan and each fact. The default is `eval` (VERB.PREPARE). */\n readonly verb?: string;\n /** The volatile reads of the host, as in `factsOf`. A document with such a read is not pure, thus it evaluates again after each change of data. */\n readonly volatile?: FactsOptions[\"volatile\"];\n /** The rule of the host for two things, as in `verifyReads`. */\n readonly equal?: VerifyOptions[\"equal\"];\n}\n\n/**\n * A cache of plans, facts and results with two levels of durability (D30). A host or a schedule tells the cache each\n * change of the structure and each change of the data.\n */\nexport interface Durable {\n /** The machine of the current structure epoch. */\n readonly machine: Machine;\n /** The current epochs. A schedule builds again what depends on the whole structure when `structure` changes, for example a graph of the nodes. */\n readonly epochs: Epochs;\n /** The work since the start. */\n readonly counts: DurableCounts;\n /**\n * This function gives the plan of a document. A document object compiles one time for a machine (DURABLE.STRUCTURE).\n * A change of data compiles nothing (DURABLE.DATA).\n *\n * @param doc - The document, as JSON.\n * @returns The plan.\n */\n plan(doc: unknown): Plan;\n /**\n * This function gives the static facts of a document. A document object computes its facts one time for a machine.\n *\n * @param doc - The document, as JSON.\n * @returns The facts.\n */\n facts(doc: unknown): DocFacts;\n /**\n * This function gives the result of the document of a node (DURABLE.REUSE). The key names the node, and in one data\n * epoch the context of a key gives the same data.\n *\n * - In the data epoch of its result, a key with the same plan gives that result again.\n * - After a change of data, a pure document verifies its reads, and it keeps its result when each read is the same.\n * - Each other document evaluates again.\n *\n * @param key - The name of the node in the host, for example the name of a cell.\n * @param doc - The document of the node.\n * @param context - The context of the node.\n * @returns The result.\n */\n evaluate(key: unknown, doc: unknown, context: Context): Result;\n /** This function tells the cache that the data changed: a context gives a new value (DURABLE.EPOCHS). */\n changeData(): void;\n /**\n * This function tells the cache that the structure changed (DURABLE.EPOCHS). An edit of a document gives a new\n * document object, and only that object compiles. A new machine drops each plan, each fact and each result.\n *\n * @param machine - The new machine, or `undefined` for an edit of a document.\n */\n changeStructure(machine?: Machine): void;\n /**\n * This function drops the result of a node, for example a node that the host removed.\n *\n * @param key - The name of the node.\n */\n forget(key: unknown): void;\n}\n\n/** The result of one node, with what it depends on. */\ninterface Entry {\n /** The plan of the evaluation. A new document or a new machine gives another plan. */\n readonly plan: Plan;\n readonly result: Result;\n /** The reads of the evaluation, only for a pure document. */\n readonly reads: readonly Read[] | undefined;\n /** The data epoch in which the result was last valid. */\n data: number;\n}\n\n/** The most values that a cache of value documents keeps, as in `planner`. */\nconst MAX_VALUES = 1000;\n\n/** No reads. One frozen list serves each result of a pure document without reads. */\nconst NO_READS: readonly Read[] = /* @__PURE__ */ Object.freeze([]);\n\n/** The key of the document `-0` in a cache of value documents. A `Map` finds the entry of `0` for `-0`. */\nconst NEGATIVE_ZERO = /* @__PURE__ */ Symbol(\"coeval.negative-zero\");\n\n/** This function makes a cache by document. A document object gives its value one time, as PLAN.CACHE says. */\nfunction byDocument<T>(make: (doc: unknown) => T): (doc: unknown) => T {\n const objects = new WeakMap<object, T>();\n const values = new Map<unknown, T>();\n return (doc) => {\n if (typeof doc === \"object\" && doc !== null) {\n if (objects.has(doc)) return objects.get(doc) as T;\n const made = make(doc);\n objects.set(doc, made);\n return made;\n }\n const key = Object.is(doc, -0) ? NEGATIVE_ZERO : doc;\n if (values.has(key)) return values.get(key) as T;\n const made = make(doc);\n if (values.size >= MAX_VALUES) values.clear();\n values.set(key, made);\n return made;\n };\n}\n\n/**\n * This function makes a cache with two levels of durability for a host or a schedule (R4 P7, D30). The structure is\n * the machine and the documents. The data is each value that a context gives: the names, `self`, `event`, the\n * capabilities and the world of the host.\n *\n * - A plan and the facts depend only on the structure. A document object compiles one time for a machine, thus a\n * change of data compiles nothing (DURABLE.DATA).\n * - A result depends on the data too. It stays in its data epoch. After a change of data, a pure document verifies\n * its reads with `verifyReads`, and each other document evaluates again.\n * - An edit gives a new document object, thus only that document compiles. A new machine drops each plan, each fact\n * and each result (DURABLE.STRUCTURE).\n *\n * The host keeps two promises. In one data epoch, the context of a key gives the same data. The values of a\n * context and the documents do not change in place, as PLAN.CACHE and `verifyReads` say.\n *\n * @param machine - The machine of the first structure epoch.\n * @param options - The type of a bare root value, the verb, the volatile reads and the rule of the host for two things.\n * @returns The cache.\n */\nexport function durable(machine: Machine, options: DurableOptions = {}): Durable {\n const prepareOptions: PrepareOptions = {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n };\n const factsOptions: FactsOptions = { ...prepareOptions, ...(options.volatile === undefined ? {} : { volatile: options.volatile }) };\n const verifyOptions: VerifyOptions = options.equal === undefined ? {} : { equal: options.equal };\n const counts = { compiles: 0, facts: 0, evaluations: 0, verifications: 0, reuses: 0 };\n const results = new Map<unknown, Entry>();\n let current = machine;\n let epochs: Epochs = { structure: 0, data: 0 };\n const plansOf = (m: Machine): ((doc: unknown) => Plan) =>\n byDocument((doc) => {\n counts.compiles += 1;\n return prepare(m, doc, prepareOptions);\n });\n const factsFor = (m: Machine): ((doc: unknown) => DocFacts) =>\n byDocument((doc) => {\n counts.facts += 1;\n return factsOf(m, doc, factsOptions);\n });\n let plans = plansOf(machine);\n let facts = factsFor(machine);\n return {\n get machine() {\n return current;\n },\n get epochs() {\n return epochs;\n },\n get counts() {\n return { ...counts };\n },\n plan: (doc) => plans(doc),\n facts: (doc) => facts(doc),\n evaluate(key, doc, context) {\n const plan = plans(doc);\n const entry = results.get(key);\n if (entry !== undefined && entry.plan === plan) {\n if (entry.data === epochs.data) {\n counts.reuses += 1;\n return entry.result;\n }\n if (entry.reads !== undefined) {\n counts.verifications += 1;\n if (verifyReads(plan, entry.reads, context, verifyOptions).same) {\n entry.data = epochs.data;\n counts.reuses += 1;\n return entry.result;\n }\n }\n }\n // Only a pure document is a function of its reads (FACTS.PURE), thus only its reads can keep its result.\n const reads: Read[] | undefined = facts(doc).pure ? [] : undefined;\n counts.evaluations += 1;\n const result = plan.evaluate(context, reads === undefined ? undefined : { reads });\n // A list that grows by push keeps room for more reads. A copy of a short list is smaller (PLAN.LEAN).\n results.set(key, { plan, result, reads: reads === undefined ? undefined : reads.length === 0 ? NO_READS : reads.slice(), data: epochs.data });\n return result;\n },\n changeData() {\n epochs = { structure: epochs.structure, data: epochs.data + 1 };\n },\n changeStructure(next) {\n epochs = { structure: epochs.structure + 1, data: epochs.data + 1 };\n if (next === undefined || next === current) return;\n current = next;\n plans = plansOf(next);\n facts = factsFor(next);\n results.clear();\n },\n forget(key) {\n results.delete(key);\n },\n };\n}\n","import type { Side } from \"./world.ts\";\n\n/*\n * The analysis of a graph of nodes (S2, R4 P5, D33). A host gives each node with its edges: the nodes that it reads.\n * The analysis gives the strongly connected components, the heights of a push schedule, the layers of independent\n * nodes, the nodes that an observer needs and the static cycles. Each function walks the graph with its own stack,\n * not with the stack of the host. Thus a chain of 100000 nodes does not overflow (GRAPH.SCC).\n */\n\n/** One edge of a graph of nodes: a read of a node by another node. `NodeEdge` of a schedule is such an edge. */\nexport interface GraphEdge<Id> {\n /** The node that the read reaches. It is `undefined` when the read can reach each node (GRAPH.UNKNOWN). */\n readonly to: Id | undefined;\n /** `true` when only a lazy part reaches the read. An evaluation can then give a value without it (FACTS.LAZY). */\n readonly lazy: boolean;\n}\n\n/** One node of a graph, with its edges. `NodeInfo` of a schedule is such a node. */\nexport interface GraphNode<Id> {\n /** The edges to the nodes that the node reads. */\n readonly edges: readonly GraphEdge<Id>[];\n /** The side of the node. A node on the run side is a sink: no edge reaches it (SCHED.SIDE). The default is `derive`. */\n readonly side?: Side;\n}\n\n/**\n * A graph of nodes, by name. The order of the map is the order of the nodes in each answer. The function `graph` of\n * a schedule gives such a graph. An edge to a name that is not in the map, or to a sink, is not an edge of the\n * analysis.\n */\nexport type NodeGraph<Id> = ReadonlyMap<Id, GraphNode<Id>>;\n\n/** The options of an analysis. */\nexport interface GraphOptions {\n /**\n * `true`: the analysis keeps only the eager edges with a target node. Such a read occurs in each evaluation in\n * which each document around it gives a value (FACTS.LAZY). The default keeps each edge.\n */\n readonly eager?: boolean;\n}\n\n/** One static cycle of a graph (GRAPH.CYCLE). */\nexport interface GraphCycle<Id> {\n /** The nodes of the cycle, in the order of the graph. */\n readonly nodes: readonly Id[];\n /**\n * `true` when the eager edges with a target close the cycle. `false` when the cycle needs a lazy edge or an edge\n * without a target. The value of each node still comes from the demand (D31).\n */\n readonly certain: boolean;\n}\n\n/**\n * A graph with a number for each node, and its edges in arrays. The edges of the node `v` are the items of `targets`\n * from `start[v]` up to `start[v + 1]`. An edge without a target goes to the extra node `all`, and `all` reaches each\n * node that is not a sink. Thus such an edge costs one edge, not one edge for each node.\n */\ninterface Indexed<Id> {\n readonly ids: readonly Id[];\n /** The count of the nodes, with the node `all` when the graph has it. */\n readonly size: number;\n readonly start: Int32Array;\n readonly targets: Int32Array;\n /** The number of the node `all`, or `-1` when no edge goes to it. */\n readonly all: number;\n}\n\n/** This function gives the indexed form of a graph, with the edges that the options keep. */\nfunction indexed<Id>(graph: NodeGraph<Id>, options: GraphOptions): Indexed<Id> {\n const eager = options.eager === true;\n const ids = [...graph.keys()];\n const count = ids.length;\n const numbers = new Map<Id, number>();\n const sink = new Uint8Array(count);\n ids.forEach((id, index) => {\n numbers.set(id, index);\n if (graph.get(id)?.side === \"run\") sink[index] = 1;\n });\n const start = new Int32Array(count + 2);\n const targets: number[] = [];\n let unknown = false;\n let from = 0;\n for (const node of graph.values()) {\n start[from] = targets.length;\n for (const edge of node.edges) {\n if (eager && edge.lazy) continue;\n if (edge.to === undefined) {\n if (eager) continue;\n unknown = true;\n targets.push(count);\n continue;\n }\n const to = numbers.get(edge.to);\n if (to !== undefined && sink[to] === 0) targets.push(to);\n }\n from += 1;\n }\n start[count] = targets.length;\n if (unknown) for (let to = 0; to < count; to += 1) if (sink[to] === 0) targets.push(to);\n start[count + 1] = targets.length;\n return { ids, size: unknown ? count + 1 : count, start, targets: Int32Array.from(targets), all: unknown ? count : -1 };\n}\n\n/** The strongly connected components of an indexed graph. */\ninterface Strong {\n /** The number of the component of each node. */\n readonly of: Int32Array;\n /** The nodes of each component. Each component comes after each component that it reaches. */\n readonly list: readonly (readonly number[])[];\n}\n\n/**\n * This function finds the strongly connected components with the algorithm of Tarjan. It keeps its own stack of\n * calls in two arrays, thus a long chain does not overflow the stack of the host. Each component comes after each\n * component that its nodes reach: the deepest component comes first.\n */\nfunction strong(graph: Indexed<unknown>): Strong {\n const { size, start, targets } = graph;\n const order = new Int32Array(size).fill(-1);\n const low = new Int32Array(size);\n const of = new Int32Array(size).fill(-1);\n // The nodes of the components that are still open.\n const open = new Int32Array(size);\n const onOpen = new Uint8Array(size);\n // The stack of calls: a node, and the position of its next edge.\n const calls = new Int32Array(size);\n const next = new Int32Array(size);\n const list: number[][] = [];\n let top = 0;\n let count = 0;\n const enter = (node: number, depth: number): void => {\n order[node] = count;\n low[node] = count;\n count += 1;\n open[top] = node;\n top += 1;\n onOpen[node] = 1;\n calls[depth] = node;\n next[depth] = start[node] as number;\n };\n for (let root = 0; root < size; root += 1) {\n if (order[root] !== -1) continue;\n enter(root, 0);\n let depth = 1;\n while (depth > 0) {\n const node = calls[depth - 1] as number;\n const edge = next[depth - 1] as number;\n if (edge < (start[node + 1] as number)) {\n next[depth - 1] = edge + 1;\n const to = targets[edge] as number;\n if (order[to] === -1) {\n enter(to, depth);\n depth += 1;\n } else if (onOpen[to] === 1 && (order[to] as number) < (low[node] as number)) {\n low[node] = order[to] as number;\n }\n continue;\n }\n depth -= 1;\n if (low[node] === order[node]) {\n const members: number[] = [];\n let member: number;\n do {\n top -= 1;\n member = open[top] as number;\n onOpen[member] = 0;\n of[member] = list.length;\n members.push(member);\n } while (member !== node);\n list.push(members.sort((a, b) => a - b));\n }\n if (depth > 0) {\n const reader = calls[depth - 1] as number;\n if ((low[node] as number) < (low[reader] as number)) low[reader] = low[node] as number;\n }\n }\n }\n return { of, list };\n}\n\n/** This function tells if a component has a cycle: two or more nodes, or one node with an edge to itself. */\nfunction cyclic(graph: Indexed<unknown>, members: readonly number[]): boolean {\n if (members.length > 1) return true;\n const node = members[0] as number;\n for (let edge = graph.start[node] as number; edge < (graph.start[node + 1] as number); edge += 1) if (graph.targets[edge] === node) return true;\n return false;\n}\n\n/** This function gives the names of the nodes of a component, without the node `all`. */\nfunction named<Id>(graph: Indexed<Id>, members: readonly number[]): Id[] {\n const out: Id[] = [];\n for (const member of members) if (member !== graph.all) out.push(graph.ids[member] as Id);\n return out;\n}\n\n/** This function gives the height of each component, in the order of `strong`. The node `all` adds no height. */\nfunction heightsOf(graph: Indexed<unknown>, found: Strong): Int32Array {\n const { start, targets } = graph;\n const heights = new Int32Array(found.list.length);\n found.list.forEach((members, component) => {\n let highest = -1;\n let real = false;\n for (const node of members) {\n if (node !== graph.all) real = true;\n for (let edge = start[node] as number; edge < (start[node + 1] as number); edge += 1) {\n const other = found.of[targets[edge] as number] as number;\n if (other !== component && (heights[other] as number) > highest) highest = heights[other] as number;\n }\n }\n heights[component] = real ? highest + 1 : highest;\n });\n return heights;\n}\n\n/**\n * This function gives the strongly connected components of a graph of nodes (GRAPH.SCC), with the algorithm of\n * Tarjan. It keeps its own stack, thus a chain of 100000 nodes does not overflow the stack of the host.\n *\n * - Each component comes after each component that it reads: the deepest component comes first.\n * - A node that is on no cycle is a component of one node.\n * - The nodes of a component are in the order of the graph.\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The components, deepest first.\n */\nexport function components<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): readonly (readonly Id[])[] {\n const index = indexed(graph, options);\n const out: (readonly Id[])[] = [];\n for (const members of strong(index).list) {\n const names = named(index, members);\n if (names.length > 0) out.push(names);\n }\n return out;\n}\n\n/**\n * This function gives the height of each node: the order of a push schedule (GRAPH.ORDER). A schedule that evaluates\n * the nodes from the lowest height up evaluates each node after each node that it reads, except on a cycle.\n *\n * - A node that reads no node outside its component has the height 0.\n * - Each other node is one higher than the highest node that it reads outside its component.\n * - The nodes of one component have one height.\n * - An edge without a target reads each node that is not a sink (GRAPH.UNKNOWN).\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The height of each node, in the order of the graph.\n */\nexport function heights<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): ReadonlyMap<Id, number> {\n const index = indexed(graph, options);\n const found = strong(index);\n const levels = heightsOf(index, found);\n const out = new Map<Id, number>();\n index.ids.forEach((id, node) => out.set(id, levels[found.of[node] as number] as number));\n return out;\n}\n\n/**\n * This function puts the nodes in layers by their heights, in linear time (GRAPH.LAYERS). The first layer has the\n * height 0. Two nodes of one layer read each other only inside one component. Thus a push schedule can evaluate the\n * components of one layer at the same time.\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The layers, from the height 0 up. Each layer keeps the order of the graph.\n */\nexport function nodeLayers<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): readonly (readonly Id[])[] {\n const out: Id[][] = [];\n for (const [id, height] of heights(graph, options)) {\n while (out.length <= height) out.push([]);\n out[height]?.push(id);\n }\n return out;\n}\n\n/**\n * This function gives the nodes that a set of observed nodes needs (GRAPH.NECESSARY). These are the observed nodes,\n * and each node with a path of edges from them. A push schedule evaluates only these nodes. An observed name that is\n * not a node of the graph adds nothing.\n *\n * @param graph - The nodes, each with its edges.\n * @param observed - The nodes that the host shows or reads.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The necessary nodes, in the order of the graph.\n */\nexport function necessary<Id>(graph: NodeGraph<Id>, observed: Iterable<Id>, options: GraphOptions = {}): ReadonlySet<Id> {\n const index = indexed(graph, options);\n const numbers = new Map<Id, number>();\n index.ids.forEach((id, node) => numbers.set(id, node));\n const seen = new Uint8Array(index.size);\n const work: number[] = [];\n for (const id of observed) {\n const node = numbers.get(id);\n if (node === undefined || seen[node] === 1) continue;\n seen[node] = 1;\n work.push(node);\n }\n while (work.length > 0) {\n const node = work.pop() as number;\n for (let edge = index.start[node] as number; edge < (index.start[node + 1] as number); edge += 1) {\n const to = index.targets[edge] as number;\n if (seen[to] === 1) continue;\n seen[to] = 1;\n work.push(to);\n }\n }\n const out = new Set<Id>();\n index.ids.forEach((id, node) => {\n if (seen[node] === 1) out.add(id);\n });\n return out;\n}\n\n/**\n * This function gives the static cycles of a graph (GRAPH.CYCLE): each component with two or more nodes, and each\n * node with an edge to itself. A cycle of the eager edges with a target is certain, and `check` or a host can report\n * it before a run. Another cycle is possible: an evaluation can skip a lazy read.\n *\n * - A component of all the edges that is also a component of the eager edges is one certain cycle.\n * - Each other component of all the edges is one possible cycle, and each certain cycle in it comes after it.\n * - A read can still fail before it occurs. Thus the demand of D31, not a static cycle, gives the value of each node.\n *\n * @param graph - The nodes, each with its edges.\n * @returns The cycles, deepest first.\n */\nexport function cycles<Id>(graph: NodeGraph<Id>): readonly GraphCycle<Id>[] {\n const every = indexed(graph, {});\n const found = strong(every);\n const eager = indexed(graph, { eager: true });\n // The certain cycles, by the component of all the edges that holds them.\n const inside = new Map<number, (readonly number[])[]>();\n for (const members of strong(eager).list) {\n if (!cyclic(eager, members)) continue;\n const component = found.of[members[0] as number] as number;\n const list = inside.get(component);\n if (list === undefined) inside.set(component, [members]);\n else list.push(members);\n }\n const out: GraphCycle<Id>[] = [];\n found.list.forEach((members, component) => {\n if (!cyclic(every, members)) return;\n const nodes = named(every, members);\n const certain = inside.get(component) ?? [];\n if (certain.length === 1 && certain[0]?.length === nodes.length) {\n out.push({ nodes, certain: true });\n return;\n }\n out.push({ nodes, certain: false });\n for (const part of certain) out.push({ nodes: named(eager, part), certain: true });\n });\n return out;\n}\n\n/**\n * This function gives the nodes that a demand of a node needs first, deepest first (SCHED.LONG-CHAIN). It follows the\n * eager edges with a target from the node, with its own stack. Each node comes after each node that it reads, except\n * on a cycle, as in an order by heights. The walk costs only the nodes that it enters.\n *\n * @param from - The node of the demand. It is not in the answer.\n * @param edgesOf - This function gives the edges of a node, or `undefined` for a node that the walk does not enter.\n * @returns The nodes, deepest first.\n */\nexport function deepestFirst<Id>(from: Id, edgesOf: (id: Id) => readonly GraphEdge<Id>[] | undefined): readonly Id[] {\n const out: Id[] = [];\n const first = edgesOf(from);\n if (first === undefined) return out;\n const seen = new Set<Id>([from]);\n const nodes: Id[] = [from];\n const lists: (readonly GraphEdge<Id>[])[] = [first];\n const positions: number[] = [0];\n while (nodes.length > 0) {\n const top = nodes.length - 1;\n const edges = lists[top] as readonly GraphEdge<Id>[];\n let position = positions[top] as number;\n let entered = false;\n while (position < edges.length) {\n const edge = edges[position] as GraphEdge<Id>;\n position += 1;\n const to = edge.to;\n if (edge.lazy || to === undefined || seen.has(to)) continue;\n seen.add(to);\n const more = edgesOf(to);\n if (more === undefined) continue;\n positions[top] = position;\n nodes.push(to);\n lists.push(more);\n positions.push(0);\n entered = true;\n break;\n }\n if (entered) continue;\n const done = nodes.pop() as Id;\n lists.pop();\n positions.pop();\n if (nodes.length > 0) out.push(done);\n }\n return out;\n}\n","import type { Key } from \"./doc.ts\";\nimport { type Context, type HostThing, type Thing, THING, context as contextOf } from \"./deref.ts\";\nimport { type Failed, type Result, Failure, fail } from \"./errors.ts\";\nimport { type Machine, type Perform, type StopSignal, rootContext } from \"./evaluate.ts\";\nimport { type DurableCounts, type DurableOptions, type Epochs, durable } from \"./durable.ts\";\nimport type { DocFacts, StaticRead } from \"./facts.ts\";\nimport { deepestFirst } from \"./graph.ts\";\nimport type { Side } from \"./world.ts\";\n\n/*\n * The interface of a schedule (S1, D31). A host gives named documents. Each document is a node, and the root `world`\n * of each node reaches the other nodes. The static reads give the edges of the graph, and the contracts give the side\n * of each node. A demand evaluates a node and each node that it reads, through `durable`. Thus after a change, a node\n * evaluates again only when one of its reads changed. A demand of the host first demands the nodes that the eager\n * edges reach, deepest first (S2a, D33). Thus a long chain does not use the stack of the host for each node.\n */\n\n/** One edge of a graph of nodes: a static read of a node from the document of another node (SCHED.EDGES). */\nexport interface NodeEdge {\n /**\n * The node that the read reaches: the first key after the root `world`. It is `undefined` when the read can reach\n * each node, for example the path `[\"world\"]`, or a step document right after the root.\n */\n readonly to: string | undefined;\n /** The keys after the node, up to the first step document: the field of the node that the read reaches (SCHED.GRAIN). */\n readonly field: readonly Key[];\n /** `true` when only a lazy part reaches the read. An evaluation can then give a value without it (FACTS.LAZY). */\n readonly lazy: boolean;\n /** The static read of `factsOf`, with its path, its place and its mark `exact`. */\n readonly read: StaticRead;\n}\n\n/** One node of a schedule, with what the static facts tell about it (SCHED.GRAPH). */\nexport interface NodeInfo {\n /** The name of the node: its key under the root `world`. */\n readonly id: string;\n /** The document of the node. */\n readonly doc: unknown;\n /** The static facts of the document. */\n readonly facts: DocFacts;\n /** The side of the node, from the facts. A node on the run side is a sink: no node reads it (SCHED.SIDE). */\n readonly side: Side;\n /** The edges to the nodes that the document can read, in the order of its reads. */\n readonly edges: readonly NodeEdge[];\n}\n\n/** The options of `schedule`: the options of `durable`, and the context of the host. */\nexport interface ScheduleOptions extends DurableOptions {\n /** The context of the host: the names, `self`, `event` and the capabilities. The schedule sets the root `world` to the nodes. */\n readonly context?: Context;\n}\n\n/** The work of a schedule since its start: the work of its `durable` cache, and the demands ahead of a node. */\nexport interface ScheduleCounts extends DurableCounts {\n /**\n * The demands that a demand of the host made before its own node (SCHED.LONG-CHAIN). Each node that the eager edges\n * reach, and that has no value in the data epoch, adds one.\n */\n readonly ahead: number;\n}\n\n/** The options of a run of a node. */\nexport interface NodeRunOptions {\n /** The event that starts the run, at the root `event`. The default is the event of the context of the host. */\n readonly event?: Thing;\n /** The host code that does each effect, as in `run`. */\n readonly perform?: Perform;\n /** A signal that stops the run. */\n readonly signal?: StopSignal;\n}\n\n/**\n * The demand schedule of a graph of named nodes (D31). The host tells it each change of a node, of the machine and of\n * its data. The schedule evaluates a node only when a host or another node reads it.\n */\nexport interface Schedule {\n /** The epochs of the schedule (DURABLE.EPOCHS). A schedule builds again what depends on the structure when `structure` changes. */\n readonly epochs: Epochs;\n /** The work of the schedule since its start: the compilations, the evaluations, the verifications, the reuses and the demands ahead. */\n readonly counts: ScheduleCounts;\n /** The context of each node in the current data epoch: the context of the host, with the nodes at the root `world`. */\n readonly context: Context;\n /**\n * This function gives each node with its facts, its side and its edges (SCHED.GRAPH). The map stays the same object\n * in one structure epoch, thus a schedule can keep what it computes from it, for example an order.\n *\n * @returns The nodes, by name.\n */\n graph(): ReadonlyMap<string, NodeInfo>;\n /**\n * This function gives the value of a node on demand (SCHED.DEMAND). A read of `world` in the document demands that\n * node first. Each node evaluates at most one time in a data epoch.\n *\n * - First, the schedule demands each node that the eager edges reach, deepest first (SCHED.LONG-CHAIN).\n * - After a change, a pure node verifies its reads, and it keeps its result when each read is the same (SCHED.STALE).\n * - Each node of a cycle gives `#CYCLE!`, in each order of demands (SCHED.CYCLE).\n * - A node on the run side gives `#REF!`, because the schedule does not evaluate it (SCHED.SIDE).\n *\n * @param id - The name of the node.\n * @returns The result, or `#N/A` for a node that the schedule does not have.\n */\n read(id: string): Result;\n /**\n * This function adds a node, or gives a node a new document. It is a change of the structure. Only a new document\n * object compiles (DURABLE.STRUCTURE).\n *\n * @param id - The name of the node.\n * @param doc - The document of the node. It must not change in place after this call.\n */\n set(id: string, doc: unknown): void;\n /**\n * This function removes a node. It is a change of the structure, and a read of the node then gives `#N/A`.\n *\n * @param id - The name of the node.\n * @returns `true` when the schedule had the node.\n */\n remove(id: string): boolean;\n /**\n * This function tells the schedule that the data of the host changed (DURABLE.EPOCHS). The values of a context do\n * not change in place, thus new data comes in a new context, or through a host thing.\n *\n * @param context - The new context of the host, or `undefined` to keep the context.\n */\n changeData(context?: Context): void;\n /**\n * This function gives the schedule a new machine. It drops each plan, each fact and each result.\n *\n * @param machine - The new machine.\n */\n changeMachine(machine: Machine): void;\n /**\n * This function starts a run of the document of a node, and the host does each effect (SCHED.RUN). Only the host\n * starts a run, for example at an event. A change of data does not start or repeat a run (L3).\n *\n * @param id - The name of the node.\n * @param options - The event, 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(id: string, options?: NodeRunOptions): Promise<Result>;\n}\n\n/**\n * This function gives the edges of a node from the static facts of its document (SCHED.EDGES). Each read of the root\n * `world` is an edge to the node of its first key. The keys after that key are the field of the edge (SCHED.GRAIN).\n * A read of another root reads the data of the host, thus it is not an edge.\n *\n * A reference in the value of a node can lead a read to a third node (DEREF.COLLAPSE). The edges do not show such a\n * read, but the reads of an evaluation do (S1d).\n *\n * @param facts - The static facts of the document of the node.\n * @returns The edges, in the order of the reads.\n */\nexport function edgesOf(facts: DocFacts): readonly NodeEdge[] {\n const edges: NodeEdge[] = [];\n for (const read of facts.reads) {\n if (read.root !== \"world\") continue;\n const first = read.keys[0];\n edges.push({ to: first === undefined ? undefined : String(first), field: read.keys.length > 1 ? read.keys.slice(1) : NO_KEYS, lazy: read.lazy, read });\n }\n // A list that grows by push keeps room for more edges. A copy of a short list is smaller (PLAN.LEAN).\n return edges.length === 0 ? NO_EDGES : edges.slice();\n}\n\n/** No keys, and no edges. One frozen list of each serves each node, thus a schedule of many nodes keeps less. */\nconst NO_KEYS: readonly Key[] = /* @__PURE__ */ Object.freeze([]);\nconst NO_EDGES: readonly NodeEdge[] = /* @__PURE__ */ Object.freeze([]);\n\n/** This function gives the error of a node on a cycle. It names only the node, thus each order of demands gives the same error. */\nfunction cycleOf(id: string): Failed {\n return fail(\"#CYCLE!\", `The node ${id} is on a cycle of reads.`);\n}\n\n/** This function gives the error of a read of a node on the run side. */\nfunction runSide(id: string): Failed {\n return fail(\"#REF!\", `The node ${id} is on the run side, thus it has no value for a reader.`);\n}\n\n/** This function gives the error of a node that the schedule does not have. */\nfunction missing(id: string): Failed {\n return fail(\"#N/A\", `The schedule has no node ${id}.`);\n}\n\n/** The state of one data epoch: the context of the nodes, and the value of each node that a demand reached. */\ninterface Epoch {\n readonly context: Context;\n readonly values: Map<string, Result>;\n}\n\n/**\n * This function makes the demand schedule of a graph of named nodes (S1, R4, D31). A host gives each node a name and\n * a document. The root `world` of each node reaches the other nodes by name. The context of the host gives the other\n * roots.\n *\n * - `graph()` gives the facts, the side and the edges of each node, from `factsOf` and `edgesOf`.\n * - `read(id)` evaluates a node on demand, through `durable`. A pure node verifies its reads after a change, and a\n * read of a node demands that node again. Thus only a node with a changed read evaluates again: the red-green\n * algorithm of rustc.\n * - A node is on a cycle when its demand reaches itself through the reads of the evaluations. Each node of such a\n * strongly connected component gives `#CYCLE!`, whatever its document does with the error. The schedule finds the\n * components with the algorithm of Tarjan over the demands. Thus each order of demands gives the same values.\n * - A demand of the host, or of a run, first demands each node that the eager edges reach, deepest first. Thus each\n * read of such a node finds a value, and a chain of 100000 nodes does not overflow the stack (SCHED.LONG-CHAIN).\n * Each such demand starts with no node in evaluation, thus the order of demands keeps the values of D31.\n * - A node on the run side is a sink. Only `run` evaluates it, and only the host uses `run`.\n *\n * The host keeps the promises of `durable`. The documents and the values of a context do not change in place.\n *\n * @param machine - The machine of the first structure epoch.\n * @param options - The options of `durable`, and the context of the host.\n * @returns The schedule.\n */\nexport function schedule(machine: Machine, options: ScheduleOptions = {}): Schedule {\n const { context: given, ...cacheOptions } = options;\n const cache = durable(machine, cacheOptions);\n const docs = new Map<string, unknown>();\n const edges = new WeakMap<DocFacts, readonly NodeEdge[]>();\n let base: Context = given ?? contextOf();\n let now: Epoch | undefined;\n let nodes: { readonly structure: number; readonly map: ReadonlyMap<string, NodeInfo> } | undefined;\n\n // The nodes in evaluation, in the order of their demands. The top of the stack is the node whose read demands.\n const stack: string[] = [];\n const busy = new Set<string>();\n // The algorithm of Tarjan over the demands: the order of each demand, the lowest order that the node reaches, and\n // the nodes of the components that are still open.\n const order = new Map<string, number>();\n const low = new Map<string, number>();\n const open: string[] = [];\n const onOpen = new Set<string>();\n // The nodes in evaluation that read themselves.\n const looped = new Set<string>();\n let count = 0;\n let ahead = 0;\n\n const lower = (id: string, to: number): void => {\n if (to < (low.get(id) as number)) low.set(id, to);\n };\n\n /** This function closes the open components down to an index of the list `open`. */\n const close = (from: number): number => {\n let size = 0;\n while (open.length > from) {\n const id = open.pop() as string;\n onOpen.delete(id);\n order.delete(id);\n low.delete(id);\n size += 1;\n }\n return size;\n };\n\n /** This function gives the edges of the facts of a document. They stay for each facts object, as the facts stay for each document. */\n const edgesFrom = (facts: DocFacts): readonly NodeEdge[] => {\n let found = edges.get(facts);\n if (found === undefined) {\n found = edgesOf(facts);\n edges.set(facts, found);\n }\n return found;\n };\n\n /** This function gives the edges of a node, for the walk of a demand. A known node, a missing node and a node on the run side need no walk. */\n const edgesFor = (id: string): readonly NodeEdge[] | undefined => {\n if (current().values.has(id) || !docs.has(id)) return undefined;\n const facts = cache.facts(docs.get(id));\n return facts.side === \"run\" ? undefined : edgesFrom(facts);\n };\n\n /**\n * This function gives the value of a node. A demand of the host or of a run has no node in evaluation. It first\n * demands each node that the eager edges reach, deepest first. Each of these demands also starts with no node in\n * evaluation, thus it is a demand of the host too. D31 gives each order of such demands the same values.\n */\n const demand = (id: string): Result => {\n if (stack.length === 0) {\n for (const first of deepestFirst(id, edgesFor)) {\n ahead += 1;\n visit(first);\n }\n }\n return visit(id);\n };\n\n /** This function demands one node, with the algorithm of Tarjan over the demands for the cycles of D31. */\n const visit = (id: string): Result => {\n const epoch = current();\n const reader = stack[stack.length - 1];\n const known = epoch.values.get(id);\n if (known !== undefined) {\n // A finished node of an open component is on a cycle with its reader too.\n if (reader !== undefined && onOpen.has(id)) lower(reader, order.get(id) as number);\n return known;\n }\n if (busy.has(id)) {\n // A read of a node in evaluation closes a cycle. It gives the same error as the final result of that node.\n if (reader !== undefined) lower(reader, order.get(id) as number);\n if (reader === id) looped.add(id);\n return cycleOf(id);\n }\n const doc = docs.get(id);\n if (cache.facts(doc).side === \"run\") {\n const refused = runSide(id);\n epoch.values.set(id, refused);\n return refused;\n }\n const mine = count++;\n order.set(id, mine);\n low.set(id, mine);\n const from = open.length;\n open.push(id);\n onOpen.add(id);\n busy.add(id);\n stack.push(id);\n let result: Result | undefined;\n try {\n result = cache.evaluate(id, doc, epoch.context);\n } finally {\n stack.pop();\n busy.delete(id);\n // An exception of the host leaves the node without a result. A later demand evaluates it again.\n if (result === undefined) {\n looped.delete(id);\n close(from);\n }\n }\n const reached = low.get(id) as number;\n const self = looped.delete(id);\n let value = result;\n if (reached < mine) {\n // The node reaches an earlier node that is still open, thus it is in that component.\n value = cycleOf(id);\n } else if (close(from) > 1 || self) {\n value = cycleOf(id);\n } else if (!result.ok && result.error.code === \"#DEPTH!\") {\n // An overflow of the stack depends on the depth of the demand, not on the node (D15).\n cache.forget(id);\n }\n epoch.values.set(id, value);\n if (reader !== undefined) lower(reader, reached);\n return value;\n };\n\n /** This function gives the record of the derive nodes, for a path that ends at the root `world`. */\n const record = (): unknown => {\n const out: Record<string, unknown> = {};\n for (const id of [...docs.keys()].sort()) {\n if (cache.facts(docs.get(id)).side === \"run\") continue;\n const result = demand(id);\n if (!result.ok) throw new Failure(result.error);\n Object.defineProperty(out, id, { value: result.value, enumerable: true, writable: true, configurable: true });\n }\n return out;\n };\n\n /**\n * This function gives the state of the current data epoch. Each data epoch has a new host thing at the root\n * `world`. Thus a read that reaches the whole root changes at each change of data (READS.KEPT).\n */\n const current = (): Epoch => {\n if (now !== undefined) return now;\n const nodesThing: HostThing = {\n [THING]: true,\n label: \"nodes\",\n deref(key) {\n const id = String(key);\n if (!docs.has(id)) return undefined;\n const result = demand(id);\n // A failed node gives its own error to each reader, as a failed attribute of a tree does (D16).\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n has: (key) => docs.has(String(key)),\n toJson: record,\n };\n // The context has a world, thus `rootContext` only gives it its grant (CAP.NARROW-CODE). Each evaluation of the\n // epoch then uses this object with no copy.\n now = { context: rootContext(machine, { ...base, world: nodesThing }), values: new Map() };\n return now;\n };\n\n const changed = (structure: boolean): void => {\n if (structure) cache.changeStructure();\n else cache.changeData();\n now = undefined;\n };\n\n return {\n get epochs() {\n return cache.epochs;\n },\n get counts() {\n return { ...cache.counts, ahead };\n },\n get context() {\n return current().context;\n },\n graph() {\n const structure = cache.epochs.structure;\n if (nodes?.structure === structure) return nodes.map;\n const map = new Map<string, NodeInfo>();\n for (const [id, doc] of docs) {\n const facts = cache.facts(doc);\n map.set(id, { id, doc, facts, side: facts.side, edges: edgesFrom(facts) });\n }\n nodes = { structure, map };\n return map;\n },\n read: (id) => (docs.has(id) ? demand(id) : missing(id)),\n set(id, doc) {\n docs.set(id, doc);\n changed(true);\n },\n remove(id) {\n if (!docs.delete(id)) return false;\n cache.forget(id);\n changed(true);\n return true;\n },\n changeData(next) {\n if (next !== undefined) base = next;\n changed(false);\n },\n changeMachine(next) {\n cache.changeStructure(next);\n now = undefined;\n },\n run(id, runOptions = {}) {\n if (!docs.has(id)) return Promise.resolve(missing(id));\n const ctx = current().context;\n return cache.plan(docs.get(id)).run(runOptions.event === undefined ? ctx : { ...ctx, event: runOptions.event }, {\n ...(runOptions.perform === undefined ? {} : { perform: runOptions.perform }),\n ...(runOptions.signal === undefined ? {} : { signal: runOptions.signal }),\n });\n },\n };\n}\n","import { docEquals } from \"./doc.ts\";\nimport { type Result, Failure, fail } from \"./errors.ts\";\nimport { type Effect, type Journal, type Perform, JOURNAL } from \"./evaluate.ts\";\n\n/*\n * Record and replay (R2 P2, D19). A recorder wraps the function `perform` of a host and keeps a log. The log has each\n * effect with its address, its request and its outcome, and the order in which the waits of each `all` settled. A\n * replayer answers each effect from the log by its address, thus a replay does no host effect. The kernel gives the\n * address and the outcome of each effect. The journal on the function `perform` carries the order of the waits.\n */\n\n/** One effect of a log: its address, its request and its outcome. */\nexport interface ReplayEntry {\n /** The address of the effect (RUN.ADDRESS), for example `1#0` or `all0.1/1#0`. */\n readonly address: string;\n /** The kind of the effect, as a text with dots. */\n readonly kind: string;\n readonly payload: unknown;\n /** The outcome of the effect (RUN.OUTCOME). It is absent when the recorded run stopped before the answer came. */\n readonly outcome?: Result;\n /** `true` when the host made the run wait for the outcome. */\n readonly waited: boolean;\n}\n\n/** An item of an `all` whose wait settled in the recorded run. */\nexport interface ReplaySettle {\n /** The address of the `all`, for example `all0` or `all0.1/all0`. */\n readonly all: string;\n /** The index of the item. */\n readonly item: number;\n}\n\n/** The log of a run: each effect in the order of the requests, and the order in which the waits of each `all` settled. */\nexport interface ReplayLog {\n readonly effects: readonly ReplayEntry[];\n readonly settles: readonly ReplaySettle[];\n}\n\n/** A recorder: the function `perform` for a run, and the log of that run (RUN.RECORD). */\nexport interface Recorder {\n /** The function to give the run. It gives each effect to the function `perform` of the host, and it records the effect. */\n readonly perform: Perform;\n /**\n * This function gives the log of the run until this time. An effect gets its outcome when the answer comes.\n *\n * @returns The log.\n */\n log(): ReplayLog;\n}\n\n/** The options of a replayer. */\nexport interface ReplayOptions {\n /**\n * `false`: each answer comes at once, also for an effect that waited in the recorded run. An evaluation needs this\n * value, because it does not wait. The default is `true`: an effect waits when it waited in the recorded run.\n */\n readonly wait?: boolean;\n}\n\n/**\n * This function makes a recorder (RUN.RECORD). The recorder gives each effect to the function `perform` of the host.\n * Its log keeps each effect with its address, its kind, its payload and the outcome that the kernel gives it. The log\n * also keeps the order in which the waits of each `all` settle.\n *\n * @param perform - The function of the host. Without it, each effect gives its payload, as in a run without a host.\n * @returns The function `perform` for the run, and the log.\n */\nexport function recorder(perform?: Perform): Recorder {\n const seen: { readonly effect: Effect; waited: boolean }[] = [];\n const settles: ReplaySettle[] = [];\n const journal: Journal = {\n settled: (all, item) => {\n settles.push({ all, item });\n },\n };\n const host = (effect: Effect): unknown => {\n const entry = { effect, waited: false };\n seen.push(entry);\n const answer = perform === undefined ? effect.payload : perform(effect);\n if (answer instanceof Promise) entry.waited = true;\n return answer;\n };\n return {\n perform: Object.assign(host, { [JOURNAL]: journal }),\n log: () => ({\n effects: seen.map(({ effect, waited }) => ({\n address: effect.address ?? \"\",\n kind: effect.kind,\n payload: effect.payload,\n waited,\n ...(effect.outcome === undefined ? {} : { outcome: effect.outcome }),\n })),\n settles: [...settles],\n }),\n };\n}\n\n/**\n * This function makes a replayer: a function `perform` that answers each effect from a log, by its address (RUN.REPLAY). A\n * recorded error comes again with its code, its reason, its place and its cause. The waits of each `all` settle in the\n * recorded order. An effect that the log does not have at its address gives `#REPLAY!` (RUN.REPLAY-MISMATCH).\n *\n * A replayer keeps its place in the order of the waits, thus each run needs a new replayer.\n *\n * @param log - The log of a recorder.\n * @param options - `wait: false` for an evaluation.\n * @returns The function `perform` for the replay.\n */\nexport function replayer(log: ReplayLog, options: ReplayOptions = {}): Perform {\n const wait = options.wait !== false;\n const entries = new Map<string, ReplayEntry>();\n for (const entry of log.effects) entries.set(entry.address, entry);\n const order = new Map<string, number[]>();\n for (const settle of log.settles) {\n const items = order.get(settle.all);\n if (items === undefined) order.set(settle.all, [settle.item]);\n else items.push(settle.item);\n }\n const journal: Journal = {\n next: (all, waiting) => {\n const items = order.get(all);\n const item = items?.[0];\n if (items === undefined || item === undefined || !waiting.includes(item)) return undefined;\n items.shift();\n return item;\n },\n };\n const perform = (effect: Effect): unknown => {\n const entry = effect.address === undefined ? undefined : entries.get(effect.address);\n const wrong = mismatch(effect, entry);\n if (wrong !== undefined || entry === undefined) throw wrong;\n const outcome = entry.outcome;\n const failure =\n outcome === undefined\n ? replayError(effect, `The log has no outcome for the effect ${effect.kind} at ${effect.address ?? \"\"}: the recorded run stopped before the answer.`)\n : outcome.ok\n ? undefined\n : new Failure(outcome.error);\n const value = outcome?.ok === true ? outcome.value : undefined;\n if (wait && entry.waited) return failure === undefined ? Promise.resolve(value) : Promise.reject(failure);\n if (failure !== undefined) throw failure;\n return value;\n };\n return Object.assign(perform, { [JOURNAL]: journal });\n}\n\n/** This function gives the error of an effect that the log does not have at its address, or `undefined`. */\nfunction mismatch(effect: Effect, entry: ReplayEntry | undefined): Failure | undefined {\n const at = effect.address ?? \"\";\n if (entry === undefined) return replayError(effect, `The log has no effect at the address ${at}, and the run asks for the effect ${effect.kind}.`);\n if (entry.kind !== effect.kind) return replayError(effect, `The log has the effect ${entry.kind} at the address ${at}, and the run asks for the effect ${effect.kind}.`);\n if (!docEquals(entry.payload, effect.payload)) return replayError(effect, `The effect ${effect.kind} at the address ${at} has another payload than the log.`);\n return undefined;\n}\n\n/** This function gives the exception that carries `#REPLAY!` to the kernel, with the place of the effect. */\nfunction replayError(effect: Effect, reason: string): Failure {\n return new Failure(fail(\"#REPLAY!\", reason, { place: effect.place }).error);\n}\n","import { type Json, type Key, docEquals, isRecord } from \"./doc.ts\";\nimport { type TypeIssue, type ValueType, isUnknown, join, member } from \"./types.ts\";\n\n/*\n * Type providers (R5 P4, D28). A provider makes a value type from data that a host already has: a JSON Schema or\n * sample values. A host gives such a type to a root of a check, for example the schema of a store for `world`.\n */\n\n/** The type that a provider reads, and the problems of the reading. Each problem tells what the type does not test. */\nexport interface TypeReading {\n readonly type: ValueType;\n readonly issues: readonly TypeIssue[];\n}\n\n/** The deepest schema that `typeFromSchema` reads. A deeper schema reads as `unknown`. */\nconst MAX_SCHEMA_DEPTH = 256;\n\n/** The keywords that describe a schema and do not test a value. The reading ignores them without an issue. */\nconst NOTES: ReadonlySet<string> = /* @__PURE__ */ new Set([\n \"$schema\",\n \"$id\",\n \"$anchor\",\n \"$comment\",\n \"$defs\",\n \"definitions\",\n \"title\",\n \"description\",\n \"default\",\n \"examples\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n]);\n\n/** The keywords that the reading reads. Each other keyword gives an issue and tests nothing. */\nconst READ: ReadonlySet<string> = /* @__PURE__ */ new Set([\"type\", \"properties\", \"required\", \"additionalProperties\", \"items\", \"enum\", \"const\", \"anyOf\", \"oneOf\"]);\n\n/**\n * The keywords that can permit more values than the other keywords permit. Older drafts ignore each keyword beside\n * `$ref`, and `nullable` of OpenAPI 3.0 permits `null`. Thus a schema with one of them reads as `unknown`.\n */\nconst WIDENING: ReadonlySet<string> = /* @__PURE__ */ new Set([\"$ref\", \"$dynamicRef\", \"$recursiveRef\", \"nullable\"]);\n\n/** The base type of each name of the keyword `type`. */\nconst BASES: Readonly<Record<string, ValueType>> = { null: \"null\", boolean: \"bool\", number: \"number\", integer: \"number\", string: \"text\" };\n\n/** This function sets an own field of a new record. 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\n/** The union of types: the join of each type, or `never` for no type. */\nfunction unionOf(types: readonly ValueType[]): ValueType {\n return types.reduce<ValueType>((all, type) => join(all, type), \"never\");\n}\n\n/** The state of one reading of a schema: the issues that it found. */\nclass SchemaReader {\n readonly issues: TypeIssue[] = [];\n\n issue(at: readonly Key[], reason: string): void {\n this.issues.push({ at, reason });\n }\n\n /** This method reads one schema. */\n read(schema: unknown, at: readonly Key[], depth: number): ValueType {\n if (depth > MAX_SCHEMA_DEPTH) {\n this.issue(at, `The schema is deeper than ${MAX_SCHEMA_DEPTH} levels. The type reads it as unknown.`);\n return \"unknown\";\n }\n if (schema === true) return \"unknown\";\n if (schema === false) return \"never\";\n if (!isRecord(schema)) {\n this.issue(at, \"A schema is a record or a truth value. The type reads this value as unknown.\");\n return \"unknown\";\n }\n let widens = false;\n for (const key of Object.keys(schema)) {\n if (READ.has(key) || NOTES.has(key)) continue;\n if (WIDENING.has(key)) {\n this.issue([...at, key], `The type does not read the keyword ${key}. Thus it reads the schema as unknown.`);\n widens = true;\n } else {\n this.issue([...at, key], `The type does not read the keyword ${key}. It does not test what the keyword tests.`);\n }\n }\n if (widens) return \"unknown\";\n // A schema is the conjunction of its keywords. The reading keeps one of them, and each one alone holds each value.\n const sides: { readonly key: string; readonly type: ValueType }[] = [];\n if (Object.hasOwn(schema, \"type\")) sides.push({ key: \"type\", type: this.byType(schema, at, depth) });\n else if ([\"properties\", \"required\", \"additionalProperties\", \"items\"].some((key) => Object.hasOwn(schema, key)) && ![\"enum\", \"const\", \"anyOf\", \"oneOf\"].some((key) => Object.hasOwn(schema, key))) {\n this.issue(at, \"The schema has no keyword type. Thus a value of each JSON type fits it, and the type reads it as unknown.\");\n }\n for (const key of [\"anyOf\", \"oneOf\"]) {\n if (!Object.hasOwn(schema, key)) continue;\n const items = schema[key];\n if (!Array.isArray(items)) {\n this.issue([...at, key], `The value of ${key} is a list of schemas.`);\n continue;\n }\n // A union holds each value of oneOf too. It does not test that only one schema fits.\n sides.push({ key, type: unionOf(items.map((item, index) => this.read(item, [...at, key, index], depth + 1))) });\n }\n // A finite set of values meets each other keyword exactly: the type keeps each value that each side holds.\n const values = this.values(schema, at);\n if (values !== undefined) return { one: values.filter((value) => sides.every((side) => member(value, side.type))) };\n const known = sides.filter((side) => !isUnknown(side.type, undefined));\n const kept = known[0];\n if (kept === undefined) return \"unknown\";\n for (const side of known.slice(1)) this.issue([...at, side.key], `The type reads the keyword ${kept.key}, and not the keyword ${side.key}.`);\n return kept.type;\n }\n\n /** This method reads `enum` and `const`: the values that the schema permits, or `undefined` without them. */\n values(schema: Readonly<Record<string, unknown>>, at: readonly Key[]): Json[] | undefined {\n let values: Json[] | undefined;\n if (Object.hasOwn(schema, \"enum\")) {\n if (Array.isArray(schema[\"enum\"])) values = [...(schema[\"enum\"] as Json[])];\n else this.issue([...at, \"enum\"], \"The value of enum is a list of JSON values.\");\n }\n if (Object.hasOwn(schema, \"const\")) {\n const one = schema[\"const\"] as Json;\n values = values === undefined ? [one] : values.filter((value) => docEquals(value, one));\n }\n return values;\n }\n\n /** This method reads the keyword `type` with the keywords of an object and of an array. */\n byType(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const raw = schema[\"type\"];\n const names = typeof raw === \"string\" ? [raw] : Array.isArray(raw) ? raw : undefined;\n if (names === undefined) {\n this.issue([...at, \"type\"], \"The value of type is a text or a list of texts.\");\n return \"unknown\";\n }\n const types: ValueType[] = [];\n for (const [index, name] of names.entries()) {\n const where = typeof raw === \"string\" ? [...at, \"type\"] : [...at, \"type\", index];\n if (name === \"object\") types.push(this.object(schema, at, depth));\n else if (name === \"array\") types.push(this.array(schema, at, depth));\n else if (typeof name === \"string\" && Object.hasOwn(BASES, name)) {\n if (name === \"integer\") this.issue(where, \"The type reads integer as number. It does not test that the number is whole.\");\n types.push(BASES[name] as ValueType);\n } else {\n this.issue(where, `The type ${String(name)} is not a type of JSON Schema. The type reads it as unknown.`);\n return \"unknown\";\n }\n }\n return unionOf(types);\n }\n\n /** This method reads an object: its properties, the properties that it needs and the other properties. */\n object(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const fields: Record<string, ValueType> = {};\n const properties = schema[\"properties\"] ?? {};\n if (isRecord(properties)) {\n for (const key of Object.keys(properties)) setOwn(fields, key, this.read(properties[key], [...at, \"properties\", key], depth + 1));\n } else {\n this.issue([...at, \"properties\"], \"The value of properties is a record of schemas.\");\n }\n const required = schema[\"required\"] ?? [];\n const needed = Array.isArray(required) ? required.filter((key): key is string => typeof key === \"string\") : [];\n if (!Array.isArray(required) || needed.length !== required.length) this.issue([...at, \"required\"], \"The value of required is a list of texts.\");\n // A property that `required` names without a schema can hold each value.\n for (const key of needed) if (!Object.hasOwn(fields, key)) setOwn(fields, key, \"unknown\");\n const optional = Object.keys(fields).filter((key) => !needed.includes(key));\n const other = schema[\"additionalProperties\"];\n // Each property that a pattern names is permitted too, thus the record is closed only without patterns.\n let closed = other === false && !Object.hasOwn(schema, \"patternProperties\");\n if (other !== undefined && other !== true && other !== false) {\n this.issue([...at, \"additionalProperties\"], \"The type reads additionalProperties with a schema as an open record. The other fields can hold each value.\");\n closed = false;\n }\n return { record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) };\n }\n\n /** This method reads an array: the schema of its items. */\n array(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const items = schema[\"items\"];\n if (items === undefined) return { list: \"unknown\" };\n // With prefixItems, the keyword items covers only the items after the prefix.\n if (Object.hasOwn(schema, \"prefixItems\") || Array.isArray(items)) {\n this.issue([...at, \"items\"], \"The type does not read the items of a tuple. It reads a list of unknown items.\");\n return { list: \"unknown\" };\n }\n return { list: this.read(items, [...at, \"items\"], depth + 1) };\n }\n}\n\n/**\n * This function makes a value type from a JSON Schema (TYPE.SCHEMA). A host uses it for the type of a root, for\n * example the schema of a store for `world`. It reads this subset:\n *\n * - `type`: `null`, `boolean`, `number`, `integer` (as `number`), `string`, `object` and `array`, or a list of them.\n * - `properties`, `required` and `additionalProperties` give a record. `false` closes it, and a property that is not\n * in `required` is optional.\n * - `items` gives a list. `enum` and `const` give `one`. `anyOf` and `oneOf` give a union.\n *\n * The type holds each value that the schema accepts. Each keyword that the function does not read tests nothing, as\n * `unknown`, and the issues name it. Examples are `minimum`, `pattern` and `allOf`. A schema with `$ref` or `nullable`\n * reads as `unknown`, because these keywords can permit more values. A schema with more than one of `type`, `anyOf`\n * and `oneOf` gives the type of the first, and an issue for each other. The function does not throw.\n *\n * @param schema - The schema, as JSON.\n * @returns The type, and the problems of the reading with their keys in the schema.\n */\nexport function typeFromSchema(schema: unknown): TypeReading {\n const reader = new SchemaReader();\n try {\n return { type: reader.read(schema, [], 0), issues: reader.issues };\n } catch (error) {\n // A getter of a host value can throw. The reading then gives the top.\n reader.issue([], `The schema cannot be read: ${error instanceof Error ? error.message : String(error)}`);\n return { type: \"unknown\", issues: reader.issues };\n }\n}\n\n/** The options of `typeFromSamples`. */\nexport interface SampleOptions {\n /** `true`: the samples show each field, thus each record type is closed. The default is `false`. */\n readonly closed?: boolean;\n}\n\n/** The deepest sample that `typeFromSamples` reads. A deeper value gives `unknown`. */\nconst MAX_SAMPLE_DEPTH = 256;\n\n/** This function gives the type of a group of sample values at one depth. */\nfunction samplesAt(values: readonly unknown[], closed: boolean, depth: number): ValueType {\n if (depth > MAX_SAMPLE_DEPTH) return values.length === 0 ? \"never\" : \"unknown\";\n const types: ValueType[] = [];\n const bases = new Set<string>();\n const items: unknown[] = [];\n const records: Readonly<Record<string, unknown>>[] = [];\n let lists = false;\n for (const value of values) {\n if (value === null) bases.add(\"null\");\n else if (value === undefined) bases.add(\"undefined\");\n else if (typeof value === \"boolean\") bases.add(\"bool\");\n else if (typeof value === \"number\") bases.add(\"number\");\n else if (typeof value === \"string\") bases.add(\"text\");\n else if (Array.isArray(value)) {\n lists = true;\n // A hole of a list holds undefined, thus a loop by index reads it too.\n for (let index = 0; index < value.length; index += 1) items.push(value[index]);\n } else if (isRecord(value)) records.push(value);\n // A value without a type of the kernel, for example a function, has each type.\n else return \"unknown\";\n }\n for (const base of [\"null\", \"undefined\", \"bool\", \"number\", \"text\"]) if (bases.has(base)) types.push(base);\n if (lists) types.push({ list: samplesAt(items, closed, depth + 1) });\n if (records.length > 0) {\n // All records join into one record. A field that a record does not have is optional.\n const keys: string[] = [];\n for (const record of records) for (const key of Object.keys(record)) if (!keys.includes(key)) keys.push(key);\n const fields: Record<string, ValueType> = {};\n const optional: string[] = [];\n for (const key of keys) {\n const found = records.filter((record) => Object.hasOwn(record, key));\n if (found.length < records.length) optional.push(key);\n setOwn(fields, key, samplesAt(found.map((record) => record[key]), closed, depth + 1));\n }\n types.push({ record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) });\n }\n return types.length === 1 ? (types[0] as ValueType) : unionOf(types);\n}\n\n/**\n * This function infers a value type from sample values (TYPE.SAMPLES), as a type provider of F# does. A host uses it\n * for the type of a root, for example from some events.\n *\n * - `null`, `undefined`, a truth value, a number and a text give their base types, not their values.\n * - The items of each list join into one type of items.\n * - All records join into one record with each key of the samples. A key that a record does not have is optional.\n * - Values of different forms give a union, as `join` gives. No samples give `never`.\n * - A value without a type of the kernel, for example a function, gives `unknown`.\n *\n * Each sample is a member of the type. A record is open, because samples do not show that a field cannot exist. With\n * `closed: true`, each record is closed, and a reference to a field that no sample has gives `#TYPE!`.\n *\n * @param values - The sample values.\n * @param options - `closed: true` closes each record type.\n * @returns The type.\n */\nexport function typeFromSamples(values: readonly unknown[], options: SampleOptions = {}): ValueType {\n return samplesAt(values, options.closed === true, 0);\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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,WAAqB,CAAC;EAC5B,KAAK,MAAM,OAAO,MAAM;GACtB,MAAM,QAAQ,QAAQ,QAAQ,WAAW,OAAO,OAAO,QAAQ,GAAG,CAAC;GACnE,IAAI,MAAM,SAAS,QAAQ,QAAQ,SAAS,KAAK,GAAG;GACpD,OAAO,QAAQ,KAAK,UAAU,MAAM,KAAK,WAAW,OAAO,IAAI,GAAG,QAAQ,QAAQ,CAAC,CAAC;EACtF;EACA,MAAM,KAAK;GAAE,QAAQ;GAAQ,GAAI,SAAS,WAAW,IAAI,CAAC,IAAI,EAAE,SAAS;GAAI,GAAI,SAAS,EAAE,QAAQ,KAAK,IAAI,CAAC;EAAG,CAAC;CACpH;CACA,OAAO,MAAM,WAAW,IAAK,MAAM,KAAmB,QAAQ,KAAK;AACrE;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,QAA4B,UAAyB,CAAC,GAAc;CAClG,OAAO,UAAU,QAAQ,QAAQ,WAAW,MAAM,CAAC;AACrD"}
1
+ {"version":3,"file":"index.js","names":["termOf","setOwn","unionOf","valueText","NONE","setOwn","own","entryOf","nodeAt","NO_HOPS","resolveFully","setOwn","makeRootContext","NO_CAPS","drive","ABORTED","finish","NO_CAPS","NO_NAMES","contractOf","NONE","EACH","EACH","setOwn","CLOSURE","setOwn","partsOf","own","examine","drive","CLOSURE","setField","NAMES","contextOf"],"sources":["../src/doc.ts","../src/errors.ts","../src/world.ts","../src/types.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/typing.ts","../src/static.ts","../src/facts.ts","../src/effects.ts","../src/codec.ts","../src/formula.ts","../src/syntax.ts","../src/reference.ts","../src/agree.ts","../src/generate.ts","../src/conform.ts","../src/same.ts","../src/reads.ts","../src/durable.ts","../src/graph.ts","../src/schedule.ts","../src/replay.ts","../src/providers.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 envelope\n * does not change the value 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` and `sameResult` use the same walk, and each adds its rules\n * for other values (D20).\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 return equalWith(a, b, undefined);\n}\n\n/** A rule for two values that are not the same by `Object.is`: `true`, `false`, or `undefined` for the next rule. */\nexport type SameRule = (a: unknown, b: unknown) => boolean | undefined;\n\n/**\n * This function is the one walk of `docEquals`, `sameValue` and `sameResult` (D20). It compares two values by the\n * rules of `docEquals`. A rule of the caller answers first for each pair that is not the same by `Object.is`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param rule - The rule of the caller. Its `undefined` gives the rules of `docEquals`.\n * @returns `true` when the values are equal.\n */\nexport function equalWith(a: unknown, b: unknown, rule: SameRule | undefined): 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 told = rule?.(x, y);\n if (told !== undefined) {\n if (told) continue;\n return false;\n }\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 | \"#REPLAY!\"\n | \"#TYPE!\";\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, Root } from \"./deref.ts\";\nimport type { ValueType } from \"./types.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 *\n * `expect` is the value type that a part must have, as `of` is its type (TYPE.CHECK). A shape with parts gives it to\n * each part that `of` covers. Only a check of types reads it, and it describes the verb `eval`.\n */\nexport type Shape =\n | { readonly shape: \"none\" }\n | { readonly shape: \"term\"; readonly of?: string; readonly address?: boolean; readonly kinds?: readonly (readonly Key[])[]; readonly expect?: ValueType }\n | { readonly shape: \"list\"; readonly of?: string; readonly item?: Shape; readonly distinct?: boolean; readonly expect?: ValueType }\n | { readonly shape: \"map\"; readonly of?: string; readonly item?: Shape; readonly expect?: ValueType }\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 readonly expect?: ValueType;\n }\n | { readonly shape: \"deep\"; readonly of?: string; readonly expect?: ValueType }\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/**\n * A lazy rule of a kind names the parts that an evaluation can skip and still give a value. An example is the\n * branches of `if`. The static facts mark each read under such a part (D24).\n *\n * `in` names the parts, as patterns of their paths in the value. The key `\"*\"` matches each key. A rule without `in`\n * covers each part. With `after: n`, the rule covers only the parts after the first `n` parts that its patterns\n * match. Thus `{ after: 1 }` makes each part lazy except the first part, as in `and`.\n */\nexport interface LazyRule {\n readonly in?: readonly (readonly Key[])[];\n readonly after?: number;\n}\n\n/**\n * The static facts that a kind declares for its code (D24). The contract of a kind holds them, and the hook `facts`\n * of a machine can give them for a name under a fallback kind. The facts describe the code of `eval`, and of `step`\n * for a step document.\n *\n * - `pure`: `true` when the code of the kind causes no effect. Its result depends only on its data, the results\n * of its parts and what its paths reach. A kind that reads the context in another way does not declare it,\n * because the static facts do not see that read.\n * - `volatile`: `true` when its result can change while each read gives the same thing, for example a clock.\n * - `lazy`: the parts that an evaluation can skip and still give a value.\n * - `reads`: the roots that the code of the kind resolves as a whole, with the path of one root. The static facts\n * give a read of each root at each document of the kind (D44). The tree node reads `self` this way.\n */\nexport interface KindFacts {\n readonly pure?: boolean;\n readonly volatile?: boolean;\n readonly lazy?: readonly LazyRule[];\n readonly reads?: readonly Root[];\n}\n\n/**\n * The declaration of one attribute of the nodes of a kind (D42). The last two rungs of the ladder of an attribute\n * read it (TREE.LADDER). Each term is a document. A bare term gets the type `of` of the parts of the kind.\n *\n * - `copy`: `true` gives a node without an answer of the first three rungs the same attribute of its parent\n * (TREE.COPY).\n * - `fold`: the value of a node without an answer of the first four rungs. The fold starts with the term `unit`.\n * Then the term `combine` adds the attribute of each node in the list `children`, one at a time (TREE.FOLD).\n * `combine` sees the names `acc` and `item`.\n * - `default`: the term that gives the value when no rung before it answers and the declaration has no fold.\n */\nexport interface AttributeDeclaration {\n readonly copy?: boolean;\n readonly fold?: { readonly unit: Json; readonly combine: Json };\n readonly default?: Json;\n}\n\n/**\n * The tree contract of a kind (D42): the equations of the attributes of its nodes. Each equation is a document that\n * evaluates with the node as `self` and without capabilities. A bare equation gets the type `of` of the parts of the\n * kind.\n *\n * - `equations`: the attributes of the node itself. An equation sees no names.\n * - `down`: the attributes of each child of the node. `self` is this node. An equation sees the names `child`,\n * `index` and `prev` (TREE.DOWN).\n * - `attributes`: the declarations of the attributes of the node, for the rungs `copy` and `default`.\n */\nexport interface TreeContract {\n readonly equations?: Readonly<Record<string, Json>>;\n readonly down?: Readonly<Record<string, Json>>;\n readonly attributes?: Readonly<Record<string, AttributeDeclaration>>;\n}\n\n/**\n * This function gives the type of a bare equation of a kind (D42). It is the type `of` of the shape of its parts, or\n * else the type `of` of the shape `rest` of a record. The plan, the reference and `check` read it with this one function.\n *\n * @param kind - The kind.\n * @returns The type, or `undefined` when the shape declares none.\n */\nexport function equationType(kind: Kind): string | undefined {\n const parts = kind.parts as { readonly of?: string; readonly rest?: { readonly of?: string } } | undefined;\n return parts?.of ?? parts?.rest?.of;\n}\n\n/**\n * A kind gives the name of an evaluator for each verb, and the contract of its value. The contract serves each verb.\n * For each verb, the kernel splits the parts and narrows their capabilities by it, and `check` reads its scope rules.\n * `side` and `effects` tell what the verb `eval` does (VERB.CONTRACT). `verbEffects` tells the effects of the other\n * verbs (VERB.EFFECTS).\n */\nexport interface Kind extends KindFacts {\n /**\n * The evaluator names, by verb. `eval` evaluates a document, `deref` answers a step on it, and `step` names the\n * walker of a step document. A language adds its own verbs, for example `view` or `format`.\n */\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 verb `eval` of the kind. A kind of the run side causes effects. The default is `derive`. */\n readonly side?: Side;\n /**\n * The effects that the verb `eval` of a document of this kind can cause. It is a list of the kinds of the effects.\n * The text `\"type\"` means that the kind of the effect is the type of the document itself, as for a call. For a\n * procedure entry, the list holds the latent effects of the procedure, and `checkLatent` compares them with its body\n * (CAP.LATENT).\n */\n readonly effects?: \"type\" | readonly string[];\n /**\n * The effects that the other verbs of a document of this kind can cause, by verb, in the form of `effects`\n * (VERB.EFFECTS, D49). An entry `view: []` declares no effect for `view`. A verb without an entry has no\n * declaration, thus `check` does not test its effects. The field `effects` declares `eval`, thus this field has no\n * entry `eval`.\n */\n readonly verbEffects?: VerbEffects;\n /**\n * The value type of the result of the verb `eval`, when it is fixed (TYPE.SYNTH). A check of types gives it to each\n * document of the kind, in the place of the type that the rule of the evaluator synthesizes.\n */\n readonly result?: ValueType;\n /**\n * The equations and the declarations of the attributes of a node of the decorated tree (D42). Only the evaluator\n * `tree.node` reads them, and `check` checks each equation one time (TREE.LADDER).\n */\n readonly tree?: TreeContract;\n /** One sentence that tells what the kind is. */\n readonly summary?: string;\n}\n\n/**\n * The effects that a contract declares for the verbs other than `eval`, by verb (D49). Each entry has the form of the\n * field `effects` of a kind. The type has no entry `eval`, because the field `effects` declares `eval`.\n */\nexport type VerbEffects = Readonly<Record<string, \"type\" | readonly string[]>> & { readonly eval?: never };\n\n/**\n * This function gives the effects that the contract of a kind declares for a verb (VERB.EFFECTS, D49). For `eval`,\n * the field `effects` declares them, and a kind without the field declares no effect. For another verb, the entry of\n * `verbEffects` declares them. `check` and `conforms` read the declarations with this one function.\n *\n * @param kind - The kind.\n * @param verb - The verb.\n * @returns The declaration in the form of `effects`, or `undefined` when the contract does not declare the effects of\n * the verb.\n */\nexport function effectsOfVerb(kind: Kind, verb: string): \"type\" | readonly string[] | undefined {\n if (verb === \"eval\") return kind.effects ?? [];\n const table = kind.verbEffects as Readonly<Record<string, \"type\" | readonly string[]>> | undefined;\n return table !== undefined && Object.hasOwn(table, verb) ? table[verb] : undefined;\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 /**\n * The default evaluator of each verb: the last rung of the ladder (LADDER.DEFAULT). It serves each verb, also\n * `deref` and `step`. Without a default of `deref`, a step goes into the value of a document (VERB.LADDER).\n */\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 Json, type Key, docEquals, isEnvelope, isRecord } from \"./doc.ts\";\n\n/*\n * Value types and value domains (R5 P2, D22). A value type is a set of values that a result can have. It is a JSON\n * term that only a check reads. It is not a kind, and it does not go into an envelope (D2, D6). A text names a base\n * type. The set of base types is open: a language adds its own domains, each with a membership test.\n */\n\n/**\n * A value type: a set of values that a result can have, as a JSON term.\n *\n * - A text names a base type: `unknown`, `never`, a domain of the kernel (`null`, `undefined`, `bool`, `number`,\n * `text`), or a domain of a language.\n * - `list`: a list whose items have the type.\n * - `record`: a plain record with the named fields. `optional` names the fields that can be absent. A `closed`\n * record has no other fields. The other fields of an open record can hold each value.\n * - `fn`: a function with the types of its parameters, and the type of its result (`to`).\n * - `union`: a value of one of the types. An empty union holds no value.\n * - `one`: one of the JSON values of the list.\n *\n * A term that is not in this list reads as `unknown` (TYPE.UNKNOWN). Thus a later version can add a term.\n */\nexport type ValueType =\n | string\n | { readonly list: ValueType }\n | { readonly record: Readonly<Record<string, ValueType>>; readonly optional?: readonly string[]; readonly closed?: boolean }\n | { readonly fn: readonly ValueType[]; readonly to: ValueType }\n | { readonly union: readonly ValueType[] }\n | { readonly one: readonly Json[] };\n\n/**\n * A value domain: a base type of a language, with its membership test. A machine holds its domains by their names\n * (`Machine.domains`). A value is a member of a domain only when the test of the domain and the test of each parent\n * accept it (TYPE.MEMBER).\n *\n * A path does not follow a member of a domain as a reference (DEREF.COLLAPSE). Thus the test `is` must refuse each\n * reference document.\n */\nexport interface Domain {\n /**\n * This function tells if a value is a member of the domain. It must be pure. A test that throws gives `false`.\n *\n * @param value - The value.\n * @returns `true` for a member.\n */\n readonly is: (value: unknown) => boolean;\n /** The names of the parents: the base types that hold each member of the domain. A base type fits each parent. */\n readonly under?: readonly string[];\n /** One sentence that tells what the domain holds. */\n readonly summary?: string;\n /**\n * The value type of each step into a member, by its key, for example the field `x` of a point (TYPE.STEPS). The\n * check of a path reads the steps of the domain first, then the steps of each parent. The language keeps them true:\n * a step with the key into a member reaches a member of the type. A key without a type gives `unknown`.\n */\n readonly steps?: Readonly<Record<string, ValueType>>;\n /**\n * The codec of the members: it writes a member as JSON and reads it again (D40). A document holds a member as the\n * standard extension `ext.domain`. A domain without a codec has no such document.\n */\n readonly codec?: DomainCodec;\n}\n\n/**\n * The codec of a domain: it writes a member of the domain as JSON, and it reads the JSON again (D40). Both functions\n * must be pure. `decode(encode(v))` must equal `v` by `sameValue` (EXT.ROUNDTRIP). The codec must give one JSON\n * value for each member, thus the same value has the same document in each language (D12).\n */\nexport interface DomainCodec {\n /**\n * This function writes a member of the domain as JSON.\n *\n * @param value - A member of the domain.\n * @returns The JSON of the member.\n */\n readonly encode: (value: unknown) => Json;\n /**\n * This function reads the JSON of a member again. It throws for JSON that does not write a member.\n *\n * @param data - The JSON that `encode` gave.\n * @returns The member.\n */\n readonly decode: (data: Json) => unknown;\n}\n\n/** A problem of a value type: the keys from the root of the term to the problem, and the reason. */\nexport interface TypeIssue {\n readonly at: readonly Key[];\n readonly reason: string;\n}\n\n/**\n * The domains of the kernel. `unknown` and `never` are not domains: they are the top and the bottom of the types.\n * A machine that does not name one of these domains gets it from this table.\n */\nexport const STD_DOMAINS: Readonly<Record<string, Domain>> = {\n null: { is: (value) => value === null, summary: \"The value null.\" },\n // JSON has no undefined, thus a document holds it as ext.undefined (D48). The domain has no codec: the codec of values writes undefined first.\n undefined: { is: (value) => value === undefined, summary: \"The value undefined. A document holds it as the extension ext.undefined.\" },\n bool: { is: (value) => typeof value === \"boolean\", summary: \"A truth value: true or false.\" },\n number: { is: (value) => typeof value === \"number\", summary: \"A number of the host, also NaN, an infinity and -0.\" },\n text: { is: (value) => typeof value === \"string\", summary: \"A text.\" },\n};\n\n/** The deepest term that a value type can have. A deeper term reads as `unknown`, thus a check stays total. */\nconst MAX_TYPE_DEPTH = 256;\n\n/** The keys that each term permits beside its own key. */\nconst TERM_KEYS: Readonly<Record<string, readonly string[]>> = {\n list: [\"list\"],\n record: [\"record\", \"optional\", \"closed\"],\n fn: [\"fn\", \"to\"],\n union: [\"union\"],\n one: [\"one\"],\n};\n\nconst TERMS = /* @__PURE__ */ Object.keys(TERM_KEYS);\n\n/** The form of a value type that the rules read. `top` is `unknown`, and also each term that is not a value type. */\ntype Form =\n | { readonly t: \"top\" }\n | { readonly t: \"bottom\" }\n | { readonly t: \"base\"; readonly name: string }\n | { readonly t: \"list\"; readonly item: ValueType }\n | { readonly t: \"record\"; readonly fields: Readonly<Record<string, ValueType>>; readonly optional: ReadonlySet<string>; readonly closed: boolean }\n | { readonly t: \"fn\"; readonly params: readonly ValueType[]; readonly to: ValueType }\n | { readonly t: \"union\"; readonly members: readonly ValueType[] }\n | { readonly t: \"one\"; readonly values: readonly Json[] };\n\nconst TOP: Form = { t: \"top\" };\nconst BOTTOM: Form = { t: \"bottom\" };\n\n/** This function gives the domain of a base type: the domain of the machine, or else the domain of the kernel. */\nexport function domainOf(name: string, domains: Readonly<Record<string, Domain>> | undefined): Domain | undefined {\n // The top and the bottom are not domains. A table entry with their names has no effect.\n if (name === \"unknown\" || name === \"never\") return undefined;\n const found = domains !== undefined && Object.hasOwn(domains, name) ? domains[name] : Object.hasOwn(STD_DOMAINS, name) ? STD_DOMAINS[name] : undefined;\n // A domain can be an instance of a class, thus the test reads only its function `is`.\n return typeof found === \"object\" && found !== null && typeof found.is === \"function\" ? found : undefined;\n}\n\n/** This function gives the term key of a record, when the record has exactly one term key and no other key. */\nfunction termOf(term: Readonly<Record<string, unknown>>): string | undefined {\n const keys = Object.keys(term);\n const own = keys.filter((key) => TERMS.includes(key));\n if (own.length !== 1) return undefined;\n const allowed = TERM_KEYS[own[0] as string] as readonly string[];\n return keys.every((key) => allowed.includes(key)) ? own[0] : undefined;\n}\n\n/** This function reads one level of a value type. A part of a term reads only when a rule asks for it. */\nfunction formOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): Form {\n if (typeof type === \"string\") {\n if (type === \"unknown\") return TOP;\n if (type === \"never\") return BOTTOM;\n return domainOf(type, domains) === undefined ? TOP : { t: \"base\", name: type };\n }\n if (!isRecord(type)) return TOP;\n const term = termOf(type);\n if (term === \"list\") return { t: \"list\", item: type[\"list\"] as ValueType };\n if (term === \"fn\") {\n const params = type[\"fn\"];\n return Array.isArray(params) && Object.hasOwn(type, \"to\") ? { t: \"fn\", params: params as readonly ValueType[], to: type[\"to\"] as ValueType } : TOP;\n }\n if (term === \"union\") return Array.isArray(type[\"union\"]) ? { t: \"union\", members: type[\"union\"] as readonly ValueType[] } : TOP;\n if (term === \"one\") return Array.isArray(type[\"one\"]) ? { t: \"one\", values: type[\"one\"] as readonly Json[] } : TOP;\n if (term !== \"record\") return TOP;\n const fields = type[\"record\"];\n const optional = type[\"optional\"] ?? [];\n const closed = type[\"closed\"] ?? false;\n if (!isRecord(fields) || !Array.isArray(optional) || typeof closed !== \"boolean\") return TOP;\n const names = (optional as readonly unknown[]).filter((name): name is string => typeof name === \"string\" && Object.hasOwn(fields, name));\n return { t: \"record\", fields: fields as Readonly<Record<string, ValueType>>, optional: new Set(names), closed };\n}\n\n/** This function gives each base type that holds the members of a base type: the type itself and each parent, through each level. */\nfunction lineOf(name: string, domains: Readonly<Record<string, Domain>> | undefined): ReadonlySet<string> {\n const seen = new Set<string>([name]);\n const queue = [name];\n while (queue.length > 0) {\n const under = domainOf(queue.pop() as string, domains)?.under;\n if (!Array.isArray(under)) continue;\n for (const parent of under) {\n if (typeof parent !== \"string\" || seen.has(parent)) continue;\n seen.add(parent);\n queue.push(parent);\n }\n }\n return seen;\n}\n\n/** This function tells if a value is a member of a base type: each test of the type and of its parents accepts it. */\nfunction inDomain(value: unknown, name: string, domains: Readonly<Record<string, Domain>> | undefined): boolean {\n for (const each of lineOf(name, domains)) {\n if (each === \"never\") return false;\n const domain = domainOf(each, domains);\n if (domain === undefined) continue;\n try {\n if (domain.is(value) !== true) return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\n/** This function is the membership test at one depth of a type. Below the deepest term, each value is a member. */\nfunction memberAt(value: unknown, type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n const next = depth + 1;\n switch (form.t) {\n case \"top\":\n return true;\n case \"bottom\":\n return false;\n case \"base\":\n return inDomain(value, form.name, domains);\n case \"list\": {\n if (!Array.isArray(value)) return false;\n // A hole of a list holds undefined, thus a loop by index tests it too.\n for (let index = 0; index < value.length; index += 1) if (!memberAt(value[index], form.item, domains, next)) return false;\n return true;\n }\n case \"record\": {\n if (!isRecord(value)) return false;\n for (const key of Object.keys(form.fields)) {\n if (Object.hasOwn(value, key)) {\n if (!memberAt(value[key], form.fields[key], domains, next)) return false;\n } else if (!form.optional.has(key)) {\n return false;\n }\n }\n return !form.closed || Object.keys(value).every((key) => Object.hasOwn(form.fields, key));\n }\n case \"fn\":\n return typeof value === \"function\";\n case \"union\":\n return form.members.some((item) => memberAt(value, item, domains, next));\n case \"one\":\n return form.values.some((item) => docEquals(item, value));\n }\n}\n\n/**\n * This function tells if a value is a member of a value type (TYPE.MEMBER). It is the membership test that a cast\n * at run time uses.\n *\n * - Each value is a member of `unknown`, and no value is a member of `never`.\n * - A value is a member of a domain when the test `is` of the domain and of each parent accepts it.\n * - A list, a record, a union and `one` test their values at each depth.\n * - A function type tests only that the value is a function. Its parameters need a test at each call.\n *\n * The function does not throw. A term that is not a value type, or a base type without a domain, holds each value.\n *\n * @param value - The value.\n * @param type - The value type.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns `true` when the value is a member of the type.\n */\nexport function member(value: unknown, type: ValueType, domains?: Readonly<Record<string, Domain>>): boolean {\n return memberAt(value, type, domains, 0);\n}\n\n/** This function tells if the record type `a` fits the record type `b`: width, closed records and optional fields. */\nfunction recordFits(\n a: Extract<Form, { readonly t: \"record\" }>,\n b: Extract<Form, { readonly t: \"record\" }>,\n domains: Readonly<Record<string, Domain>> | undefined,\n depth: number,\n gradual: boolean,\n): boolean {\n if (b.closed && (!a.closed || Object.keys(a.fields).some((key) => !Object.hasOwn(b.fields, key)))) return false;\n for (const key of Object.keys(b.fields)) {\n const want = b.fields[key];\n const needed = !b.optional.has(key);\n if (Object.hasOwn(a.fields, key)) {\n if (needed && a.optional.has(key)) return false;\n if (!fitsAt(a.fields[key], want, domains, depth, gradual)) return false;\n } else if (needed) {\n return false;\n } else if (!a.closed && formOf(want, domains).t !== \"top\") {\n // The other fields of an open record can hold each value, thus only `unknown` accepts such a field.\n return false;\n }\n }\n return true;\n}\n\n/**\n * This function is the relation `fits` at one depth of two types. The order of its tests is the order of the rules of\n * `fits`. Without `gradual`, `unknown` is only the top: it fits only `unknown`. The join uses this strict form.\n */\nfunction fitsAt(found: unknown, expected: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number, gradual = true): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const a = formOf(found, domains);\n const b = formOf(expected, domains);\n const next = depth + 1;\n if (b.t === \"top\" || a.t === \"bottom\") return true;\n if (a.t === \"top\") return gradual;\n if (a.t === \"union\") return a.members.every((item) => fitsAt(item, expected, domains, next, gradual));\n if (a.t === \"one\") return a.values.every((item) => memberAt(item, expected, domains, next));\n if (b.t === \"bottom\") return false;\n if (b.t === \"union\") return b.members.some((item) => fitsAt(found, item, domains, next, gradual));\n if (a.t === \"base\") return b.t === \"base\" && lineOf(a.name, domains).has(b.name);\n if (a.t === \"list\") return b.t === \"list\" && fitsAt(a.item, b.item, domains, next, gradual);\n if (a.t === \"record\") return b.t === \"record\" && recordFits(a, b, domains, next, gradual);\n if (b.t !== \"fn\" || a.params.length > b.params.length) return false;\n // A function fits when it accepts each argument of the expected type, and when its result fits.\n return a.params.every((param, index) => fitsAt(b.params[index], param, domains, next, gradual)) && fitsAt(a.to, b.to, domains, next, gradual);\n}\n\n/**\n * This function tells if each value of the type `found` can be where the type `expected` must be (TYPE.FITS). Each\n * check of a type uses it.\n *\n * - `unknown` fits each type, and each type fits `unknown` (TYPE.UNKNOWN). This is the gradual top.\n * - `never` fits each type. Only `never`, an empty union and an empty `one` fit `never`.\n * - A union fits when each of its types fits. A type fits a union when it fits one of its types.\n * - `one` fits when each of its values is a member of `expected`.\n * - A base type fits itself and each parent of its domain, through each level (TYPE.DOMAIN).\n * - A list fits a list when its items fit.\n * - A record fits a record with fewer fields. A field that `expected` needs is not optional in `found`, and each field\n * fits. Only a closed record fits a closed record. An open record without an optional field fits only when that\n * field is `unknown`.\n * - A function fits when it has the same or fewer parameters, each expected parameter fits its parameter, and its\n * result fits.\n *\n * The relation is sound: a member of `found` is a member of `expected` when no `unknown` is in the types. It is not\n * complete. For example, `bool` does not fit `{ \"one\": [true, false] }`. The function does not throw.\n *\n * @param found - The type that a part has.\n * @param expected - The type that the position needs.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns `true` when `found` fits `expected`.\n */\nexport function fits(found: ValueType, expected: ValueType, domains?: Readonly<Record<string, Domain>>): boolean {\n return fitsAt(found, expected, domains, 0);\n}\n\n/** This function sets an own field of a new record. 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\n/** This function is the join of two record types. A field that only one record has is optional, or absent from an open record. */\nfunction joinRecords(\n a: Extract<Form, { readonly t: \"record\" }>,\n b: Extract<Form, { readonly t: \"record\" }>,\n domains: Readonly<Record<string, Domain>> | undefined,\n depth: number,\n): ValueType {\n const closed = a.closed && b.closed;\n const fields: Record<string, ValueType> = {};\n const optional: string[] = [];\n const keys = [...Object.keys(a.fields), ...Object.keys(b.fields).filter((key) => !Object.hasOwn(a.fields, key))];\n for (const key of keys) {\n const inA = Object.hasOwn(a.fields, key);\n const inB = Object.hasOwn(b.fields, key);\n if (inA && inB) {\n setOwn(fields, key, joinAt(a.fields[key], b.fields[key], domains, depth));\n if (a.optional.has(key) || b.optional.has(key)) optional.push(key);\n } else if (closed) {\n // The other record is closed, thus the field can be absent.\n setOwn(fields, key, inA ? a.fields[key] : b.fields[key]);\n optional.push(key);\n }\n // In an open record, a field of one side can hold each value on the other side. The open join leaves it out.\n }\n return { record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) };\n}\n\n/**\n * This function makes a union of types. It puts the members of each inner union and each value of `one` together. It\n * leaves out each member that fits another member, by the strict form of `fits`.\n */\nfunction unionOf(types: readonly unknown[], domains: Readonly<Record<string, Domain>> | undefined, depth: number): ValueType {\n const members: unknown[] = [];\n const values: Json[] = [];\n let valuesAt = -1;\n const add = (type: unknown, level: number): void => {\n const form = formOf(type, domains);\n if (form.t === \"bottom\") return;\n if (form.t === \"union\" && level <= MAX_TYPE_DEPTH) {\n for (const item of form.members) add(item, level + 1);\n return;\n }\n if (form.t === \"one\") {\n if (valuesAt === -1) {\n valuesAt = members.length;\n members.push(undefined);\n }\n for (const value of form.values) if (!values.some((item) => docEquals(item, value))) values.push(value);\n return;\n }\n members.push(type);\n };\n for (const type of types) add(type, depth);\n if (valuesAt !== -1) members[valuesAt] = { one: values };\n const kept: unknown[] = [];\n for (const member of members) {\n if (kept.some((item) => fitsAt(member, item, domains, depth, false))) continue;\n for (let index = kept.length - 1; index >= 0; index -= 1) if (fitsAt(kept[index], member, domains, depth, false)) kept.splice(index, 1);\n kept.push(member);\n }\n if (kept.length === 0) return \"never\";\n return kept.length === 1 ? (kept[0] as ValueType) : { union: kept as ValueType[] };\n}\n\n/** This function is the join at one depth of two types. */\nfunction joinAt(a: unknown, b: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth: number): ValueType {\n if (depth > MAX_TYPE_DEPTH) return \"unknown\";\n const fa = formOf(a, domains);\n const fb = formOf(b, domains);\n if (fa.t === \"top\" || fb.t === \"top\") return \"unknown\";\n if (fa.t === \"bottom\") return b as ValueType;\n if (fb.t === \"bottom\") return a as ValueType;\n // The strict form keeps the join sound: a type with `unknown` inside is not under a type without it.\n if (fitsAt(a, b, domains, depth, false)) return b as ValueType;\n if (fitsAt(b, a, domains, depth, false)) return a as ValueType;\n const next = depth + 1;\n if (fa.t === \"list\" && fb.t === \"list\") return { list: joinAt(fa.item, fb.item, domains, next) };\n if (fa.t === \"record\" && fb.t === \"record\") return joinRecords(fa, fb, domains, next);\n return unionOf([a, b], domains, next);\n}\n\n/**\n * This function gives the join of two value types (TYPE.JOIN): a type that holds each member of both types. The check\n * of a type uses it for the branches of an `if` and for the items of a list.\n *\n * - `unknown` with each type gives `unknown`, and `never` with a type gives that type.\n * - When one type fits the other by the strict form of `fits`, the join is the wider type. The strict form reads\n * `unknown` only as the top.\n * - Two lists give a list of the join of their items.\n * - Two records give a record of the join of their common fields. A field of one closed record is optional in the\n * join of two closed records. The join of an open record leaves out the fields that only one record has.\n * - Each other pair gives a union. The union puts the values of `one` together and leaves out each member that fits\n * another member.\n *\n * The join is sound: a member of `a` or of `b` is a member of the join. It is not always the least such type. The\n * function does not throw.\n *\n * @param a - The first type.\n * @param b - The second type.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns The join.\n */\nexport function join(a: ValueType, b: ValueType, domains?: Readonly<Record<string, Domain>>): ValueType {\n return joinAt(a, b, domains, 0);\n}\n\n/** The most values of `one` that the text of a type shows. */\nconst MAX_TEXT_VALUES = 8;\n/** The most characters of one JSON value in the text of a type. */\nconst MAX_TEXT_VALUE = 40;\n\n/** This function gives a short text of a JSON value for the text of a type. */\nfunction valueText(value: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = String(value);\n }\n return text.length > MAX_TEXT_VALUE ? `${text.slice(0, MAX_TEXT_VALUE - 1)}…` : text;\n}\n\n/** This function gives the text of a type at one depth. `wrap` puts a union or a function type in brackets. */\nfunction textAt(type: unknown, depth: number, wrap: boolean): string {\n if (depth > MAX_TYPE_DEPTH) return \"unknown\";\n if (typeof type === \"string\") return type;\n const term = isRecord(type) ? termOf(type) : undefined;\n if (!isRecord(type) || term === undefined) return \"unknown\";\n const next = depth + 1;\n const group = (items: readonly string[]): string => (items.length === 0 ? \"never\" : items.length > 1 && wrap ? `(${items.join(\" | \")})` : items.join(\" | \"));\n if (term === \"list\") return `list<${textAt(type[\"list\"], next, false)}>`;\n if (term === \"union\") return Array.isArray(type[\"union\"]) ? group((type[\"union\"] as readonly unknown[]).map((item) => textAt(item, next, true))) : \"unknown\";\n if (term === \"one\") {\n if (!Array.isArray(type[\"one\"])) return \"unknown\";\n const values = type[\"one\"] as readonly unknown[];\n const shown = values.slice(0, MAX_TEXT_VALUES).map(valueText);\n return group(values.length > MAX_TEXT_VALUES ? [...shown, `… ${values.length - MAX_TEXT_VALUES} more`] : shown);\n }\n if (term === \"fn\") {\n if (!Array.isArray(type[\"fn\"])) return \"unknown\";\n const text = `(${(type[\"fn\"] as readonly unknown[]).map((item) => textAt(item, next, false)).join(\", \")}) => ${textAt(type[\"to\"], next, true)}`;\n return wrap ? `(${text})` : text;\n }\n const fields = type[\"record\"];\n if (!isRecord(fields)) return \"unknown\";\n const optional = Array.isArray(type[\"optional\"]) ? (type[\"optional\"] as readonly unknown[]) : [];\n const items = Object.keys(fields).map((key) => {\n const name = /^[A-Za-z_$][\\w$]*$/.test(key) ? key : JSON.stringify(key);\n return `${name}${optional.includes(key) ? \"?\" : \"\"}: ${textAt(fields[key], next, false)}`;\n });\n if (type[\"closed\"] !== true) items.push(\"...\");\n return `{${items.join(\", \")}}`;\n}\n\n/**\n * This function gives the text of a value type (TYPE.TEXT), for the reason of an issue. The function does not throw.\n *\n * - A base type gives its name.\n * - `list<T>` is a list, `{a: T, b?: U}` is a closed record, and `{a: T, ...}` is an open record.\n * - `(T, U) => V` is a function, and `T | U` is a union.\n * - `one` gives its values as JSON, and an empty union gives `never`.\n * - A term that is not a value type gives `unknown`.\n *\n * The text shows at most 8 values of `one`, and it cuts a long value.\n *\n * @param type - The value type.\n * @returns The text.\n */\nexport function typeText(type: ValueType): string {\n return textAt(type, 0, false);\n}\n\n/*\n * The functions below read one level of a type for the type rules of the kit. The package does not export them.\n */\n\n/** This function tells if a type reads as `unknown`. Such a type is the top, a term that is not a value type, or a base type without a domain. */\nexport function isUnknown(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): boolean {\n return formOf(type, domains).t === \"top\";\n}\n\n/** This function gives the type of the items of a list type, or `undefined` for each other type. */\nexport function itemOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): ValueType | undefined {\n const form = formOf(type, domains);\n return form.t === \"list\" ? form.item : undefined;\n}\n\n/** This function gives the type of a field of a record type, or `undefined` when the type is not a record with the field. */\nexport function fieldOf(type: unknown, key: string, domains: Readonly<Record<string, Domain>> | undefined): ValueType | undefined {\n const form = formOf(type, domains);\n return form.t === \"record\" && Object.hasOwn(form.fields, key) ? form.fields[key] : undefined;\n}\n\n/** This function gives the parameters and the result of a function type, or `undefined` for each other type. */\nexport function fnOf(type: unknown, domains: Readonly<Record<string, Domain>> | undefined): { readonly params: readonly ValueType[]; readonly to: ValueType } | undefined {\n const form = formOf(type, domains);\n return form.t === \"fn\" ? { params: form.params, to: form.to } : undefined;\n}\n\n/** This function tells if each value of a type can be a function. Such a type is the top, the bottom, a function type, or a union of them. */\nexport function callable(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n if (form.t === \"top\" || form.t === \"bottom\" || form.t === \"fn\") return true;\n if (form.t === \"union\") return form.members.every((item) => callable(item, domains, depth + 1));\n return form.t === \"one\" && form.values.length === 0;\n}\n\n/** This function tells if a type has no `unknown` at any depth. Then `fits` decides it without the gradual rule. */\nexport function isPrecise(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return false;\n const form = formOf(type, domains);\n const next = depth + 1;\n switch (form.t) {\n case \"top\":\n return false;\n case \"list\":\n return isPrecise(form.item, domains, next);\n case \"record\":\n return Object.keys(form.fields).every((key) => isPrecise(form.fields[key], domains, next));\n case \"fn\":\n return form.params.every((item) => isPrecise(item, domains, next)) && isPrecise(form.to, domains, next);\n case \"union\":\n return form.members.every((item) => isPrecise(item, domains, next));\n default:\n return true;\n }\n}\n\n/** The keys of the header of an envelope. A record with only these keys can have the form of an envelope. */\nexport const HEADER_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set([\"type\", \"value\", \"name\", \"own\"]);\n\n/**\n * This function tells if a member of a type can have the form of an envelope. A path asks the ladder for each step\n * into an envelope, and it follows a reference document (DEREF.COLLAPSE). Thus the type of such a member does not\n * tell what a path reaches.\n *\n * The test is conservative. A record that needs a key outside the header is not an\n * envelope. A closed record without the fields `type` and `value` is not an envelope either. A domain refuses each\n * reference document (`Domain`), and its steps tell what a step reaches.\n */\nexport function holdsEnvelope(type: unknown, domains: Readonly<Record<string, Domain>> | undefined, depth = 0): boolean {\n if (depth > MAX_TYPE_DEPTH) return true;\n const form = formOf(type, domains);\n switch (form.t) {\n case \"top\":\n return true;\n case \"union\":\n return form.members.some((item) => holdsEnvelope(item, domains, depth + 1));\n case \"one\":\n return form.values.some((value) => isEnvelope(value));\n case \"record\":\n if (Object.keys(form.fields).some((key) => !form.optional.has(key) && !HEADER_KEYS.has(key))) return false;\n return !form.closed || (Object.hasOwn(form.fields, \"type\") && Object.hasOwn(form.fields, \"value\"));\n default:\n return false;\n }\n}\n\n/**\n * What one step reaches from a member of a type: its type, or the fields of the type when no member has the step.\n * The field list is empty when the type is not a record.\n */\nexport type StepType = { readonly type: ValueType } | { readonly missing: readonly string[] };\n\n/** This function gives the index of a key into a list, as a step into the value finds it, or -1. */\nfunction indexOf(key: Key): number {\n if (typeof key === \"number\") return Number.isInteger(key) && key >= 0 ? key : -1;\n return /^\\d+$/.test(key) ? Number(key) : -1;\n}\n\n/** This function adds the keys of a list to another list, without the keys that it has. */\nfunction addKeys(into: string[], keys: readonly string[]): void {\n for (const key of keys) if (!into.includes(key)) into.push(key);\n}\n\n/** This function gives the step of a key into one JSON value of `one`: the value that it reaches, or the fields of the value. */\nfunction valueStep(value: unknown, key: Key): { readonly found: unknown } | { readonly fields: readonly string[] } {\n if (Array.isArray(value)) {\n if (key === \"length\") return { found: value.length };\n const index = indexOf(key);\n return index >= 0 && index < value.length ? { found: value[index] } : { fields: [] };\n }\n if (isRecord(value)) return Object.hasOwn(value, String(key)) ? { found: value[String(key)] } : { fields: Object.keys(value) };\n return { fields: [] };\n}\n\n/**\n * This function gives the type that a step with a key reaches from a member of a type (TYPE.PATH). The caller tests\n * first that no member can be an envelope (`holdsEnvelope`).\n *\n * - A record gives the type of its field. A closed record without the field has no such step. An open record gives\n * `unknown`.\n * - A list gives the type of its items for an index, and `number` for `length`.\n * - A base type reads the steps of its domain, then of each parent (`Domain.steps`).\n * - A union joins the steps of its types. `one` gives the values that the step reaches.\n * - Each other step gives `unknown`, and `never` gives `never`.\n *\n * @param examine - The function that examines a type of the steps of a domain, one time in a check.\n */\nexport function stepType(\n type: unknown,\n key: Key,\n domains: Readonly<Record<string, Domain>> | undefined,\n examine?: (type: ValueType, what: string) => ValueType,\n depth = 0,\n): StepType {\n if (depth > MAX_TYPE_DEPTH) return { type: \"unknown\" };\n const form = formOf(type, domains);\n const name = String(key);\n switch (form.t) {\n case \"bottom\":\n return { type: \"never\" };\n case \"base\":\n for (const each of lineOf(form.name, domains)) {\n const steps = domainOf(each, domains)?.steps;\n if (typeof steps !== \"object\" || steps === null || !Object.hasOwn(steps, name)) continue;\n const found = steps[name] as ValueType;\n return { type: examine === undefined ? found : examine(found, `type of the step ${name} of the domain ${each}`) };\n }\n return { type: \"unknown\" };\n case \"list\":\n if (key === \"length\") return { type: \"number\" };\n return { type: indexOf(key) >= 0 ? form.item : \"unknown\" };\n case \"record\":\n if (Object.hasOwn(form.fields, name)) return { type: form.fields[name] as ValueType };\n return form.closed ? { missing: Object.keys(form.fields) } : { type: \"unknown\" };\n case \"union\": {\n let joined: ValueType | undefined;\n const fields: string[] = [];\n for (const item of form.members) {\n const step = stepType(item, key, domains, examine, depth + 1);\n if (\"missing\" in step) addKeys(fields, step.missing);\n else joined = joined === undefined ? step.type : join(joined, step.type, domains);\n }\n // A member without the step makes the path fail, thus only the other members give a type.\n return joined === undefined ? { missing: fields } : { type: joined };\n }\n case \"one\": {\n const found: Json[] = [];\n const fields: string[] = [];\n for (const value of form.values) {\n const step = valueStep(value, key);\n if (\"fields\" in step) addKeys(fields, step.fields);\n else if (!found.some((item) => docEquals(item, step.found))) found.push(step.found as Json);\n }\n return found.length === 0 ? { missing: fields } : { type: { one: found } };\n }\n default:\n return { type: \"unknown\" };\n }\n}\n\n/** A term that `typeIssues` reads later: the term, its keys from the root and its depth. */\ninterface Pending {\n readonly type: unknown;\n readonly at: readonly Key[];\n readonly depth: number;\n}\n\n/**\n * This function lists the problems of a value type (TYPE.ISSUES). A problem is a term that is not a value type, a\n * base type without a domain, or a term that is too deep. `fits` and `member` read each such term as `unknown`.\n * Thus a check that reads a type from a contract can report it first.\n *\n * @param type - The value type, as JSON.\n * @param domains - The domains of the machine. A domain of the kernel that the table does not name comes from `STD_DOMAINS`.\n * @returns The problems. A term comes before its parts, and the parts keep their order.\n */\nexport function typeIssues(type: unknown, domains?: Readonly<Record<string, Domain>>): readonly TypeIssue[] {\n const issues: TypeIssue[] = [];\n const stack: Pending[] = [{ type, at: [], depth: 0 }];\n while (stack.length > 0) {\n const { type: here, at, depth } = stack.pop() as Pending;\n const issue = (reason: string, where: readonly Key[] = at): void => {\n issues.push({ at: where, reason });\n };\n if (depth > MAX_TYPE_DEPTH) {\n issue(`The value type is deeper than ${MAX_TYPE_DEPTH} terms.`);\n continue;\n }\n if (typeof here === \"string\") {\n if (here !== \"unknown\" && here !== \"never\" && domainOf(here, domains) === undefined) issue(`The machine has no domain ${here}.`);\n continue;\n }\n const term = isRecord(here) ? termOf(here) : undefined;\n if (!isRecord(here) || term === undefined) {\n issue(`A value type is a text, or a record with one of the keys ${TERMS.join(\", \")} and the keys that go with it.`);\n continue;\n }\n // The parts go on the stack in the reverse order, thus the issues come in the order of the term.\n const parts: Pending[] = [];\n const part = (each: unknown, where: readonly Key[]): void => {\n parts.push({ type: each, at: where, depth: depth + 1 });\n };\n const list = (key: string, what: string): readonly unknown[] => {\n const items = here[key];\n if (Array.isArray(items)) return items;\n issue(`The value of ${key} is a list of ${what}.`, [...at, key]);\n return [];\n };\n if (term === \"list\") part(here[\"list\"], [...at, \"list\"]);\n if (term === \"union\") list(\"union\", \"value types\").forEach((each, index) => part(each, [...at, \"union\", index]));\n if (term === \"one\") list(\"one\", \"JSON values\");\n if (term === \"fn\") {\n list(\"fn\", \"value types\").forEach((each, index) => part(each, [...at, \"fn\", index]));\n if (Object.hasOwn(here, \"to\")) part(here[\"to\"], [...at, \"to\"]);\n else issue(\"A function type has the key to: the type of its result.\");\n }\n if (term === \"record\") {\n const fields = here[\"record\"];\n if (isRecord(fields)) for (const key of Object.keys(fields)) part(fields[key], [...at, \"record\", key]);\n else issue(\"The value of record is a record of value types.\", [...at, \"record\"]);\n if (Object.hasOwn(here, \"optional\")) {\n list(\"optional\", \"field names\").forEach((name, index) => {\n if (typeof name !== \"string\" || !isRecord(fields) || !Object.hasOwn(fields, name)) issue(`The optional field ${String(name)} is not a field of the record.`, [...at, \"optional\", index]);\n });\n }\n if (Object.hasOwn(here, \"closed\") && typeof here[\"closed\"] !== \"boolean\") issue(\"The value of closed is true or false.\", [...at, \"closed\"]);\n }\n for (let index = parts.length - 1; index >= 0; index -= 1) stack.push(parts[index] as Pending);\n }\n return issues;\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 Domain, type ValueType, STD_DOMAINS } from \"./types.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\"]>;\ntype Facts = NonNullable<Machine[\"facts\"]>;\n\nconst NONE: ReadonlySet<string> = /* @__PURE__ */ 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/**\n * Two domains are the same when they are one object. They are also the same when they have the same test `is`,\n * parents, summary and steps. Thus two languages that give one test under one name give one domain.\n */\nfunction sameDomain(a: Domain, b: Domain): boolean {\n return a === b || (a.is === b.is && same(a.under ?? [], b.under ?? []) && a.summary === b.summary && same(a.steps ?? {}, b.steps ?? {}));\n}\n\n/** What `extendDomain` adds to a domain: more parents, and the types of more steps. */\nexport interface DomainExtension {\n /** The names of the parents to add. A member of the domain then also passes the test of each new parent. */\n readonly under?: readonly string[];\n /** The types of the steps to add. A step with the key of an earlier step replaces its type. */\n readonly steps?: Readonly<Record<string, ValueType>>;\n}\n\n/**\n * This function makes a part of a merge that adds parents or steps to a domain of an earlier part (TYPE.PARENTS). An\n * example is a domain of another language. The part reads the domain from the merge before it (`prev`). It gives a\n * copy with the same test and summary, and it names `[\"domains\", name]` in `replaces` (D17). A domain of the kernel\n * that the earlier parts do not name comes from `STD_DOMAINS`.\n *\n * A new parent adds its test to the domain (TYPE.MEMBER). Thus `fits` stays sound, but a value that fails the test of\n * the parent is no longer a member. The language that adds the parent keeps the signatures of the other language\n * true. A name without a domain gives an empty part, and `typeIssues` reports each use of that name.\n *\n * @param name - The name of the domain.\n * @param more - The parents and the steps to add.\n * @returns The part, as a function of the merge before it.\n */\nexport function extendDomain(name: string, more: DomainExtension): (prev: Machine) => MachinePart {\n return (prev) => {\n const found = own(prev.domains, name) ?? own(STD_DOMAINS, name);\n if (typeof found !== \"object\" || found === null || typeof found.is !== \"function\") return {};\n // A domain can be an instance of a class, thus the copy reads each field by its name.\n const under = [...(found.under ?? [])];\n for (const parent of more.under ?? []) if (parent !== name && !under.includes(parent)) under.push(parent);\n const steps = { ...found.steps, ...more.steps };\n const domain: Domain = {\n is: found.is,\n ...(under.length === 0 ? {} : { under }),\n ...(found.summary === undefined ? {} : { summary: found.summary }),\n ...(Object.keys(steps).length === 0 ? {} : { steps }),\n };\n const domains: Record<string, Domain> = {};\n setOwn(domains, name, domain);\n return { domains, replaces: [[\"domains\", name]] };\n };\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 = /* @__PURE__ */ new Set([\"world\", \"evaluators\", \"runners\", \"derefs\", \"walkers\", \"domains\", \"known\", \"facts\", \"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 domains?: Record<string, Domain>;\n readonly hooks: { readonly part: number; readonly known: Known }[];\n readonly factHooks: { readonly part: number; readonly facts: Facts }[];\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\n/**\n * This function composes the hooks `facts` in the order of their parts. The first answer that is not `undefined`\n * wins. A hook does not answer for a name whose code a later part replaces (D24).\n */\nfunction composeFacts(hooks: readonly { readonly part: number; readonly facts: Facts }[], replaced: ReadonlyMap<string, number>): Facts | undefined {\n const first = hooks[0];\n if (first === undefined) return undefined;\n if (hooks.length === 1 && replaced.size === 0) return first.facts;\n const list = [...hooks];\n const last = new Map(replaced);\n return (path, code) => {\n const after = last.get(code);\n for (const hook of list) {\n if (after !== undefined && hook.part < after) continue;\n const answer = hook.facts(path, code);\n if (answer !== undefined) return answer;\n }\n return undefined;\n };\n}\n\nfunction machineOf(draft: MachineDraft): Machine {\n const known = composeKnown(draft.hooks, draft.replaced);\n const facts = composeFacts(draft.factHooks, 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 ...(draft.domains === undefined ? {} : { domains: { ...draft.domains } }),\n ...(known === undefined ? {} : { known }),\n ...(facts === undefined ? {} : { facts }),\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 table `domains` merges name by name. Two domains with the same test, parents and summary give one domain (D22).\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 * The hooks `facts` compose the same way, and the first answer that is not `undefined` wins.\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: [], factHooks: [], 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.domains !== undefined) {\n const domains = (draft.domains ??= {});\n for (const name of Object.keys(part.domains)) mergeLeaf(m, domains, name, part.domains[name], [\"domains\", name], index, replaces, sameDomain, \"Two parts give two different domains for this base type.\");\n }\n if (part.known !== undefined && !draft.hooks.some((hook) => hook.known === part.known)) draft.hooks.push({ part: index, known: part.known });\n if (part.facts !== undefined && !draft.factHooks.some((hook) => hook.facts === part.facts)) draft.factHooks.push({ part: index, facts: part.facts });\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\", \"domains\"] 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]`, `[\"walkers\", name]` and `[\"domains\", 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 domains: machine.domains === undefined ? undefined : { ...machine.domains },\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 ...(tables.domains === undefined ? {} : { domains: tables.domains as NonNullable<Machine[\"domains\"]> }),\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/** A test that passes each name. A rung of `answerOf` then answers with each entry that it has. */\nconst EACH_NAME = (): boolean => true;\n\n/** The evaluator that a rung gives, without the record of the other rungs. */\nexport interface QuickAnswer {\n readonly name: string;\n readonly rung: Rung;\n}\n\n/**\n * This function finds the evaluator of a verb without the record of the rungs. It visits the rungs of `ask` in the\n * same order: the own entry, then the kind, then the default of the world (VERB.LADDER). A plan without a trace,\n * `deref` and the walkers of steps use it, thus each verb has one ladder.\n *\n * @param world - The world, for its defaults.\n * @param own - The own entries of the document, when it has some.\n * @param kind - The kind of the document. `undefined` skips the kind rung, as for a value without a type. `null` is\n * a kind that the world does not have: the question stops there, as in `ask`.\n * @param verb - The verb, for example `eval`, `format`, `deref` or `step`.\n * @param has - The test of a name. A rung answers only with a name that passes it. The default passes each name.\n * @returns The evaluator name and its rung, or `undefined` when no rung answers.\n */\nexport function answerOf(\n world: World,\n own: Readonly<Record<string, string>> | undefined,\n kind: Kind | undefined | null,\n verb: string,\n has: (name: string) => boolean = EACH_NAME,\n): QuickAnswer | undefined {\n const ownName = entryOf(own, verb);\n if (ownName !== undefined && has(ownName)) return { name: ownName, rung: \"own\" };\n if (kind === null) return undefined;\n const kindName = kind === undefined ? undefined : entryOf(kind.verbs, verb);\n if (kindName !== undefined && has(kindName)) return { name: kindName, rung: \"kind\" };\n const fallback = entryOf(world.defaults, verb);\n return fallback !== undefined && has(fallback) ? { name: fallback, rung: \"default\" } : undefined;\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. Each verb has this ladder:\n * `eval`, `deref`, `step` and each verb of a language (VERB.LADDER).\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 Kind, type World, entriesAsJson, lookupKind } from \"./world.ts\";\nimport { answerOf } from \"./ladder.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 = /* @__PURE__ */ 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. A field that holds `undefined` also gives `undefined`. The function `has` tells\n * the two cases apart (DEREF.HOST-UNDEFINED).\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 optional function tells if the thing has a field for a key. The kernel asks it only when `deref` gives\n * `undefined`. Then `true` tells that the field holds `undefined`. A thing without `has` reads `undefined` as a\n * missing field.\n *\n * @param key - The key of the step.\n * @returns `true` when the thing has the field.\n */\n has?(key: Key): boolean;\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. `{ thing: undefined }` tells that the keys reach a field that holds `undefined`.\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\n/** This function gives the own entries of an envelope, when it has a record of them. */\nfunction ownEntries(envelope: Envelope): Readonly<Record<string, string>> | undefined {\n const own = field(envelope as JsonRecord, \"own\");\n return isRecord(own) ? (own as Readonly<Record<string, string>>) : undefined;\n}\n\n/** One node of the memo of the kinds of a world: the kind of the keys up to this node, and the longer keys. */\ninterface KindNode {\n /** The kind of the keys, `null` for a type without a kind, or `undefined` before the first lookup. */\n kind?: Kind | null;\n next?: Map<Key, KindNode>;\n}\n\n/** The memo of the kinds of one world, by the keys of a type. */\ninterface KindMemo {\n first: Map<Key, KindNode>;\n /** The number of kinds in the memo. */\n size: number;\n}\n\n/** The most kinds in the memo of one world. A larger memo starts again, thus the types of the data cannot fill the memory. */\nconst MAX_KINDS = 1000;\n\nconst kindMemos = /* @__PURE__ */ new WeakMap<World, KindMemo>();\n\n/**\n * This function gives the kind of a type for the ladder: `null` when the world does not have the kind. The result\n * depends only on the world and on the keys of the type, thus a memo for each world keeps it (PLAN.KIND-MEMO). A\n * world does not change after a plan or a resolution uses it, as for `worldThing`.\n */\nfunction kindFor(world: World, type: TypeRef): Kind | null {\n const keys = typeof type === \"string\" ? undefined : typePath(type);\n // A computed type has no keys, and `lookupKind` gives it no kind.\n if (typeof type !== \"string\" && (keys === undefined || keys.length === 0)) {\n const found = lookupKind(world, type);\n return found.ok ? found.kind : null;\n }\n let memo = kindMemos.get(world);\n if (memo === undefined || memo.size >= MAX_KINDS) {\n memo = { first: new Map(), size: 0 };\n kindMemos.set(world, memo);\n }\n const node = keys === undefined ? nodeAt(memo.first, type as string) : nodeOf(memo.first, keys);\n if (node.kind === undefined) {\n const found = lookupKind(world, type);\n node.kind = found.ok ? found.kind : null;\n memo.size += 1;\n }\n return node.kind;\n}\n\n/** This function gives the node of one key in a level of the memo, and makes it when the level does not have it. */\nfunction nodeAt(level: Map<Key, KindNode>, key: Key): KindNode {\n let node = level.get(key);\n if (node === undefined) {\n node = {};\n level.set(key, node);\n }\n return node;\n}\n\n/** This function gives the node of the keys of a type in the memo. */\nfunction nodeOf(first: Map<Key, KindNode>, keys: readonly Key[]): KindNode {\n let node = nodeAt(first, keys[0] as Key);\n for (let index = 1; index < keys.length; index += 1) node = nodeAt((node.next ??= new Map()), keys[index] as Key);\n return node;\n}\n\n/** This function tells if a table of code has the name. An entry of a document can hold another value than a text. */\nfunction codeIn(table: Readonly<Record<string, unknown>>, name: unknown): boolean {\n return typeof name === \"string\" && Object.hasOwn(table, name);\n}\n\n/**\n * This function finds the walker of a step document through the ladder of the verb `step` (VERB.LADDER). The rungs\n * are the own entry, then the kind, then the default of the world. A rung answers only with a walker that the\n * navigator has. A resolution and `check` use this function, thus they agree on `#STEP?`.\n *\n * @param nav - The world and the walkers.\n * @param step - A step of a path that is not a key.\n * @returns The walker, or `undefined` when no rung answers.\n */\nexport function walkerOf(nav: Navigator, step: unknown): Walker | undefined {\n const walkers = nav.walkers;\n if (walkers === undefined || !isEnvelope(step)) return undefined;\n const answer = answerOf(nav.world, ownEntries(step), kindFor(nav.world, step.type), \"step\", (name) => codeIn(walkers, name));\n return answer === undefined ? undefined : walkers[answer.name];\n}\n\n/** The answer of `plainStep` for a field that the value does not have. A field can hold `undefined`. */\nconst NOTHING: unique symbol = /* @__PURE__ */ Symbol(\"nothing\") as never;\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): unknown {\n if (Array.isArray(thing)) {\n if (key === \"length\") return thing.length;\n const index = typeof key === \"number\" ? key : /^\\d+$/.test(key) ? Number(key) : -1;\n return index >= 0 && index < thing.length ? (thing as readonly unknown[])[index] : NOTHING;\n }\n if (typeof thing === \"object\" && thing !== null) {\n const name = String(key);\n return Object.hasOwn(thing, name) ? (thing as Readonly<Record<string, unknown>>)[name] : NOTHING;\n }\n return NOTHING;\n}\n\n/**\n * This function tells if a value can be an envelope by its field `type`. An envelope has its own field `type`, thus\n * a value without that field is not an envelope, and the full test is not necessary.\n */\nfunction mayBeEnvelope(thing: unknown): boolean {\n return typeof thing === \"object\" && thing !== null && (thing as { readonly type?: unknown }).type !== 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, then the default of the world\n * (VERB.LADDER). A rung answers only with a `deref` that the navigator has. When no rung answers, the step goes into\n * the value: an own field of an object, or an item of a list. A value without a type is data, thus the step goes\n * into it at once.\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 // DEREF.HOST-UNDEFINED: `has` tells a field that holds undefined from a missing field.\n return reached !== undefined || thing.has?.(key) === true ? { thing: reached, by: \"own\" } : undefined;\n }\n if (nav.plain !== true && mayBeEnvelope(thing) && isEnvelope(thing)) {\n const envelope = thing as JsonRecord & Envelope;\n const derefs = nav.derefs;\n // A navigator without the code of a deref needs no lookup of the kind: no rung can answer.\n const answer = derefs === undefined ? undefined : answerOf(nav.world, ownEntries(envelope), kindFor(nav.world, envelope.type), \"deref\", (name) => codeIn(derefs, name));\n if (answer !== undefined) {\n const reached = (derefs as Readonly<Record<string, DerefCode>>)[answer.name]?.(envelope, key);\n return reached === undefined ? undefined : { thing: reached, by: answer.rung };\n }\n const reached = plainStep(envelope.value, key);\n return reached === NOTHING ? undefined : { thing: reached, by: \"default\" };\n }\n const reached = plainStep(thing, key);\n return reached === NOTHING ? undefined : { thing: reached, 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 (typeof thing !== \"object\" || thing === null) return false;\n // A text type other than `ref` names another kind, thus the full test of the envelope is not necessary.\n const type = (thing as { readonly type?: unknown }).type;\n if (type === undefined || (typeof type === \"string\" && type !== \"ref\")) return false;\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 = /* @__PURE__ */ 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[] = /* @__PURE__ */ 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/** This function tells if a root has a value of its own for the short path: each root except `caps`. */\nfunction quickRoot(root: unknown): root is \"names\" | \"self\" | \"event\" | \"world\" {\n return root === \"names\" || root === \"self\" || root === \"event\" || root === \"world\";\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 (!quickRoot(root)) return undefined;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return undefined;\n if (nav.adopt !== undefined) return undefined;\n return walkQuick(ctx[root], path, nav.plain === true, false);\n}\n\n/**\n * This function walks the steps of the short path from the value of the root (DEREF.QUICK). `resolveQuick` and each\n * compiled path use it, thus the two cannot disagree. It gives `undefined` when the path needs the full algorithm.\n *\n * @param start - The value of the root.\n * @param path - The steps. The walk starts at the index 1.\n * @param plain - `true` for a plain navigation.\n * @param keyed - `true` when each step after the root is a key. The walk then does not test the steps again.\n */\nfunction walkQuick(start: unknown, path: readonly unknown[], plain: boolean, keyed: boolean): Resolution | undefined {\n let here = start;\n for (let index = 1; index < path.length; index += 1) {\n if (typeof here !== \"object\" || here === null) return undefined;\n // One read of the field `type` finds a reference document. Without the field, the value is not an envelope.\n const type = plain ? undefined : (here as { readonly type?: unknown }).type;\n if (type === \"ref\") return undefined;\n if ((here as Partial<HostThing>)[THING] === true) {\n const thing = here as HostThing;\n if (thing.resolve === undefined || !(keyed || 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 (type !== undefined && 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 * A compiled path: one static path for one navigator (PLAN.PATH). `compilePath` reads the root, the open roots and\n * the steps one time. It asks the ladder of the verb `step` for each step document one time. Each resolution then\n * examines only the values of the context.\n */\nexport interface CompiledPath {\n /** The steps of the path, as the document gives them. The list of reads records these steps. */\n readonly path: readonly unknown[];\n /** The navigator of the compilation. A runtime with another navigator resolves the steps again. */\n readonly nav: Navigator;\n /**\n * This function resolves the path from a context, without a record of hops.\n *\n * @param ctx - The context.\n * @returns The same resolution as `resolve(nav, ctx, path, { hops: false })`.\n */\n resolve(ctx: Context): Resolution;\n}\n\n/** The walker of each step document of a path, by its index: `null` when no rung answers, `undefined` for a key. */\ntype KnownWalkers = readonly (Walker | null | undefined)[];\n\n/** The root whose value starts the short path of a compiled path. `FULL` takes the full algorithm at once. */\nconst FULL = 0;\nconst FROM_NAMES = 1;\nconst FROM_SELF = 2;\nconst FROM_EVENT = 3;\nconst FROM_WORLD = 4;\ntype From = typeof FULL | typeof FROM_NAMES | typeof FROM_SELF | typeof FROM_EVENT | typeof FROM_WORLD;\n\n/**\n * A compiled path as an object with fields (PLAN.LEAN). The code of `resolve` is on the class, thus each compiled path\n * keeps only its fields and makes no closure.\n */\nclass StaticPath implements CompiledPath {\n // The constructor writes each field one time, thus each field stays constant for V8, as the variable of a closure.\n declare readonly path: readonly unknown[];\n declare readonly nav: Navigator;\n /** The walker of each step document, from the ladder of `step`, or `undefined` for a path of keys. */\n declare private readonly known: KnownWalkers | undefined;\n /** The root that starts the short path, or `FULL`. */\n declare private readonly from: From;\n declare private readonly plain: boolean;\n\n constructor(path: readonly unknown[], nav: Navigator, known: KnownWalkers | undefined, from: From, plain: boolean) {\n this.path = path;\n this.nav = nav;\n this.known = known;\n this.from = from;\n this.plain = plain;\n }\n\n resolve(ctx: Context): Resolution {\n const from = this.from;\n if (from !== FULL) {\n const start = from === FROM_NAMES ? ctx.names : from === FROM_WORLD ? ctx.world : from === FROM_SELF ? ctx.self : ctx.event;\n const quick = walkQuick(start, this.path, this.plain, true);\n if (quick !== undefined) return quick;\n }\n return resolveFully(this.nav, ctx, this.path, undefined, this.known);\n }\n}\n\n/**\n * This function compiles one static path for one navigator. The resolver gives the same thing, error and reason as\n * `resolve` without hops (PLAN.PATH-SAME). It keeps no value of a context.\n *\n * - Some paths take the full algorithm at once, because the short path cannot answer them. A path from `caps` or from\n * a closed root is one. A path with a step document and each path of a navigator with `adopt` are others.\n * - Each other path walks the short path from its root, and it takes the full algorithm when the values need it.\n * - The walker of each step document comes from the ladder one time, here. The navigator and the step document do\n * not change, thus the answer does not change either.\n *\n * @param nav - The navigator. A plan compiles its paths for its machine.\n * @param path - The steps. The first step is a root.\n * @returns The compiled path.\n */\nexport function compilePath(nav: Navigator, path: readonly unknown[]): CompiledPath {\n const keyed = keysFrom(path, 1);\n const known = keyed ? undefined : walkersOf(nav, path);\n return new StaticPath(path, nav, known, startOf(nav, path, keyed), nav.plain === true);\n}\n\n/** This function gives the root that starts the short path of a compiled path, or `FULL`. */\nfunction startOf(nav: Navigator, path: readonly unknown[], keyed: boolean): From {\n const root = path[0];\n // The short path of `resolveQuick` refuses each of these paths before it reads a value, thus it is not necessary.\n if (!keyed || !quickRoot(root) || nav.adopt !== undefined) return FULL;\n if (nav.roots !== undefined && !(nav.roots as readonly string[]).includes(root)) return FULL;\n return root === \"names\" ? FROM_NAMES : root === \"self\" ? FROM_SELF : root === \"event\" ? FROM_EVENT : FROM_WORLD;\n}\n\n/**\n * This function asks the ladder of the verb `step` for each step document of a path. A step whose lookup throws\n * stays unknown, thus the full algorithm asks the ladder again for it.\n */\nfunction walkersOf(nav: Navigator, path: readonly unknown[]): KnownWalkers | undefined {\n // Without walkers, `walkerOf` gives `undefined` at once.\n if (nav.walkers === undefined) return undefined;\n const out = new Array<Walker | null | undefined>(path.length);\n for (let index = 1; index < path.length; index += 1) {\n const step = path[index];\n if (isKey(step)) continue;\n try {\n out[index] = walkerOf(nav, step) ?? null;\n } catch {\n // The full algorithm asks the ladder again, and it gives the exception there.\n }\n }\n return out;\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 that the\n * ladder of the verb `step` gives, with the thing that the path reached. After each hop, a reference document is\n * followed until the path reaches 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 return resolveFully(nav, ctx, path, options.hops === false ? undefined : [], undefined);\n}\n\n/**\n * This function resolves a path with the full algorithm of `resolve`.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The steps.\n * @param hops - The list that gets each hop, or `undefined` for no record.\n * @param known - The walker of each step document of the path, from `compilePath`. A reference that a step reaches has its own steps, and the ladder answers them.\n * @returns What the path reached and each hop, or an error.\n */\nfunction resolveFully(nav: Navigator, ctx: Context, path: readonly unknown[], hops: Hop[] | undefined, known: KnownWalkers | undefined): Resolution {\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, undefined);\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[], walkers: KnownWalkers | undefined): 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 && keysFrom(steps, index)) {\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 given = walkers?.[index];\n const walker = given === undefined ? walkerOf(nav, step) : (given ?? undefined);\n if (walker === undefined) return failed(\"#STEP?\", \"A step is a key, or a document of a kind with the verb step.\");\n const envelope = step as Envelope;\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, known);\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 NamesSource, type ScopeRule, type Shape, type World, lookupKind } from \"./world.ts\";\nimport type { ValueType } from \"./types.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 /** The value type that the shape declares for the part (`expect`). Only a check of types reads it. */\n readonly expect?: ValueType;\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[] = /* @__PURE__ */ Object.freeze([]);\n\nfunction hasSlots(template: Template): boolean {\n return template.t !== \"data\";\n}\n\n/** This function gives the shape of a part with the default type `of` and the value type `expect` of its container. */\nfunction termOf(of: string | undefined, expect: ValueType | undefined): Shape {\n return { shape: \"term\", ...(of === undefined ? {} : { of }), ...(expect === undefined ? {} : { expect }) };\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, expect?: ValueType): Template => {\n parts.push({\n path,\n key: path.join(\".\"),\n item,\n ...(of === undefined ? {} : { of }),\n ...(address ? { address: true as const } : {}),\n ...(expect === undefined ? {} : { expect }),\n });\n return { t: \"slot\", index: parts.length - 1 };\n };\n\n const deep = (item: Json, path: readonly Key[], of: string | undefined, expect: ValueType | undefined): Template => {\n if (isEnvelope(item)) return slot(item, path, of, false, expect);\n if (Array.isArray(item)) {\n const items = (item as readonly Json[]).map((child, index) => deep(child, [...path, index], of, expect));\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, expect)] 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, spec.expect);\n }\n if (spec.shape === \"deep\") return deep(item, path, spec.of, spec.expect);\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 ?? termOf(spec.of, spec.expect);\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 ?? termOf(spec.of, spec.expect);\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, termOf(spec.of, spec.expect)]))\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\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/**\n * This function gives the names that the scope rules of a kind give each part, and the names that only later parts\n * see. `check`, `conforms` and the plan read the scope rules with it.\n *\n * @param rules - The scope rules of the kind.\n * @param value - The value of the document.\n * @param slots - The parts of the value, in order.\n * @returns The names that each part sees, and the names that only the later parts see, by the index of the part.\n */\nexport function 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","import { type Envelope, type Json, type Key, type TypeRef, isEnvelope, isKey, typeName } from \"./doc.ts\";\nimport { type PartSlot, type Split, partsOf, pathMatches, scopesOf } from \"./parts.ts\";\nimport { answerOf, ask, type Answer } from \"./ladder.ts\";\nimport type { CapsRule, Kind, KindFacts, Side } from \"./world.ts\";\nimport type { Domain } from \"./types.ts\";\nimport type { TypeRule } from \"./typing.ts\";\nimport { type ErrorCode, type EvalError, type Result, Failure, fail, ok, placed, thrown, describe } from \"./errors.ts\";\nimport {\n type Cap,\n type CompiledPath,\n type Context,\n type Hop,\n type Navigator,\n type Resolution,\n type ResolveOptions,\n type Root,\n type Thing,\n ROOTS,\n context as makeRootContext,\n isHostThing,\n isRef,\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[] = /* @__PURE__ */ Object.freeze([]);\n\n/** No capability rules. One list serves each part that no rule narrows. */\nconst NO_RULES: readonly CapsRule[] = /* @__PURE__ */ 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 key of the grant of a context (CAP.NARROW-CODE): the capabilities that the kernel gave the document of the\n * context. A spread of a context keeps its grant. Thus compiled code passes the grant on in each context that it makes\n * from the context of its document. Only the kernel writes a grant.\n */\nconst GRANT = /* @__PURE__ */ Symbol(\"coeval.grant\");\n\n/** A context with the grant of the kernel. */\ntype Granted = Context & { readonly [GRANT]?: readonly Cap[] };\n\n/**\n * This function gives a context whose capabilities its grant permits (CAP.NARROW-CODE). A context whose grant is its\n * own list of capabilities stays the same object. Each other context keeps only the capabilities that its grant\n * permits, and a context without a grant keeps none. The result has the grant of its capabilities.\n */\nfunction granted(ctx: Context): Context {\n const grant = (ctx as Granted)[GRANT];\n if (grant === ctx.caps) return ctx;\n const caps = grant === undefined ? NO_CAPS : ctx.caps.every((cap) => permits(grant, cap)) ? ctx.caps : ctx.caps.filter((cap) => permits(grant, cap));\n const out: Granted = { ...ctx, caps, [GRANT]: caps };\n return out;\n}\n\n/**\n * This function gives the context of a part of a function evaluator. It is the context that the evaluator gives,\n * narrowed by the context of the document (CAP.NARROW), with the grant of its capabilities.\n */\nfunction handed(parent: Context, next: Context): Context {\n const ctx = narrow(parent, next);\n if ((ctx as Granted)[GRANT] === ctx.caps) return ctx;\n const out: Granted = { ...ctx, [GRANT]: ctx.caps };\n return out;\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 /** The number of effects before this effect. Under `all`, this number follows the order of the host. */\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 * The stable address of the effect (RUN.ADDRESS). The order of the host does not change it. The address has the\n * keys of the place, a `#` and the count of the earlier effects at that place in its scope. An example is\n * `1/bind/x#0`. Each item of `all` is a scope, and its prefix comes first: `all0.1/` is the item 1 of the first `all`\n * of the scope. The kernel gives each effect its address.\n */\n readonly address?: string;\n /**\n * The outcome of the effect: the result that it gave its document (RUN.OUTCOME). The kernel sets it when the answer\n * comes. It stays `undefined` when the run stops first, for example at an abort.\n */\n readonly outcome?: Result;\n}\n\n/**\n * One read of an evaluation: a path that code resolved, and what the path reached (READS.RECORD, D26). A schedule\n * keeps the list of the reads of an evaluation. `verifyReads` resolves each free read again in a new context, and it\n * tells if the old result stays valid.\n */\nexport interface Read {\n /** The path that the code resolved: its root, and its steps with the value of each step document. */\n readonly path: readonly unknown[];\n /**\n * What the path reached: the thing, or the error of the resolution. A host thing stays a thing. An exception of the\n * host gives its error value.\n */\n readonly reached: Result;\n /**\n * `true` when the read reads the context of the evaluation (READS.FREE). A read of a name that a kind binds, for\n * example a name of `let`, is not free. A read of a `self` that a kind sets is not free either, for example a node\n * of a tree. A path without a root is not free. `verifyReads` resolves only the free reads again.\n */\n readonly free: boolean;\n /**\n * `true` when the kernel adds the read, because a value keeps a root of the context for later (READS.KEPT). Such a\n * read has the whole root as its path.\n */\n readonly kept?: true;\n /** The hops of the resolution, only when the code asked for them. `verifyReads` then compares each hop too. */\n readonly hops?: readonly Hop[];\n}\n\n/** The text that names a resolution in the error of an exception of the host. */\nconst READ_FAILED = \"the resolution of a path\";\n\n/**\n * This function gives what a resolution reached as a result: the thing, or the error with its code and its reason.\n * The record of a read and `verifyReads` share it.\n *\n * @param found - The resolution.\n * @returns The result.\n */\nexport function reachedOf(found: Resolution): Result {\n return found.ok ? ok(found.thing) : fail(found.code, found.reason);\n}\n\n/**\n * This function resolves the path of a read, and it gives an exception of the host as an error value. The record of\n * a kept read and `verifyReads` use it.\n *\n * @param nav - The world and the code of the evaluators.\n * @param ctx - The context.\n * @param path - The path.\n * @param hops - `true` records each hop.\n * @returns What the path reached, and the hops when the resolution gave them.\n */\nexport function readAgain(nav: Navigator, ctx: Context, path: readonly unknown[], hops: boolean): { readonly reached: Result; readonly hops?: readonly Hop[] } {\n try {\n const found = resolve(nav, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n return hops ? { reached: reachedOf(found), hops: found.hops } : { reached: reachedOf(found) };\n } catch (error) {\n return { reached: thrown(error, READ_FAILED) };\n }\n}\n\n/**\n * This function tells if a read reads the context at the root of the evaluation (READS.FREE). A kind can bind a name\n * or set `self` for its parts, and a read of that binding is not free. A path without a root reads no context. A read\n * of each other root is free. When a kind changes such a root, the read resolves again to another value, thus\n * `verifyReads` only does more work.\n */\nfunction isFree(root: Context, ctx: Context, path: readonly unknown[]): boolean {\n const head = path[0];\n if (head === \"self\") return ctx === root || Object.is(ctx.self, root.self);\n if (head !== \"names\") return typeof head === \"string\" && (ROOTS as readonly string[]).includes(head);\n if (ctx === root || ctx.names === root.names) return true;\n const name = path[1];\n // A read of the whole record of the names reads each free name too.\n if (!isKey(name)) return true;\n const key = String(name);\n const has = Object.hasOwn(ctx.names, key);\n return has === Object.hasOwn(root.names, key) && (!has || Object.is(ctx.names[key], root.names[key]));\n}\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, and a\n * `Failure` gives its own error value. In an evaluation, this function is a mock: it answers at once, and a promise\n * from it gives `#CALC!` (RUN.MOCK).\n */\nexport type Perform = (effect: Effect) => unknown;\n\n/** The key of the journal of a recorder or of a replayer, on its function. Two copies of the kernel share it. */\nexport const JOURNAL: unique symbol = /* @__PURE__ */ Symbol.for(\"coeval.journal\") as never;\n\n/**\n * The journal of a recorder or of a replayer, on its function `perform`. The kernel tells it the order in which the\n * waits of each `all` settle. In a replay, the kernel asks the journal for that order (RUN.RECORD, RUN.REPLAY).\n */\nexport interface Journal {\n /**\n * This function gets the item whose wait settled.\n *\n * @param all - The address of the `all`, for example `all0` or `all0.1/all0`.\n * @param item - The index of the item.\n */\n readonly settled?: (all: string, item: number) => void;\n /**\n * This function gives the item whose wait settles next.\n *\n * @param all - The address of the `all`.\n * @param waiting - The indices of the items that wait.\n * @returns The index of an item that waits, or `undefined` for the order of the host.\n */\n readonly next?: (all: string, waiting: readonly number[]) => number | undefined;\n}\n\n/** This function gives the journal of a function `perform`, when it has one. */\nfunction journalOf(perform: Perform | undefined): Journal | undefined {\n return perform === undefined ? undefined : (perform as { readonly [JOURNAL]?: Journal })[JOURNAL];\n}\n\n/**\n * This function gives the outcome of an effect that the host failed. A `Failure` gives its own error value, for\n * example the recorded error of a replay or `#REPLAY!`. Each other exception gives `#CALC!`, with the exception as the\n * cause (RUN.CAUSE).\n */\nfunction hostFailed(kind: string, place: readonly Key[], error: unknown): Result {\n if (error instanceof Failure) return placed({ ok: false, error: error.error }, place);\n return fail(\"#CALC!\", `The host failed the effect ${kind}: ${describe(error)}`, { place, cause: error });\n}\n\n/**\n * The scope of the addresses of effects (RUN.ADDRESS). The root of an evaluation is one scope, and each item of `all`\n * is a scope. The code of one scope does not interleave with itself, thus its counts do not depend on the host.\n */\ninterface Scope {\n /** The text before each address of the scope, for example `all0.1/`. */\n readonly prefix: string;\n /** The number of earlier effects at each place, by the text of the place. It is made at the first effect. */\n counts: Map<string, number> | undefined;\n /** The number of earlier uses of `all` in the scope. */\n alls: number;\n}\n\n/**\n * This function gives the text of a place in an address: each key, with a slash between two keys. A text key with\n * other characters than letters, digits, `_`, `$` and `-` gets quotes.\n *\n * @param place - The keys from the root document to a document.\n * @returns The text of the place.\n */\nexport function placeText(place: readonly Key[]): string {\n let text = \"\";\n for (let index = 0; index < place.length; index += 1) {\n const key = place[index] as Key;\n if (index > 0) text += \"/\";\n text += typeof key === \"number\" || /^[\\w$-]+$/.test(key) ? String(key) : JSON.stringify(key);\n }\n return text;\n}\n\n/** An effect while the kernel waits for its outcome. */\ntype Recorded = { -readonly [K in keyof Effect]: Effect[K] };\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. It gives only the capabilities that the document has (CAP.NARROW-CODE).\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 answer of the mock, the payload without a mock, 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. It gives only the capabilities that the document has (CAP.NARROW-CODE).\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 * This optional function tells the runtime that a value keeps the context for later, for example a closure of\n * `fn`. A later use of the value reads that context, and no evaluation records these reads. Thus the list of reads\n * gets a read of each root of the context (READS.KEPT).\n */\n keepsContext?(): void;\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/**\n * Compiled code: the evaluation of a document in a context. The code gives each part a context that it makes from\n * its own context with a spread. The part then keeps only the capabilities of the document (CAP.NARROW-CODE). A\n * context that the code makes without a spread gives the part no capabilities.\n */\nexport type Code = (ctx: Context, rt: Runtime) => Result;\n\n/**\n * Compiled code that can wait: the run of a document in a context. Its parts keep only the capabilities of the\n * document, as for `Code`.\n */\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 /** The machine of the evaluation, for example for its domains (D40). The kernel sets it. */\n readonly machine?: Machine;\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 answer of the mock, the payload without a mock, or an error value, for example `#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 /** The machine of the evaluation, for example for its domains (D40). The kernel sets it. */\n readonly machine?: Machine;\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, a mock answers the effect at once, or 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 * The type rule of the evaluator: the value types that a check of types gives its documents and their parts\n * (TYPE.RULE). Only a check reads it. An evaluator without a rule gives `unknown`.\n */\n readonly type?: TypeRule;\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. A run,\n * `check` and `effectsOf` ask it (CAP.PERMITS). In a check, its context has only the capabilities and the world.\n * - `known`: the names that the evaluators know, for `check`. Without it, `check` does not check such names.\n * - `domains`: the value domains of the language, by the name of their base type (D22).\n * - `facts`: the static facts of the names that a fallback kind covers, for `factsOf` (D24).\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 of the verb of the check 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 * The value domains of the language, by the name of their base type, for example a color or a unit of length. A\n * check reads them through `fits` and `member`. A domain of the kernel that the table does not name comes from\n * `STD_DOMAINS`.\n */\n readonly domains?: Readonly<Record<string, Domain>>;\n /**\n * This function gives the static facts of the code of a name, for `factsOf` (D24). An example is the operation\n * `[\"ops\", \"now\"]` of a formula language: a fallback kind names it, and only the language knows that it is volatile.\n * Each field of the answer wins over the same field of the contract of the kind. The function must be pure.\n *\n * @param path - The keys of the kind of the document, after each alias.\n * @param code - The name of the evaluator of the document, or of the walker of a step document.\n * @returns The facts, or `undefined` for the facts of the contract.\n */\n readonly facts?: (path: readonly Key[], code: string) => KindFacts | undefined;\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 of the plan, `eval` by default. */\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/**\n * The options of `plan.run`. A plan keeps the verb and the declared type of its `prepare`, thus these options do not\n * have them (PLAN.RUN-OPTIONS).\n */\nexport interface PlanRunOptions {\n /** The host code that does each effect. Without it, an effect gives its payload, as in an evaluation. */\n readonly perform?: Perform;\n /** A signal of the host. When it aborts, the run stops with `#ABORT`. */\n readonly signal?: StopSignal;\n /**\n * A list that gets each read, in the order of the resolutions (READS.RECORD). Under `all`, the order of the host\n * decides the order of the reads of the items.\n */\n readonly reads?: Read[];\n}\n\n/** The options of `run`: the options of `plan.run`, and the type of a bare root value and the verb for `prepare`. */\nexport interface RunOptions extends PlanRunOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The verb of `run`, for example `format`. The default is `eval` (VERB.PREPARE). */\n readonly verb?: string;\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 * The mock of the host (RUN.MOCK). It answers each effect at once, and its answer is the result of the effect.\n * Without it, an effect gives its payload (RUN.EVAL).\n */\n readonly perform?: Perform;\n /**\n * A list that gets each read, in the order of the resolutions (READS.RECORD). Without it, the plan records no read,\n * and each resolution costs one more test.\n */\n readonly reads?: Read[];\n}\n\n/** The options of `evaluate`. */\nexport interface EvaluateOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /** The verb that goes up the ladder at each document, for example `format`. The default is `eval` (VERB.PREPARE). */\n readonly verb?: string;\n /** The mock of the host (RUN.MOCK). Without it, an effect gives its payload (RUN.EVAL). */\n readonly perform?: Perform;\n /** A list that gets each read, in the order of the resolutions (READS.RECORD). */\n readonly reads?: Read[];\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 = /* @__PURE__ */ Object.freeze({ hops: false });\nconst WITH_HOPS: ResolveOptions = /* @__PURE__ */ Object.freeze({ hops: true });\n\n/** The record of the reads of one evaluation (READS.RECORD). */\ninterface Reading {\n readonly list: Read[];\n /** The context at the root of the evaluation. A free read has the binding of this context. */\n readonly root: Context;\n /** `true` after the kernel added a read of each root (READS.KEPT). */\n kept: boolean;\n /** `true` after the kernel added the read of the root `self`. */\n self: boolean;\n}\n\n/** This function makes the record of the reads of an evaluation, when the host gives a list. */\nfunction readingOf(list: Read[] | undefined, root: Context): Reading | undefined {\n return list === undefined ? undefined : { list, root, kept: false, self: false };\n}\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 * The scope of the addresses of the code that runs at this time (RUN.ADDRESS). `all` changes it for each item. The\n * root scope is made at the first effect or `all`, thus an evaluation without effects makes no scope.\n */\n private scope: Scope | 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 /** The record of the reads. Without it, a resolution records nothing. */\n private readonly reading: Reading | undefined = 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 /** `true` when the evaluation records its reads. Then folded code evaluates again, thus each read goes in the list (PLAN.FOLD). */\n get recording(): boolean {\n return this.reading !== undefined;\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n return this.read(ctx, path, undefined, options);\n }\n\n /**\n * This function resolves a compiled path (PLAN.PATH). Without a list of reads and without a trace, the compiled\n * path answers at once. Each other resolution records its read, as `resolve` does.\n */\n resolvePath(ctx: Context, compiled: CompiledPath): Resolution {\n if (this.reading === undefined && !this.traced && compiled.nav === this.machine) return compiled.resolve(ctx);\n return this.read(ctx, compiled.path, compiled, undefined);\n }\n\n /** This function resolves a path, and records its read when the evaluation has a list of reads (READS.RECORD). */\n private read(ctx: Context, path: readonly unknown[], compiled: CompiledPath | undefined, options: ResolveOptions | undefined): Resolution {\n const hops = options?.hops ?? this.traced;\n const reading = this.reading;\n if (reading === undefined) return this.find(ctx, path, compiled, hops);\n const free = isFree(reading.root, ctx, path);\n // A kind that sets another self can give the old self on, as the parent of a node of a tree does (READS.KEPT).\n if (!free && path[0] === \"self\" && !reading.self) this.keep(reading, [\"self\"]);\n // A free read of the whole root self already holds what a kept read of self holds, as the root of a tree reads it.\n else if (free && path.length === 1 && path[0] === \"self\") reading.self = true;\n let found: Resolution;\n try {\n found = this.find(ctx, path, compiled, hops);\n } catch (error) {\n reading.list.push({ path, reached: thrown(error, READ_FAILED), free });\n throw error;\n }\n const asked = options?.hops === true;\n reading.list.push(asked ? { path, reached: reachedOf(found), free, hops: found.hops } : { path, reached: reachedOf(found), free });\n return found;\n }\n\n /**\n * This function resolves the steps of a path. A compiled path of this machine answers a resolution without hops. A\n * resolution with hops, and a path that compiled for another navigator, resolve the steps again.\n */\n private find(ctx: Context, path: readonly unknown[], compiled: CompiledPath | undefined, hops: boolean): Resolution {\n if (compiled !== undefined && !hops && compiled.nav === this.machine) return compiled.resolve(ctx);\n return resolve(this.machine, ctx, path, hops ? WITH_HOPS : WITHOUT_HOPS);\n }\n\n keepsContext(): void {\n const reading = this.reading;\n if (reading === undefined || reading.kept) return;\n reading.kept = true;\n this.keep(reading, reading.self ? ROOTS.filter((root) => root !== \"self\") : ROOTS);\n }\n\n /**\n * This function adds a read of each whole root to the list, from the context at the root (READS.KEPT). An exception\n * of the host gives the error value of the read, because the evaluation did not ask for the read.\n */\n private keep(reading: Reading, roots: readonly Root[]): void {\n for (const root of roots) {\n if (root === \"self\") reading.self = true;\n const path = [root];\n reading.list.push({ path, reached: readAgain(this.machine, reading.root, path, false).reached, free: true, kept: true });\n }\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 /**\n * This function checks the capability of an effect, and records the effect with its address (RUN.ADDRESS). The\n * context keeps only the capabilities of its grant, thus compiled code cannot widen the context of its own effect\n * (CAP.NARROW-CODE).\n */\n private record(given: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result | Recorded {\n const ctx = granted(given);\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 scope = (this.scope ??= { prefix: \"\", counts: undefined, alls: 0 });\n const at = placeText(place);\n const counts = (scope.counts ??= new Map<string, number>());\n const count = counts.get(at) ?? 0;\n counts.set(at, count + 1);\n const effect: Recorded = {\n index: list.length,\n kind: text,\n path: keys,\n payload,\n node: node?.id ?? -1,\n at: this.tick,\n place,\n context: ctx,\n address: `${scope.prefix}${at}#${count}`,\n };\n list.push(effect);\n if (node !== undefined) node.effects.push(effect.index);\n return effect;\n }\n\n /**\n * This function answers an effect at once, without a wait: the mock gives the result, or the effect gives its\n * payload without a mock (RUN.MOCK, RUN.EVAL). A promise from the mock gives `#CALC!`.\n */\n private answer(effect: Recorded, place: readonly Key[]): Result {\n const perform = this.perform;\n if (perform === undefined) return (effect.outcome = ok(effect.payload));\n let done: unknown;\n try {\n done = perform(effect);\n } catch (error) {\n return (effect.outcome = hostFailed(effect.kind, place, error));\n }\n if (!(done instanceof Promise)) return (effect.outcome = ok(done));\n // The evaluation does not read the promise, thus its rejection must not be unhandled.\n void done.catch(() => undefined);\n return (effect.outcome = fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place }));\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 : this.answer(made, place);\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 this.answer(made, place);\n let done: unknown;\n try {\n done = perform(made);\n } catch (error) {\n return (made.outcome = hostFailed(made.kind, place, error));\n }\n if (!(done instanceof Promise)) return (made.outcome = ok(done));\n const result = (yield done.then(\n (value: unknown) => ok(value),\n (error: unknown) => hostFailed(made.kind, place, error),\n )) as Result;\n // A run that stops at this wait does not reach this line, thus the effect keeps no outcome (RUN.OUTCOME).\n return (made.outcome = 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 // The address of this call, and a scope for each item (RUN.ADDRESS). The journal of a replay reads the address.\n const outer = (this.scope ??= { prefix: \"\", counts: undefined, alls: 0 });\n const address = `${outer.prefix}all${outer.alls}`;\n outer.alls += 1;\n const scopes: Scope[] = new Array<Scope>(list.length);\n const journal = journalOf(this.perform);\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 const before = this.scope;\n this.scope = scopes[index] as Scope;\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 } finally {\n this.scope = before;\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 scope: Scope = { prefix: `${address}.${index}/`, counts: undefined, alls: 0 };\n scopes[index] = scope;\n const begin = list[index] as () => Steps;\n let steps: Steps;\n const before = this.scope;\n this.scope = scope;\n try {\n steps = begin();\n } catch (error) {\n settle(index, thrown(error, \"a part\"));\n continue;\n } finally {\n this.scope = before;\n }\n advance(index, steps, { threw: false });\n }\n };\n start();\n while (active.length > 0 && !failed) {\n // A replay settles the waits in the recorded order. Each other run takes the first wait that settles.\n const chosen = journal?.next?.(address, active.map((item) => item.index));\n const pick = chosen === undefined ? undefined : active.find((item) => item.index === chosen);\n const settled = (yield pick === undefined ? Promise.race(active.map((item) => item.pending)) : pick.pending) as {\n readonly item: Active;\n readonly value?: unknown;\n readonly error?: unknown;\n readonly threw: boolean;\n };\n journal?.settled?.(address, settled.item.index);\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\n/**\n * This function resolves a compiled path through a runtime (PLAN.PATH). The runtime of the kernel uses the compiled\n * path. Each other runtime gets the steps through `resolve`, thus a runtime that wraps another runtime sees each path.\n *\n * @param rt - The runtime.\n * @param ctx - The context.\n * @param compiled - The compiled path, from `compilePath`.\n * @returns What the path reached, or an error.\n */\nexport function resolveCompiled(rt: Runtime, ctx: Context, compiled: CompiledPath): Resolution {\n return rt instanceof Session ? rt.resolvePath(ctx, compiled) : rt.resolve(ctx, compiled.path);\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/**\n * This function gives the reason of a runner that waits where its parent cannot wait (RUN.WAIT). The plan, the\n * reference and `check` with the option `run` give the same reason.\n *\n * @param kindText - The text of the type of the runner document.\n * @returns The reason.\n */\nexport function waitedReason(kindText: string): string {\n return `${kindText} waits for effects, and its parent cannot wait. Give the parent a runner.`;\n}\n\n/** This function drives steps that cannot wait. A step that waits stops the steps, and gives `#CALC!`. */\nfunction drive(steps: Steps, kindText: string): 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!\", waitedReason(kindText));\n void steps.return(waited);\n return waited;\n}\n\nconst ABORTED = /* @__PURE__ */ 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 * The verb that goes up the ladder at each document, for example `format`. Each part evaluates with the same verb.\n * The default is `eval` (VERB.PREPARE).\n */\n readonly verb?: string;\n /**\n * `false`: no part of the plan folds. The default is `true`. Then a closed pure part of a plan without a trace\n * evaluates one time, when the plan compiles. Its result is one frozen value for each evaluation (PLAN.FOLD).\n */\n readonly fold?: 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. A mock can answer each\n * effect at once (RUN.MOCK).\n *\n * @param context - The names and the capabilities at the root.\n * @param options - A list that gets the effects, the mock of the host and a list that gets the reads.\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, a signal to stop the run and a list that gets the reads.\n * @returns The result, when the run ends.\n */\n run(context?: Context, options?: PlanRunOptions): Promise<Result>;\n}\n\ninterface Compiler {\n readonly machine: Machine;\n readonly traced: boolean;\n readonly maxDepth: number;\n /** The verb that goes up the ladder at each document. */\n readonly verb: string;\n /** The answer of a document that the ladder did not see, in a trace. */\n readonly noAnswer: Answer;\n /** `true` when closed pure parts fold (PLAN.FOLD). A plan with a trace does not fold. */\n readonly fold: boolean;\n /** The runtime of the folds of this compilation. The first fold makes it. */\n probe?: Probe;\n}\n\nfunction failing(c: Compiler, meta: Meta, place: readonly Key[], code: ErrorCode, reason: string): Compiled {\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): Compiled {\n const plain: Code = () => result;\n return finish(c, meta, plain, undefined);\n}\n\n/**\n * This function gives the code of a document in a trace. Each node records the context that its grant permits\n * (CAP.NARROW-CODE), as the code of the document gets it.\n */\nfunction finish(c: Compiler, meta: Meta, code: Code, steps: RunCode | undefined): Compiled {\n if (!c.traced) return { code, run: steps };\n const run = steps ?? runOf(code);\n const tracedCode: Code = (given, rt) => {\n const ctx = granted(given);\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* (given, rt) {\n const ctx = granted(given);\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/** The meta of a node of a compilation without a trace. Only a trace reads the meta of a node. */\nconst NO_META: Meta = /* @__PURE__ */ 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): Compiled {\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: c.noAnswer, 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: c.noAnswer, 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 let quick: ReturnType<typeof answerOf>;\n if (c.traced) {\n const answer = ask(world, envelope ?? {}, c.verb, 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 // A document has a type here, thus a kind that the read did not find is a kind that the world does not have.\n quick = answerOf(world, envelope?.own, kind ?? null, c.verb);\n name = quick?.name;\n unknown = quick === undefined && kind === undefined;\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 // The free names of each part, for the fold of this document (PLAN.FOLD). A plan without folds does not collect them.\n const frees: (readonly string[] | undefined)[] | undefined = c.fold ? [] : undefined;\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 frees?.push(own.free);\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 const run = compiled.run ?? runOf(compiled.code);\n return header === undefined\n ? { key: slot.key, path: slot.path, code: compiled.code, run }\n : { key: slot.key, path: slot.path, name: header, code: compiled.code, 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 // Code that cannot fail needs no place and no catch, and it does not read the context of its grant (PLAN.TOTAL).\n const done = finish(c, meta, TOTAL.has(inner) ? inner : placedCode(inner, place, name), undefined);\n if (frees === undefined || kind === undefined || !pureCode(c, envelope, kind, typePath, name, quick)) return done;\n const free = freeOf(doc, kind, split.parts, frees);\n if (free === undefined) return done;\n return free.length === 0 ? folded(c, done) : { code: done.code, run: done.run, free };\n}\n\n/*\n * The fold of a closed pure part (PLAN.FOLD, D43). A part folds when it evaluates one time at compile time, and its\n * code then gives that one result. These conditions make the result the same as at each evaluation:\n *\n * - The code of the part and of each part in it is pure, and the kind declares no effect and no run side.\n * - The part reads no name that it does not bind (STATIC.REFS). A reference is the only document that reads a name.\n * - The evaluation at compile time gets an empty context and a probe runtime. The probe resolves only the names that\n * the part binds. It refuses each other read, each effect and each closure that keeps its context.\n *\n * A refusal, an exception, the error #DEPTH! and a result that is not plain data cancel the fold.\n */\n\n/** The free names of a closed part. */\nconst CLOSED: readonly string[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function tells if the code of a document is pure, by the facts of D24 (FACTS.PURE). It reads the facts as\n * `factsOf` reads them. A kind with a run side, with declared effects or with volatile code is not pure here.\n */\nfunction pureCode(c: Compiler, envelope: Envelope | undefined, kind: Kind, typePath: readonly Key[], name: string, quick: ReturnType<typeof answerOf>): boolean {\n if (kind.side === \"run\" || (kind.effects !== undefined && kind.effects.length > 0)) return false;\n let answer: KindFacts | undefined;\n try {\n answer = c.machine.facts?.(typePath, name);\n } catch {\n return false;\n }\n // The contract of the kind describes the code of its own name, or an own entry that names the same code (D24).\n const described = c.verb === \"eval\" && (envelope === undefined || quick?.rung !== \"own\" || name === answerOf(c.machine.world, undefined, kind, c.verb)?.name);\n const pure = described ? (answer?.pure ?? kind.pure) : answer?.pure;\n const volatile = described ? (answer?.volatile ?? kind.volatile) : answer?.volatile;\n return pure === true && volatile !== true;\n}\n\n/**\n * This function gives the names that a document reads and does not bind, or `undefined` when the document can read\n * other roots. A reference reads the name of its path. Each other document reads the free names of its parts, less\n * the names that its scope rules give each part (STATIC.REFS).\n */\nfunction freeOf(doc: Envelope, kind: Kind, slots: readonly PartSlot[], frees: readonly (readonly string[] | undefined)[]): readonly string[] | undefined {\n if (isRef(doc)) {\n const path = doc.value;\n if (path.length < 2 || path[0] !== \"names\" || !path.every((step, index) => index === 0 || isKey(step))) return undefined;\n return [String(path[1])];\n }\n let sees: readonly (readonly string[])[] | undefined;\n let out: string[] | undefined;\n for (let index = 0; index < frees.length; index += 1) {\n const free = frees[index];\n if (free === undefined) return undefined;\n if (free.length === 0) continue;\n if (sees === undefined) sees = kind.scope === undefined || kind.scope.length === 0 ? [] : scopesOf(kind.scope, doc.value, slots).sees;\n const bound = sees[index] ?? CLOSED;\n for (const name of free) {\n if (bound.includes(name)) continue;\n out ??= [];\n if (!out.includes(name)) out.push(name);\n }\n }\n return out ?? CLOSED;\n}\n\n/** This class is the runtime of a fold. It reads only the names that the folded part binds, and it causes no effect. */\nclass Probe implements Runtime {\n readonly running = false;\n /** `true` after the part asked for something that a fold cannot give. */\n refused = false;\n /** The count of the names that the part read. */\n reads = 0;\n /**\n * The context of the folded part. Its roots `self`, `event` and `names` are traps: a direct read of a field\n * refuses the fold, as a resolution of these roots does. A copy of the record of the names reads no field.\n */\n readonly root: Context;\n\n constructor(readonly machine: Machine) {\n const refuse = (): void => {\n this.refused = true;\n };\n const root: Granted = {\n self: trap(refuse, false),\n event: trap(refuse, false),\n names: trap(refuse, true) as Readonly<Record<string, unknown>>,\n world: worldThing(machine.world),\n caps: NO_CAPS,\n [GRANT]: NO_CAPS,\n };\n this.root = root;\n }\n\n resolve(ctx: Context, path: readonly unknown[]): Resolution {\n const name = path[1];\n if (path[0] === \"names\" && isKey(name) && Object.hasOwn(ctx.names, String(name))) {\n this.reads += 1;\n const found = resolve(this.machine, ctx, path, WITH_HOPS);\n // A reference in the data resolves in the context of its reader, thus it can read a free name (DEREF.READER).\n if (found.hops.some((hop) => hop.by === \"collapse\" || isRef(hop.thing))) this.refused = true;\n return found;\n }\n this.refused = true;\n return { ok: false, code: \"#REF!\", reason: \"A folded part reads only the names that it binds.\", hops: [] };\n }\n\n effect(): Result {\n this.refused = true;\n return fail(\"#CAP!\", \"A folded part causes no effect.\");\n }\n\n *runEffect(): Steps {\n return this.effect();\n }\n\n *all(): Generator<Promise<unknown>, readonly Result[], unknown> {\n this.refused = true;\n return [];\n }\n\n keepsContext(): void {\n this.refused = true;\n }\n}\n\n/**\n * This function makes a trap for a root of the context of a fold. Each read of a field calls `refuse`. A trap of the\n * names gives no keys, thus a copy of the names reads no field.\n */\nfunction trap(refuse: () => void, copies: boolean): object {\n const no = (): undefined => {\n refuse();\n return undefined;\n };\n return new Proxy(\n {},\n {\n get: no,\n getOwnPropertyDescriptor: no,\n has: () => (refuse(), false),\n ownKeys: () => {\n if (!copies) refuse();\n return [];\n },\n getPrototypeOf: () => (refuse(), null),\n set: () => (refuse(), false),\n defineProperty: () => (refuse(), false),\n deleteProperty: () => (refuse(), false),\n },\n );\n}\n\n/**\n * This function folds the code of a closed pure part. The part evaluates one time with the probe. Its result becomes\n * one deeply frozen copy, and the code gives that copy at each evaluation (PLAN.SHARED). A fold that the probe cancels\n * gives the code without free names, thus no parent tries the fold again.\n */\nfunction folded(c: Compiler, done: Compiled): Compiled {\n const probe = (c.probe ??= new Probe(c.machine));\n probe.refused = false;\n probe.reads = 0;\n let constant: Result | undefined;\n try {\n const result = done.code(probe.root, probe);\n if (!probe.refused && (result.ok || result.error.code !== \"#DEPTH!\")) constant = sharedCopy(result) as Result | undefined;\n } catch {\n constant = undefined;\n }\n if (constant === undefined) return { code: done.code, run: done.run };\n const value = constant;\n if (probe.reads === 0) return { code: () => value, run: undefined, free: CLOSED };\n // The part reads its own names. A list of reads gets each read, thus the code evaluates again (READS.RECORD).\n const original = done.code;\n return { code: (ctx, rt) => (rt instanceof Session && !rt.traced && !rt.recording ? value : original(ctx, rt)), run: undefined, free: CLOSED };\n}\n\n/** The objects that a fold made. Each one is deeply frozen, thus a later fold uses it again and does not copy it. */\nconst SHARED: WeakSet<object> = /* @__PURE__ */ new WeakSet();\n\n/** The mark of a value that is not plain data. */\nconst NOT_PLAIN: unique symbol = /* @__PURE__ */ Symbol(\"not plain\");\n\n/**\n * This function gives a deeply frozen copy of plain data, or `undefined` for other values. Plain data is a primitive or\n * an array without holes and extra keys. It is also a record of enumerable data fields with the prototype of an object\n * or no prototype. The copy keeps cycles and shared objects. The objects of the host do not change.\n */\nfunction sharedCopy(value: unknown): unknown {\n try {\n const out = copyPlain(value, new Map());\n return out === NOT_PLAIN ? undefined : out;\n } catch {\n // A very deep value overflows the stack of the host.\n return undefined;\n }\n}\n\n/** This function copies one value for `sharedCopy`. The map holds the copy of each object that the copy saw. */\nfunction copyPlain(value: unknown, memo: Map<object, unknown>): unknown {\n if (typeof value === \"function\") return NOT_PLAIN;\n if (typeof value !== \"object\" || value === null) return value;\n if (SHARED.has(value)) return value;\n const seen = memo.get(value);\n if (seen !== undefined) return seen;\n const proto: unknown = Object.getPrototypeOf(value);\n const keys = Reflect.ownKeys(value);\n let out: Record<string, unknown> | unknown[];\n if (Array.isArray(value)) {\n if (proto !== Array.prototype || keys.length !== value.length + 1) return NOT_PLAIN;\n const list: unknown[] = [];\n memo.set(value, list);\n for (let index = 0; index < value.length; index += 1) {\n const field = Object.getOwnPropertyDescriptor(value, index);\n if (field === undefined || !(\"value\" in field) || field.enumerable !== true) return NOT_PLAIN;\n const item = copyPlain(field.value, memo);\n if (item === NOT_PLAIN) return NOT_PLAIN;\n list.push(item);\n }\n out = list;\n } else {\n if (proto !== Object.prototype && proto !== null) return NOT_PLAIN;\n const record: Record<string, unknown> = proto === null ? (Object.create(null) as Record<string, unknown>) : {};\n memo.set(value, record);\n for (const key of keys) {\n if (typeof key !== \"string\") return NOT_PLAIN;\n const field = Object.getOwnPropertyDescriptor(value, key);\n if (field === undefined || !(\"value\" in field) || field.enumerable !== true) return NOT_PLAIN;\n const item = copyPlain(field.value, memo);\n if (item === NOT_PLAIN) return NOT_PLAIN;\n // The key __proto__ is a field of the data, thus it does not set the prototype of the copy.\n if (key === \"__proto__\") Object.defineProperty(record, key, { value: item, enumerable: true, writable: true, configurable: true });\n else record[key] = item;\n }\n out = record;\n }\n Object.freeze(out);\n SHARED.add(out);\n return out;\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/**\n * The compiled code that cannot fail (PLAN.TOTAL). Such code gives a value and throws nothing. It does not read its\n * context or its runtime. Only the kits of the kernel mark code, thus the code of a host always gets its grant.\n */\nconst TOTAL: WeakSet<Code> = /* @__PURE__ */ new WeakSet();\n\n/**\n * This function marks compiled code that cannot fail (PLAN.TOTAL). Then `compileNode` does not wrap the code in\n * `placedCode`, thus a literal costs one call. The kits of the kernel use it. The package does not export it.\n *\n * @param code - The code. It gives a value and throws nothing. It does not read its context or its runtime.\n * @returns The same code.\n */\nexport function totalCode(code: Code): Code {\n TOTAL.add(code);\n return code;\n}\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\n * exception. The code gets the context that its grant permits, thus a compiled parent cannot widen it (CAP.NARROW-CODE).\n */\nfunction placedCode(inner: Code, place: readonly Key[], name: string): Code {\n return (ctx, rt) => {\n try {\n return placed(inner(granted(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. First the context keeps only the capabilities of its grant, thus a compiled\n * parent cannot widen the capabilities that the rules narrow (CAP.NARROW-CODE).\n */\nfunction gated(rules: readonly CapsRule[], part: Compiled): Compiled {\n const inner = part.code;\n const steps = part.run;\n const under = (given: Context): Context => {\n const ctx = granted(given);\n const caps = capsUnder(rules, ctx.caps);\n if (caps === ctx.caps || (caps.length === 0 && ctx.caps.length === 0)) return ctx;\n const out: Granted = { ...ctx, caps, [GRANT]: caps };\n return out;\n };\n // The steps of an evaluator are `runOf` of its code, thus `runOf` of this code narrows the context the same way.\n return { code: (ctx, rt) => inner(under(ctx), rt), run: steps === undefined ? undefined : (ctx, rt) => steps(under(ctx), rt) };\n}\n\n/**\n * This function gives the steps of a runner, with the place of each error and of each exception. The steps get the\n * context that its grant permits (CAP.NARROW-CODE).\n */\nfunction placedRun(inner: RunCode, place: readonly Key[], name: string): RunCode {\n return function* (ctx, rt) {\n try {\n return placed(yield* inner(granted(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 under a parent that cannot wait: its steps, driven without a wait. An\n * evaluation and a run both drive them (RUN.DRIVE-NESTED). Only a step that really waits gives `#CALC!`, at the place\n * of the runner, where the error started (RUN.WAIT).\n */\nfunction runnerCode(run: RunCode, place: readonly Key[], kindText: string): Code {\n return (ctx, rt) => placed(drive(run(ctx, rt), kindText), place);\n}\n\n/**\n * The code of a compiled document. The steps of a run are `undefined` for an evaluator: they are `runOf(code)`, and a\n * plan makes them only for a run (PLAN.LEAN).\n */\ninterface Compiled {\n readonly code: Code;\n readonly run: RunCode | undefined;\n /**\n * The names that the document reads and does not bind, when it is pure. An empty list marks a folded document.\n * `undefined` marks a document that cannot fold, or a plan without folds (PLAN.FOLD).\n */\n readonly free?: readonly string[];\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, machine } = input;\n const address = input.address === true ? { address: true } : {};\n // The code keeps the fill and not the whole input, thus it does not keep the compiled value of the document (PLAN.LEAN).\n const refill = input.fill;\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 : handed(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 machine,\n ...address,\n resolve: (path, options) => rt.resolve(ctx, path, options),\n effect: (effectKind, payload) => rt.effect(ctx, effectKind, payload, place),\n fill: refill,\n });\n };\n}\n\nfunction interpretRun(fn: RunFn, input: CompileInput, fill: <P>(handles: readonly P[]) => unknown): RunCode {\n const { kind, typePath, doc, data, place, machine } = input;\n const refill = input.fill;\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 : handed(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 machine,\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: refill,\n });\n };\n}\n\n/**\n * This function gives the context at the root of an evaluation. It is the context of the host, with the world of\n * the machine when the context has none. The host gives the capabilities, thus the root has the grant of each one\n * (CAP.NARROW-CODE). An evaluation and `verifyReads` share it.\n *\n * @param machine - The machine.\n * @param ctx - The context of the host.\n * @returns The context at the root.\n */\nexport function rootContext(machine: Machine, ctx: Context): Context {\n if (ctx.world !== null && (ctx as Granted)[GRANT] === ctx.caps) return ctx;\n const root: Granted = { ...ctx, world: ctx.world === null ? worldThing(machine.world) : ctx.world, [GRANT]: ctx.caps };\n return root;\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 * The verb of the options goes up the ladder at each document, and each part evaluates with the same verb. The\n * default verb is `eval`. A plan of another verb, for example `format`, evaluates, runs and traces as a plan of\n * `eval` does (VERB.PREPARE).\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, a trace and the verb.\n * @returns The plan.\n */\nexport function prepare(machine: Machine, doc: unknown, options: PrepareOptions = {}): Plan {\n const verb = options.verb ?? \"eval\";\n const noAnswer: Answer = verb === \"eval\" ? NO_ANSWER : { verb, error: \"no-answer\", steps: [] };\n const traced = options.trace === true;\n const c: Compiler = { machine, traced, maxDepth: machine.maxDepth ?? 1000, verb, noAnswer, fold: !traced && options.fold !== false };\n let root: Compiled;\n try {\n root = compileNode(c, doc, [], options.declaredType, 0);\n } catch (error) {\n const result = placed(thrown(error, \"the compilation\"), []);\n root = { code: () => result, run: undefined };\n }\n return new CompiledPlan(machine, c.traced, root.code, root.run);\n}\n\n/**\n * The object of a plan (PLAN.LEAN). The code of `evaluate` and `run` is on the class, thus a plan keeps only its\n * machine and its compiled code. A plan makes its compiled root and the steps of a run at their first use.\n */\nclass CompiledPlan implements Plan {\n /*\n * The constructor writes each field one time, and the class declares the fields with `declare`. A field that a class\n * defines first as `undefined` and then writes again is not constant for V8, and the code of an evaluation then\n * loads it at each call.\n */\n declare readonly machine: Machine;\n declare readonly traced: boolean;\n /** The code of the root document. */\n declare readonly code: Code;\n /** The steps of a run of the root document. `undefined` gives `runOf(code)` at the first `run`. */\n declare private steps: RunCode | undefined;\n /** The compiled root, after the first read of `root`. */\n declare private part: CompiledPart | undefined;\n\n constructor(machine: Machine, traced: boolean, code: Code, steps: RunCode | undefined) {\n this.machine = machine;\n this.traced = traced;\n this.code = code;\n this.steps = steps;\n this.part = undefined;\n }\n\n get root(): CompiledPart {\n return (this.part ??= { key: \"\", path: [], code: this.code, run: this.runCode() });\n }\n\n /** This function gives the steps of a run of the root document. */\n runCode(): RunCode {\n return (this.steps ??= runOf(this.code));\n }\n\n evaluate(context: Context = makeContext(), evalOptions?: EvalOptions): Result {\n const machine = this.machine;\n const ctx = rootContext(machine, context);\n const s = new Session(machine, false, this.traced, evalOptions?.perform, undefined, evalOptions?.effects, readingOf(evalOptions?.reads, ctx));\n return this.code(ctx, s);\n }\n\n run(context: Context = makeContext(), runOptions: PlanRunOptions = {}): Promise<Result> {\n const machine = this.machine;\n const ctx = rootContext(machine, context);\n const s = new Session(machine, true, this.traced, runOptions.perform, runOptions.signal, undefined, readingOf(runOptions.reads, ctx));\n return driveWaiting(this.runCode()(ctx, s), runOptions.signal);\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 // A map treats -0 and 0 as one key, so -0 gets its own plan each time.\n if (Object.is(doc, -0)) return prepare(machine, doc, options);\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 of the options goes up the ladder for each document. The default verb is `eval`. The kind of the document\n * tells where its parts are. The evaluator gets each part sealed: it can evaluate the part, and it cannot read its\n * value.\n *\n * A failure gives an error value, and the function does not throw. The function records each effect in its order,\n * and the host does not do it. A mock can answer each effect at once (RUN.MOCK).\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 options - The type of a bare root value, or the options: that type, the mock of the host, the verb and a list for the reads.\n * @returns The result, the trace and the effects in their order.\n */\nexport function evaluate(machine: Machine, doc: unknown, context: Context = makeContext(), options?: string | EvaluateOptions): Run {\n const given: EvaluateOptions = typeof options === \"string\" ? { declaredType: options } : (options ?? {});\n const declaredType = given.declaredType;\n const plan = prepare(machine, doc, {\n trace: true,\n ...(declaredType === undefined ? {} : { declaredType }),\n ...(given.verb === undefined ? {} : { verb: given.verb }),\n });\n const ctx = rootContext(machine, context);\n const s = new Session(machine, false, true, given.perform, undefined, undefined, readingOf(given.reads, ctx));\n const result = (plan as CompiledPlan).code(ctx, 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, a signal, the verb and a list for the reads.\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, {\n trace: true,\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n });\n const ctx = rootContext(machine, context);\n const s = new Session(machine, true, true, options.perform, options.signal, undefined, readingOf(options.reads, ctx));\n const result = await driveWaiting((plan as CompiledPlan).runCode()(ctx, 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 {\n type EvalInput,\n type Evaluator,\n type Machine,\n type Plan,\n type Result,\n type RunPart,\n type Runner,\n type Steps,\n fail,\n ok,\n planner,\n} from \"./evaluate.ts\";\nimport { Failure } from \"./errors.ts\";\nimport { type Cap, type HostThing, type Thing, type Walker, THING, isHostThing, valueOfThing } from \"./deref.ts\";\nimport type { World } from \"./ladder.ts\";\nimport { type AttributeDeclaration, type TreeContract, equationType, lookupKind } from \"./world.ts\";\nimport { STD_DOMAINS } from \"./types.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\" }, pure: true, summary: \"A number. Its value is the result.\" },\n text: { verbs: { eval: \"data.text\", view: \"view.value\" }, pure: true, summary: \"A text. Its value is the result.\" },\n bool: { verbs: { eval: \"data.bool\", view: \"view.value\" }, pure: true, 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 pure: true,\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 pure: true,\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 pure: true,\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\" }, pure: true, 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 pure: true,\n lazy: [{ in: [[\"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 pure: true,\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 pure: true,\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 // A node that nothing reads keeps its attributes without an evaluation (TREE.LAZY).\n pure: true,\n lazy: [{}],\n // The code resolves self to find an open tree and the parent (C4, D44).\n reads: [\"self\"],\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 pure: true,\n lazy: [{}],\n reads: [\"self\"],\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 pure: true,\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 // The runner evaluates only the first part.\n pure: true,\n lazy: [{ after: 1 }],\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\": /* @__PURE__ */ dataOf(\"number\"),\n \"data.text\": /* @__PURE__ */ dataOf(\"string\"),\n \"data.bool\": /* @__PURE__ */ 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 = /* @__PURE__ */ 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 rungs of the ladder of an attribute, in their order (TREE.LADDER, D42). */\nexport type AttributeRung = \"own\" | \"kind\" | \"parent\" | \"copy\" | \"default\";\n\n/** The rungs of the ladder of an attribute, in their order (TREE.LADDER, D42). */\nexport const ATTRIBUTE_RUNGS: readonly AttributeRung[] = /* @__PURE__ */ Object.freeze([\"own\", \"kind\", \"parent\", \"copy\", \"default\"] as const);\n\n/** The record of the demand of one attribute of a node (TREE.RUNGS). */\nexport interface AttributeTrace {\n readonly attribute: string;\n /** The rungs that the demand visited, in their order. The last one answered, unless no rung answered. */\n readonly rungs: readonly AttributeRung[];\n /** The rung that answered. It is `undefined` when no rung answered. */\n readonly by?: AttributeRung;\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 /** The tree contract of the kind of the node (D42). */\n readonly tree: TreeContract | undefined;\n /**\n * This function gives an attribute through its ladder (TREE.LADDER).\n *\n * @param key - The name of the attribute.\n * @returns The result, or `undefined` when no rung answers.\n */\n read(key: string): Result | undefined;\n /**\n * This function evaluates an equation of the kind of the node, with the node as `self` and no capabilities.\n *\n * @param term - The equation.\n * @param names - The names that the equation sees.\n * @returns The result.\n */\n equation(term: Json, names: Readonly<Record<string, unknown>>): Result;\n /**\n * This function gives the names of a child for an equation of `down`: `child`, `index` and `prev` (TREE.DOWN).\n *\n * @param child - The thing of the child.\n * @returns The names, or the error of the list `children`.\n */\n childNames(child: HostThing): Result;\n /**\n * This function gives the record of the demand of an attribute that ended (TREE.RUNGS).\n *\n * @param key - The name of the attribute.\n * @returns The record, or `undefined` before the end of the demand.\n */\n trace(key: string): AttributeTrace | undefined;\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/**\n * The memo cell of one attribute: in evaluation, or done with its result and the rung that answered. A done cell\n * without a result tells that no rung answered.\n */\ntype Cell = { readonly busy: true } | { readonly busy: false; readonly result: Result | undefined; readonly by: AttributeRung | undefined };\n\n/** The capabilities of an equation: none (CAP.PURE). */\nconst NO_CAPS: readonly Cap[] = /* @__PURE__ */ Object.freeze([]);\n\n/** The names of an equation of `equations`, of a `unit` and of a `default`. */\nconst NO_NAMES: Readonly<Record<string, unknown>> = /* @__PURE__ */ Object.freeze({});\n\n/** The planners of equations, for each machine and each type of a bare equation (TREE.PLAN). */\nconst equationPlanners = /* @__PURE__ */ new WeakMap<Machine, Map<string, (doc: unknown) => Plan>>();\n\n/**\n * This function gives the plan of an equation. Each equation compiles one time for each machine (PLAN.CACHE). The\n * plan of the document does not keep it (PLAN.LEAN).\n */\nfunction equationPlan(machine: Machine, of: string | undefined, term: Json): Plan {\n let byType = equationPlanners.get(machine);\n if (byType === undefined) {\n byType = new Map();\n equationPlanners.set(machine, byType);\n }\n const key = of ?? \"\";\n let plans = byType.get(key);\n if (plans === undefined) {\n plans = planner(machine, of === undefined ? {} : { declaredType: of });\n byType.set(key, plans);\n }\n return plans(term);\n}\n\n/** This function gives the own entry of a table of a tree contract, or `undefined`. */\nfunction entryOf<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/** The contract of the kind of a node: its tree contract and the type of a bare equation. */\ninterface NodeContract {\n readonly tree: TreeContract | undefined;\n readonly of: string | undefined;\n}\n\nconst NO_CONTRACT: NodeContract = /* @__PURE__ */ Object.freeze({ tree: undefined, of: undefined });\n\n/** This function finds the tree contract of the kind of a node in the world of the machine. */\nfunction contractOf(machine: Machine | undefined, typePath: readonly Key[]): NodeContract {\n if (machine === undefined || typePath.length === 0) return NO_CONTRACT;\n const found = lookupKind(machine.world, typePath);\n if (!found.ok || found.kind.tree === undefined) return NO_CONTRACT;\n return { tree: found.kind.tree, of: equationType(found.kind) };\n}\n\nconst BUSY: Cell = /* @__PURE__ */ 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. Another step reads an attribute through its ladder (TREE.LADDER). The rungs are a part of\n * the node, an equation of its kind and an equation `down` of the kind of its parent. A copy from the parent, then a\n * fold or a default, come last. A failed attribute throws `Failure` with its own error, thus a reference to it gives that error.\n * The argument `outer` is the self of the context, that `treeNode` resolved. The node reads no root of the context directly (C4).\n */\nfunction treeThing(input: EvalInput, build: TreeBuild, outer: Thing | undefined): HostThing {\n const { parts, context, kind: type, place, machine } = input;\n const { tree, of } = contractOf(machine, input.typePath);\n const above = stateOf(outer);\n // Only a node of the same tree is a parent for the rungs `parent` and `copy`.\n const up = above !== undefined && above.build === build ? above : undefined;\n const cells = new Map<string, Cell>();\n /** The positions of the items of the list `children`, for the names of the children. */\n let positions: { readonly list: readonly unknown[]; readonly at: Map<unknown, number> } | undefined;\n\n const fold = (key: string, declared: NonNullable<AttributeDeclaration[\"fold\"]>): Result => {\n let acc = state.equation(declared.unit, NO_NAMES);\n if (!acc.ok) return acc;\n const children = read(\"children\");\n if (children === undefined) return acc;\n if (!children.ok) return children;\n if (!Array.isArray(children.value)) return fail(\"#VALUE!\", `The fold of ${key} needs a list in children.`);\n for (const item of children.value as readonly unknown[]) {\n const child = stateOf(item);\n // An item that is not a node of this tree does not count.\n if (child === undefined || child.build !== build) continue;\n const value = child.read(key);\n if (value === undefined) return fail(\"#N/A\", `No rung gives ${attributeText(key, child.type, child.place)}.`);\n if (!value.ok) return value;\n acc = state.equation(declared.combine, { acc: acc.value, item: value.value });\n if (!acc.ok) return acc;\n }\n return acc;\n };\n\n /** This function visits the rungs of the ladder of an attribute in their order, until one answers. */\n const climb = (key: string): { readonly result: Result; readonly by: AttributeRung } | undefined => {\n const part = parts.find((item) => item.key === key);\n if (part !== undefined) return { result: part.evaluate({ ...context, self: node }), by: \"own\" };\n const equation = entryOf(tree?.equations, key);\n if (equation !== undefined) return { result: state.equation(equation, NO_NAMES), by: \"kind\" };\n const down = up === undefined ? undefined : entryOf(up.tree?.down, key);\n if (up !== undefined && down !== undefined) {\n const names = up.childNames(node);\n return { result: names.ok ? up.equation(down, names.value as Readonly<Record<string, unknown>>) : names, by: \"parent\" };\n }\n const declared = entryOf(tree?.attributes, key);\n if (declared?.copy === true && up !== undefined) {\n const copied = up.read(key);\n if (copied !== undefined) return { result: copied, by: \"copy\" };\n }\n if (declared?.fold !== undefined) return { result: fold(key, declared.fold), by: \"default\" };\n if (declared?.default !== undefined) return { result: state.equation(declared.default, NO_NAMES), by: \"default\" };\n return undefined;\n };\n\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 // A node without a contract has only its parts, as before D42. Thus a missing part needs no cell.\n if (tree === undefined && up?.tree === undefined && !parts.some((item) => item.key === key)) return undefined;\n cells.set(key, BUSY);\n demands.push({ cells, key, text: attributeText(key, type, place) });\n let answer: { readonly result: Result; readonly by: AttributeRung } | undefined;\n try {\n answer = climb(key);\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: answer?.result, by: answer?.by });\n return answer?.result;\n };\n\n const state: NodeState = {\n build,\n type,\n place,\n tree,\n read,\n equation(term, names) {\n if (machine === undefined) return fail(\"#NOEVAL\", \"The evaluation of an equation needs the machine.\");\n return equationPlan(machine, of, term).evaluate({ ...context, names, caps: NO_CAPS, self: node });\n },\n childNames(child) {\n const children = read(\"children\");\n if (children !== undefined && !children.ok) return children;\n const list = children !== undefined && Array.isArray(children.value) ? (children.value as readonly unknown[]) : [];\n if (positions?.list !== list) {\n const at = new Map<unknown, number>();\n list.forEach((item, index) => {\n if (!at.has(item)) at.set(item, index);\n });\n positions = { list, at };\n }\n const index = positions.at.get(child);\n return ok({ child, index: index ?? null, prev: index === undefined || index === 0 ? null : list[index - 1] });\n },\n trace(key) {\n const cell = cells.get(key);\n if (cell === undefined || cell.busy) return undefined;\n const rungs = cell.by === undefined ? ATTRIBUTE_RUNGS : ATTRIBUTE_RUNGS.slice(0, ATTRIBUTE_RUNGS.indexOf(cell.by) + 1);\n return cell.by === undefined ? { attribute: key, rungs } : { attribute: key, rungs, by: cell.by };\n },\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 outer;\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 has(key: Key): boolean {\n // DEREF.HOST-UNDEFINED: an attribute with the value undefined is a field, not a missing step.\n if (key === \"parent\" || key === \"type\" || parts.some((part) => part.key === String(key))) return true;\n const cell = cells.get(String(key));\n return cell !== undefined && !cell.busy && cell.result !== undefined;\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 gives the record of the demand of an attribute of a node of the decorated tree (TREE.RUNGS). The\n * record holds the rungs that the demand visited, and the rung that answered. An explorer draws the ladder with it.\n *\n * @param node - The thing of a node.\n * @param attribute - The name of the attribute.\n * @returns The record, or `undefined` for a thing that is not a node or an attribute that no demand reached.\n */\nexport function attributeTrace(node: Thing, attribute: string): AttributeTrace | undefined {\n return stateOf(node)?.trace(attribute);\n}\n\n/** The path of the root `self`. A node of the tree resolves it, thus the list of reads holds the read (C4). */\nconst SELF_PATH: readonly Json[] = /* @__PURE__ */ Object.freeze([\"self\"]);\n\n/** The options of the resolution of `self`: the node needs no hops. */\nconst NO_HOPS = /* @__PURE__ */ Object.freeze({ hops: false });\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. The\n * node reads `self` through `resolve` (C4, D44). A machine that closes the root `self` thus gives no nested trees.\n */\nfunction treeNode(input: EvalInput): Result {\n const found = input.resolve(SELF_PATH, NO_HOPS);\n const outer = found.ok ? found.thing : undefined;\n const above = stateOf(outer);\n if (above !== undefined && above.build.open) return ok(treeThing(input, above.build, outer));\n const build: TreeBuild = { open: true };\n const root = treeThing(input, build, outer);\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 = /* @__PURE__ */ 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 || parts.length > 1) return fail(\"#VALUE!\", \"pure needs exactly 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, its walkers and the domains of the kernel. */\nexport const STD_MACHINE: Machine = { world: STD_WORLD, evaluators: STD_EVALUATORS, runners: STD_RUNNERS, walkers: STD_WALKERS, domains: STD_DOMAINS };\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 Key, isRecord, typeName } from \"./doc.ts\";\nimport type { Machine } from \"./evaluate.ts\";\nimport type { DocVisit, Issue } from \"./static.ts\";\nimport { type ValueType, fits, isUnknown, typeIssues, typeText } from \"./types.ts\";\n\n/*\n * The check of value types (R5 P3, D25). The pass reads the documents that the walk of `check` visited. It goes down\n * to give each part the type that its position needs, and it goes up to synthesize the type of each document from the\n * types of its parts. A type issue is a static finding: it does not change an evaluation.\n */\n\n/** What a type rule gets for one document. */\nexport interface TypeInput {\n /** The keys of the kind of the document, after each alias. */\n readonly typePath: readonly Key[];\n /** The document. A bare value has the type that its position declares. */\n readonly doc: Envelope;\n /** The type that the position of the document needs. It is `unknown` when the position needs no type. */\n readonly expected: ValueType;\n /** The paths of the parts in the value, in the order of the value. */\n readonly paths: readonly (readonly Key[])[];\n /** `true` when the position declares an address. A reference there gives a thing, not a value. */\n readonly address: boolean;\n readonly machine: Machine;\n /**\n * This function gives the type of a part that the check typed before. It gives `unknown` for a part that the check\n * did not type yet, and for a part with an issue.\n *\n * @param path - The path of the part in the value.\n * @returns The type of the part.\n */\n typeOf(path: readonly Key[]): ValueType;\n /**\n * This function gives the type of a name: the type that a kind around the document binds. Without such a kind, it\n * gives the type from the option `rootTypes` of the host.\n *\n * @param name - The name.\n * @returns The type, or `undefined` when neither a kind around the document nor the host gives the name a type.\n */\n nameType(name: string): ValueType | undefined;\n /**\n * This function gives the type of a root of the context at the document (TYPE.ROOTS). The host gives the types of\n * `self`, `world` and `event` in the option `rootTypes`. A rule can give other types to its parts. The root `caps`\n * always has the type `CAPS_TYPE`. A rule reads the type of a name with `nameType`, thus the root `names` gives\n * `unknown`.\n *\n * @param root - The root.\n * @returns The type. It is `unknown` for a root without a type.\n */\n rootType(root: string): ValueType;\n /**\n * This function examines a value type of a contract with `typeIssues`, one time in a check. The first problem of a\n * type becomes an issue at the document. A term with a problem reads as `unknown`.\n *\n * @param type - The value type of the contract.\n * @param what - What the type is, for the reason, for example \"the result of ops.add\".\n * @returns The type.\n */\n contract(type: unknown, what: string): ValueType;\n}\n\n/** What a type rule tells for one part: the type that the part must have, and the types of the names of the part. */\nexport interface PartType {\n /** The type that the part must have. */\n readonly expect?: ValueType;\n /** What the part is, for the reason of an issue, for example \"argument 2 of ops.add\". */\n readonly what?: string;\n /** The types of the names that the scope rules of the kind bind for the part. Each other name of the rules gets `unknown`. */\n readonly names?: Readonly<Record<string, ValueType>>;\n /**\n * The types of the roots that the evaluator changes for the part, for example `self` for the attributes of a node.\n * Each other root keeps its type. The parts of an evaluator without a rule get `unknown` for each of these roots.\n */\n readonly roots?: Omit<RootTypes, \"names\">;\n}\n\n/**\n * The value types of the roots of a context, for a check of types (TYPE.ROOTS). The host gives them in the option\n * `rootTypes` of `check` and `typeCheck`. A root without a type has the type `unknown`. The root `caps` always has the\n * type `CAPS_TYPE`, because the kernel narrows it.\n *\n * The host keeps the types true: each root of the context holds a member of its type. A host thing, or a machine\n * with `adopt`, keeps each step true too. The context binds each name of `names`, thus the option `names` of `check`\n * lists it too.\n */\nexport interface RootTypes {\n /** The type of each name that the host binds. A name of the host without a type here has the type `unknown`. */\n readonly names?: Readonly<Record<string, ValueType>>;\n /** The type of `self`: the node or the position that the document is part of. */\n readonly self?: ValueType;\n /** The type of `world`, for example the schema of a store. The context then gives the world. */\n readonly world?: ValueType;\n /** The type of `event`: the event that started a run. */\n readonly event?: ValueType;\n}\n\n/**\n * The value type of the root `caps`: a list of capabilities. A capability is a text, or a list of keys. The kernel\n * narrows the capabilities for each part, thus the host does not give this type.\n */\nexport const CAPS_TYPE: ValueType = { list: { union: [\"text\", { list: { union: [\"text\", \"number\"] } }] } };\n\n/** A problem that a type rule finds. Its place is a part of the document, or the document itself. */\nexport interface TypeProblem {\n /** The path of the part in the value. Without it, the problem is at the document. */\n readonly path?: readonly Key[];\n readonly reason: string;\n readonly expected?: ValueType;\n readonly found?: ValueType;\n}\n\n/**\n * The type rule of an evaluator: what a check of types knows about the values that the evaluator gives. An evaluator\n * object holds its rule in its field `type`. Thus the rule follows the evaluator that the ladder gives a document\n * (TYPE.RULE).\n */\nexport interface TypeRule {\n /**\n * This function tells the type that a part must have, and the types of the names for the part. The check asks it\n * before it types the part. The parts that give the names of a rule `keysAt` come first.\n *\n * @param input - The document, the type that its position needs, and the types of the parts before.\n * @param path - The path of the part in the value.\n * @returns The type of the part and the types of its names.\n */\n readonly part?: (input: TypeInput, path: readonly Key[]) => PartType;\n /**\n * This function synthesizes the type of the document from the types of its parts. It must be sound: each value that\n * the evaluator gives is a member of the type.\n *\n * @param input - The document, the type that its position needs, and the types of its parts.\n * @param report - The function that gets each problem that the rule finds.\n * @returns The type of the document.\n */\n readonly synth: (input: TypeInput, report: (problem: TypeProblem) => void) => ValueType;\n}\n\n/** The type of one document of a check of types. */\nexport interface Typed {\n /** The keys from the root document to the document. */\n readonly place: readonly Key[];\n /** The keys from the root JSON value to the document. */\n readonly at: readonly Key[];\n /** The type that the check synthesized. A document with an issue has the type `unknown`. */\n readonly type: ValueType;\n /** The type that the position of the document needs, when it needs one. */\n readonly expected?: ValueType;\n}\n\n/** One document that the walk of a check visited, with what the pass of types needs. The package does not export it. */\nexport interface TypeNode {\n readonly visit: DocVisit;\n /** The names that the scope rules of the parent bind for this document. */\n readonly bound: readonly string[];\n /** The type that the shape of the parent declares for this part. */\n readonly expect: ValueType | undefined;\n /** The indices of the parts that the walk visited, in the order of the value. */\n readonly children: number[];\n /** The evaluator name that the ladder gives for the verb of the check. */\n evaluator: string | undefined;\n /** `true` when the check found an issue at this document. Then its type is `unknown`. */\n marked: boolean;\n}\n\n/** The result of the pass of types. */\nexport interface TypePass {\n readonly type: ValueType;\n readonly issues: readonly Issue[];\n readonly places: readonly Typed[];\n}\n\n/** A type that a position needs, and what the position is. */\ninterface Need {\n readonly type: ValueType;\n readonly what: string;\n}\n\n/** The types of the roots that an evaluator can change for its parts. */\ninterface Roots {\n readonly self: ValueType;\n readonly world: ValueType;\n readonly event: ValueType;\n}\n\n/** The roots that can change, as a rule gives them in `PartType.roots`. */\nconst CHANGING = [\"self\", \"world\", \"event\"] as const;\n\n/** The roots of the parts of an evaluator without a rule: such an evaluator can change each root. */\nconst UNKNOWN_ROOTS: Roots = { self: \"unknown\", world: \"unknown\", event: \"unknown\" };\n\n/** One document on the stack of the pass. */\ninterface Frame {\n readonly index: number;\n readonly rule: TypeRule | undefined;\n readonly input: TypeInput;\n readonly order: readonly number[];\n next: number;\n readonly typed: Map<string, ValueType>;\n readonly needs: readonly Need[];\n readonly names: ReadonlyMap<string, ValueType>;\n readonly roots: Roots;\n}\n\nfunction pathKey(path: readonly Key[]): string {\n return JSON.stringify(path.map(String));\n}\n\n/** This function gives the type rule of an evaluator name. A runner hides the evaluator of its name, and a runner has no rule yet (K29). */\nfunction ruleOf(machine: Machine, name: string | undefined): TypeRule | undefined {\n if (name === undefined || (machine.runners !== undefined && Object.hasOwn(machine.runners, name))) return undefined;\n const evaluator = Object.hasOwn(machine.evaluators, name) ? machine.evaluators[name] : undefined;\n const rule = typeof evaluator === \"object\" && evaluator !== null ? (evaluator as { readonly type?: unknown }).type : undefined;\n return typeof rule === \"object\" && rule !== null && typeof (rule as TypeRule).synth === \"function\" ? (rule as TypeRule) : undefined;\n}\n\n/** This function gives the order of the parts of a document: first the parts that give the names of a rule `keysAt`. */\nfunction orderOf(node: TypeNode, nodes: readonly TypeNode[]): readonly number[] {\n const sources = (node.visit.kind?.scope ?? []).flatMap((rule) => (\"keysAt\" in rule.names ? [rule.names.keysAt] : []));\n if (sources.length === 0 || node.children.length < 2) return node.children;\n const gives = (index: number): boolean => {\n const slot = (nodes[index] as TypeNode).visit.slot;\n return sources.some((prefix) => prefix.length <= slot.length && prefix.every((key, at) => String(key) === String(slot[at])));\n };\n return [...node.children.filter(gives), ...node.children.filter((index) => !gives(index))];\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * This function checks the value types of the documents that the walk of a check visited (TYPE.CHECK). The walk gives\n * the documents in the order of the document. The pass uses its own stack, thus a deep document cannot overflow the\n * stack of the host.\n *\n * @param machine - The machine of the check.\n * @param nodes - The documents, in the order of the document. The root is the first.\n * @param verb - The verb of the check. The value types of a contract describe the verb `eval` only.\n * @param expect - The type that the root must have.\n * @param rootTypes - The types of the roots and of the names of the host.\n * @returns The type of the root, the type issues in the order of the document, and the type of each document.\n */\nexport function typePass(machine: Machine, nodes: readonly TypeNode[], verb: string, expect: ValueType | undefined, rootTypes: RootTypes = {}): TypePass {\n if (nodes.length === 0) return { type: \"unknown\", issues: [], places: [] };\n const domains = machine.domains;\n const contracts = verb === \"eval\";\n const found: { readonly index: number; readonly issue: Issue }[] = [];\n const types = new Array<ValueType>(nodes.length);\n const needed = new Array<ValueType | undefined>(nodes.length);\n const seen = new Set<unknown>();\n\n const issueAt = (index: number, problem: TypeProblem): void => {\n const visit = (nodes[index] as TypeNode).visit;\n const issue: Issue = {\n code: \"#TYPE!\",\n place: visit.place,\n reason: problem.reason,\n at: visit.at,\n ...(problem.expected === undefined ? {} : { expected: problem.expected }),\n ...(problem.found === undefined ? {} : { found: problem.found }),\n };\n found.push({ index, issue });\n };\n\n const contract = (index: number, type: unknown, what: string): ValueType => {\n if (!seen.has(type)) {\n seen.add(type);\n const problem = typeIssues(type, domains)[0];\n if (problem !== undefined) issueAt(index, { reason: `The ${what} is not a correct value type. ${problem.reason}` });\n }\n return type as ValueType;\n };\n\n const enter = (index: number, needs: readonly Need[], names: ReadonlyMap<string, ValueType>, roots: Roots): Frame => {\n const node = nodes[index] as TypeNode;\n const visit = node.visit;\n const typed = new Map<string, ValueType>();\n const input: TypeInput = {\n typePath: visit.typePath ?? [],\n doc: visit.doc,\n // The need of the rule of the parent comes last. It is the type that the rule of this document reads.\n expected: needs.length === 0 ? \"unknown\" : (needs[needs.length - 1] as Need).type,\n paths: node.children.map((child) => (nodes[child] as TypeNode).visit.slot),\n address: visit.address === true,\n machine,\n typeOf: (path) => typed.get(pathKey(path)) ?? \"unknown\",\n nameType: (name) => names.get(name),\n rootType: (root) => (root === \"caps\" ? CAPS_TYPE : root === \"self\" || root === \"world\" || root === \"event\" ? roots[root] : \"unknown\"),\n contract: (type, what) => contract(index, type, what),\n };\n return { index, rule: node.marked ? undefined : ruleOf(machine, node.evaluator), input, order: orderOf(node, nodes), next: 0, typed, needs, names, roots };\n };\n\n const ruleFailed = (frame: Frame, error: unknown): void => {\n issueAt(frame.index, { reason: `The type rule of ${(nodes[frame.index] as TypeNode).evaluator ?? \"the evaluator\"} fails: ${message(error)}` });\n };\n\n const report = (frame: Frame, problem: TypeProblem): void => {\n const node = nodes[frame.index] as TypeNode;\n const key = problem.path === undefined ? undefined : pathKey(problem.path);\n const part = key === undefined ? undefined : node.children.find((child) => pathKey((nodes[child] as TypeNode).visit.slot) === key);\n issueAt(part ?? frame.index, problem);\n };\n\n const rootNeeds: Need[] = expect === undefined || isUnknown(contract(0, expect, \"expected type of the check\"), domains) ? [] : [{ type: expect, what: \"document\" }];\n // The check examines each type of the host at the root, one time. A kind that binds a name hides the name of the host.\n const hostNames = new Map<string, ValueType>();\n const given: Readonly<Record<string, ValueType>> = isRecord(rootTypes.names) ? rootTypes.names : {};\n for (const name of Object.keys(given)) hostNames.set(name, contract(0, given[name], `type of the name ${name} of the host`));\n const hostRoot = (root: (typeof CHANGING)[number]): ValueType => (rootTypes[root] === undefined ? \"unknown\" : contract(0, rootTypes[root], `type of the root ${root}`));\n const stack: Frame[] = [enter(0, rootNeeds, hostNames, { self: hostRoot(\"self\"), world: hostRoot(\"world\"), event: hostRoot(\"event\") })];\n while (stack.length > 0) {\n const frame = stack[stack.length - 1] as Frame;\n if (frame.next < frame.order.length) {\n const child = frame.order[frame.next] as number;\n frame.next += 1;\n const node = nodes[child] as TypeNode;\n const slot = node.visit.slot;\n const what = `part ${slot.join(\".\")} of ${typeName((nodes[frame.index] as TypeNode).visit.doc.type)}`;\n let part: PartType = {};\n if (frame.rule?.part !== undefined) {\n try {\n part = frame.rule.part(frame.input, slot) ?? {};\n } catch (error) {\n ruleFailed(frame, error);\n }\n }\n const needs: Need[] = [];\n // A need of the type `unknown` needs nothing, thus the pass leaves it out.\n const need = (type: ValueType, text: string): void => {\n if (!isUnknown(type, domains)) needs.push({ type, what: text });\n };\n if (contracts && node.expect !== undefined) need(contract(child, node.expect, `expected type of the ${what}`), what);\n if (part.expect !== undefined) need(part.expect, part.what ?? what);\n let names = frame.names;\n if (node.bound.length > 0) {\n // Each name that the scope rules bind hides the name around it. A name without a type from the rule gets `unknown`.\n const copy = new Map(names);\n for (const name of node.bound) copy.set(name, part.names !== undefined && Object.hasOwn(part.names, name) ? (part.names[name] as ValueType) : \"unknown\");\n names = copy;\n }\n // No contract tells how an evaluator changes the roots, thus only a rule keeps their types for its parts (TYPE.ROOTS).\n let roots = frame.rule === undefined ? UNKNOWN_ROOTS : frame.roots;\n const changes = part.roots;\n if (typeof changes === \"object\" && changes !== null) {\n const copy: Record<(typeof CHANGING)[number], ValueType> = { ...roots };\n for (const root of CHANGING) if (changes[root] !== undefined) copy[root] = changes[root] as ValueType;\n roots = copy;\n }\n stack.push(enter(child, needs, names, roots));\n continue;\n }\n stack.pop();\n const node = nodes[frame.index] as TypeNode;\n let type: ValueType = \"unknown\";\n if (!node.marked) {\n let synthesized: ValueType = \"unknown\";\n if (frame.rule !== undefined) {\n try {\n synthesized = frame.rule.synth(frame.input, (problem) => report(frame, problem));\n } catch (error) {\n ruleFailed(frame, error);\n }\n }\n const result = contracts ? node.visit.kind?.result : undefined;\n type = result === undefined ? synthesized : contract(frame.index, result, `result of the kind ${typeName(node.visit.doc.type)}`);\n }\n for (const need of frame.needs) {\n if (fits(type, need.type, domains)) continue;\n issueAt(frame.index, { reason: `The ${need.what} has the type ${typeText(type)}. It must have the type ${typeText(need.type)}.`, expected: need.type, found: type });\n // A part with an issue gets the type `unknown`, thus one problem does not give a chain of issues.\n type = \"unknown\";\n break;\n }\n types[frame.index] = type;\n needed[frame.index] = frame.needs.length === 0 ? undefined : (frame.needs[frame.needs.length - 1] as Need).type;\n stack[stack.length - 1]?.typed.set(pathKey(node.visit.slot), type);\n }\n\n const places = nodes.map((node, index) => {\n const want = needed[index];\n const entry = { type: types[index] ?? \"unknown\", ...(want === undefined ? {} : { expected: want }) } as Typed;\n // The keys of a place are made only when a reader asks for them, as a visit does.\n Object.defineProperty(entry, \"place\", { enumerable: true, get: () => node.visit.place });\n Object.defineProperty(entry, \"at\", { enumerable: true, get: () => node.visit.at });\n return entry;\n });\n const issues = found.sort((a, b) => a.index - b.index).map((item) => item.issue);\n return { type: types[0] ?? \"unknown\", issues, places };\n}\n","import { type Envelope, type Json, type Key, isKey, isRecord, typeName } from \"./doc.ts\";\nimport { type Kind, type Namespace, type World, type WorldEntry, effectsOfVerb, equationType, isKind, isNamespace } from \"./world.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type PartSlot, partsOf, scopesOf } from \"./parts.ts\";\nimport { type Cap, type Context, type Root, ROOTS, context, isRef, walkerOf, worldThing } from \"./deref.ts\";\nimport type { ErrorCode } from \"./errors.ts\";\nimport { type Machine, partCaps, permits, waitedReason } from \"./evaluate.ts\";\nimport type { ValueType } from \"./types.ts\";\nimport { type RootTypes, type TypeNode, type Typed, typePass } from \"./typing.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\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> = /* @__PURE__ */ 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 readonly #bound: readonly string[];\n readonly #expect: ValueType | 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 bound: readonly string[],\n expect: ValueType | undefined,\n ) {\n this.#place = place;\n this.#at = at;\n this.#bound = bound;\n this.#expect = expect;\n }\n\n /** The names that the scope rules of the parent bind for this document. The check of types reads them. */\n get bound(): readonly string[] {\n return this.#bound;\n }\n\n /** The type that the shape of the parent declares for this part. The check of types reads it. */\n get expect(): ValueType | undefined {\n return this.#expect;\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 readonly bound: readonly string[];\n readonly expect: ValueType | 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 bound: [],\n expect: undefined,\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 item.bound,\n item.expect,\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 bound: extra,\n expect: slot.expect,\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 /** The type that the position needs, for a type issue (`#TYPE!`). */\n readonly expected?: ValueType;\n /** The type that the check found, for a type issue (`#TYPE!`). */\n readonly found?: ValueType;\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 * The verb that goes up the ladder at each document, as in `prepare`. The default is `eval`. `#NOEVAL` and the hook\n * `known` follow this verb. The type rule of an evaluator serves each verb.\n *\n * The check tests the effects that the contract declares for this verb (VERB.EFFECTS). A kind without a declaration\n * for the verb gives no effect issue. The contract declares the value types of `eval` only, thus only `eval` checks\n * them (VERB.CHECK).\n */\n readonly verb?: string;\n /**\n * With `true`, the check also checks the value types (TYPE.CHECK). It reads the type rules of the evaluators, the\n * signatures of the operations and the value types of the contracts. A type issue has the code `#TYPE!`. The\n * default is `false`, thus a host opts in.\n */\n readonly types?: boolean;\n /** The type that the root document must have, for the check of the value types. */\n readonly expect?: ValueType;\n /**\n * With `true`, the check also finds the problems of a run (RUN.CAN-WAIT). A runner under a parent without a runner\n * gives `#CALC!` when an effect of its runners can reach the host. The parent cannot pass that wait through.\n * A runner without such an effect does not wait, and the run drives it (RUN.DRIVE-NESTED). A kind that declares\n * effects and has no runner gives `#CALC!` too, because in a run only a runner can wait for the host. The default is\n * `false`.\n */\n readonly run?: boolean;\n /**\n * The value types of the roots and of the names of the host, for the check of the value types (TYPE.ROOTS). A\n * reference then gets the type that its path reaches. Only a check with `types: true` reads them.\n */\n readonly rootTypes?: RootTypes;\n}\n\n/** The result of `typeCheck`. */\nexport interface Typing {\n /** The type of the root document. It is `unknown` when the root has an issue. */\n readonly type: ValueType;\n /** Each issue of the check. The type issues come after the other issues. */\n readonly issues: readonly Issue[];\n /** The type of each document, in the order of the document. */\n readonly places: readonly Typed[];\n}\n\n/** The least authority: the capability `[]` permits each effect (CAP.KEYS). */\nconst EACH: readonly Cap[] = /* @__PURE__ */ Object.freeze([[]]);\n\n/** No declared effect. One list serves each visit without effects. */\nconst NO_EFFECTS: readonly (readonly Key[])[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function gives the effects that the contract of the kind of a visit declares for a verb, as keys\n * (FACTS.EFFECTS, VERB.EFFECTS). The text `\"type\"` gives the type of the document after each alias. A visit without a\n * kind declares no effect. `check`, `factsOf` and `effectsOf` read the declarations with this one function (D27).\n *\n * @param v - The visit.\n * @param verb - The verb. The default is `eval`. A kind without a declaration for the verb gives no effect.\n * @returns The keys of each declared effect, in the order of the contract.\n */\nexport function declaredEffects(v: DocVisit, verb = \"eval\"): readonly (readonly Key[])[] {\n return verbDeclared(v, verb) ?? NO_EFFECTS;\n}\n\n/**\n * This function gives the effects that the contract of the kind of a visit declares for a verb, as keys. The result\n * is `undefined` when the contract has no declaration for the verb (D49). A visit without a kind declares no effect\n * for `eval` and no declaration for another verb.\n */\nfunction verbDeclared(v: DocVisit, verb: string): readonly (readonly Key[])[] | undefined {\n if (v.kind === undefined) return verb === \"eval\" ? NO_EFFECTS : undefined;\n const effects = effectsOfVerb(v.kind, verb);\n if (effects === undefined) return undefined;\n if (effects.length === 0) return NO_EFFECTS;\n return effects === \"type\" ? [v.typePath ?? []] : effects.map((kind) => kind.split(\".\"));\n}\n\n/**\n * This function gives the rule of a machine for an effect, for the static kit (CAP.PERMITS). The rule is the hook\n * `permits` of the machine, as in a run, or else the function `permits`. A check has no values, thus the hook gets a\n * context with the capabilities of the document and the world of the machine. Its names, its self and its event are\n * empty.\n *\n * @param machine - The machine.\n * @returns The rule. It gets the capabilities of a document and the keys of an effect.\n */\nexport function permitsOf(machine: Machine): (caps: readonly Cap[], kind: readonly Key[]) => boolean {\n const hook = machine.permits;\n if (hook === undefined) return permits;\n let base: Context | undefined;\n return (caps, kind) => hook(caps, kind, { ...(base ??= context({ world: worldThing(machine.world) })), caps });\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[], allowed: (caps: readonly Cap[], kind: readonly Key[]) => boolean): string {\n const text = kind.join(\".\");\n for (let up = v.parent; up !== undefined; up = up.parent) {\n if (up.caps !== undefined && allowed(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 * The hook `permits` of the machine decides, as in a run (CAP.PERMITS).\n * - `#CALC!`: with the option `run`, a runner under a parent without a runner, when an effect of its runners can reach\n * the host. Also a kind that declares effects and has no runner (RUN.CAN-WAIT). The issue has the place and the\n * reason of the run.\n * - `#TYPE!`: with the option `types`, a part whose type does not fit the type that its position needs (TYPE.CHECK).\n * A run does not always fail there, thus a type issue is a static finding, not an error of a run.\n *\n * The check asks the ladder for the verb of the options, `eval` by default (VERB.CHECK). The shapes, the paths and the\n * names follow the contracts, thus they are the same for each verb. The check tests the effects that each contract\n * declares for the verb: `effects` for `eval`, and the entry of `verbEffects` for another verb (VERB.EFFECTS). A kind\n * without a declaration for the verb gives no `#CAP!` and no `#CALC!` for an effect.\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, the capabilities, the verb, the types and the run.\n * @returns The problems, in the order of the document. The type issues come after the other issues.\n */\nexport function check(machine: Machine, doc: unknown, options: CheckOptions = {}): readonly Issue[] {\n return options.types === true ? typeCheck(machine, doc, options).issues : checkAll(machine, doc, options, undefined);\n}\n\n/**\n * This function checks a document, and it also checks the value types (TYPE.CHECK, D25). It finds each issue of\n * `check`. Then it synthesizes the type of each document from the types of its parts. It also checks each part\n * against the type that its position needs. The type rule of the parent, the signature of an operation or the shape\n * of the contract gives that type. A part with an issue gets the type `unknown`, thus one\n * problem does not give a chain of issues.\n *\n * A type issue has the code `#TYPE!`, the type that the position needs (`expected`) and the type that the check found\n * (`found`). It is a static finding: the evaluation of the document does not change.\n *\n * The option `rootTypes` gives the types of the roots and of the names of the host (TYPE.ROOTS). A reference then gets\n * the type that its path reaches, and a field that a closed record does not have is a type issue (TYPE.CLOSED).\n *\n * @param machine - The world and the code of the evaluators, with their type rules.\n * @param doc - The document, as JSON.\n * @param options - The options of `check`, the type that the root must have and the types of the roots.\n * @returns The type of the root, each issue, and the type of each document.\n */\nexport function typeCheck(machine: Machine, doc: unknown, options: CheckOptions = {}): Typing {\n const nodes: TypeNode[] = [];\n const issues = checkAll(machine, doc, options, nodes);\n const pass = typePass(machine, nodes, options.verb ?? \"eval\", options.expect, options.rootTypes);\n return { type: pass.type, issues: pass.issues.length === 0 ? issues : [...issues, ...pass.issues], places: pass.places };\n}\n\n/**\n * A problem of a world that `checkWorld` finds before a document exists (STATIC.COVERAGE). Each document of the\n * kind gives this problem for the verb, thus `check` with the verb finds it too.\n */\nexport interface WorldIssue {\n /** The code of the problem. `#NOEVAL`: no rung of the ladder gives an evaluator for the verb. */\n readonly code: \"#NOEVAL\";\n /** The keys of the kind from the root of the world. For a fallback kind, the keys of its namespace. */\n readonly kind: readonly Key[];\n /** `true` for the fallback kind of a namespace or of the world. */\n readonly fallback?: true;\n /** The verb without an evaluator. */\n readonly verb: string;\n readonly reason: string;\n}\n\n/** This function tells if a table of verbs has an entry for a verb. */\nfunction hasVerb(table: Readonly<Record<string, string>> | undefined, verb: string): boolean {\n return table !== undefined && Object.hasOwn(table, verb);\n}\n\n/**\n * This function checks the world of a machine before a document exists. It finds each kind that has no entry for a\n * verb of the list, when the world has no default for that verb (STATIC.COVERAGE). A document of such a kind gets no\n * evaluator for the verb, thus the check gives the same proof of coverage as a type system.\n *\n * The check visits each kind of each namespace, at each depth, and the fallback kind of each namespace and of the\n * world. It does not follow an alias, because the kind of an alias has its own place. The check reads only the world.\n *\n * @param machine - The machine, for its world.\n * @param verbs - The verbs that each kind of the language must answer, for example `eval`, `view` and `type`.\n * @returns One issue for each kind and verb without an evaluator. The order is the order of the world, then the\n * order of the verbs. The fallback kind of a namespace comes after the entries of that namespace.\n */\nexport function checkWorld(machine: Machine, verbs: readonly string[]): readonly WorldIssue[] {\n const world = machine.world;\n const open = verbs.filter((verb) => !hasVerb(world.defaults, verb));\n const out: WorldIssue[] = [];\n if (open.length === 0) return out;\n const visit = (kind: Kind, path: readonly Key[], fallback: boolean): void => {\n const text = path.join(\".\");\n const name = fallback ? (path.length === 0 ? \"the fallback kind of the world\" : `the fallback kind of ${text}`) : `the kind ${text}`;\n for (const verb of open) {\n if (hasVerb(kind.verbs, verb)) continue;\n const reason = `${name.charAt(0).toUpperCase()}${name.slice(1)} has no entry for the verb ${verb}, and the world has no default for it.`;\n out.push(fallback ? { code: \"#NOEVAL\", kind: path, fallback: true, verb, reason } : { code: \"#NOEVAL\", kind: path, verb, reason });\n }\n };\n // The set holds the namespaces on the way, thus a namespace that holds itself does not loop.\n const way = new Set<Namespace>();\n const entries = (kinds: Readonly<Record<string, WorldEntry>>, path: readonly Key[]): void => {\n for (const key of Object.keys(kinds)) {\n const entry = kinds[key];\n const here = [...path, key];\n if (isKind(entry)) visit(entry, here, false);\n else if (isNamespace(entry) && !way.has(entry)) {\n way.add(entry);\n entries(entry.kinds, here);\n if (entry.fallback !== undefined) visit(entry.fallback, here, true);\n way.delete(entry);\n }\n }\n };\n entries(world.kinds, []);\n if (world.fallback !== undefined) visit(world.fallback, [], true);\n return out;\n}\n\n/**\n * A runner under an evaluator in a check of a run. The run drives its steps without a wait, thus only a wait for an\n * effect of its runners fails (RUN.DRIVE-NESTED).\n */\ninterface Drive {\n /** The issue of the run when a step waits. */\n readonly issue: Issue;\n /** The index of the issue in the order of the document. */\n readonly index: number;\n /** The node of the runner for the pass of types. */\n readonly node: TypeNode | undefined;\n /** `true` when an effect of its runners can reach the host, and thus wait. */\n wait: boolean;\n}\n\n/** What the code of a document does with a wait: an evaluator stops it, and a runner passes it on. */\ntype Waits = boolean | Drive;\n\n/** The names that an equation of `down` sees (TREE.DOWN). */\nconst DOWN_NAMES: readonly string[] = /* @__PURE__ */ Object.freeze([\"child\", \"index\", \"prev\"]);\n\n/** The names that the term `combine` of a fold sees (TREE.FOLD). */\nconst FOLD_NAMES: readonly string[] = /* @__PURE__ */ Object.freeze([\"acc\", \"item\"]);\n\n/**\n * This function gives each equation of the tree contract of a kind, with the names that it sees (D42). An equation of\n * `equations`, a `unit` and a `default` see no names.\n */\nfunction equationsOf(kind: Kind): readonly { readonly label: string; readonly term: Json; readonly names: readonly string[] }[] {\n const tree = kind.tree;\n if (tree === undefined) return [];\n const out: { readonly label: string; readonly term: Json; readonly names: readonly string[] }[] = [];\n for (const [name, term] of Object.entries(tree.equations ?? {})) out.push({ label: `tree.equations.${name}`, term, names: [] });\n for (const [name, term] of Object.entries(tree.down ?? {})) out.push({ label: `tree.down.${name}`, term, names: DOWN_NAMES });\n for (const [name, declared] of Object.entries(tree.attributes ?? {})) {\n if (declared.fold !== undefined) {\n out.push({ label: `tree.attributes.${name}.fold.unit`, term: declared.fold.unit, names: [] });\n out.push({ label: `tree.attributes.${name}.fold.combine`, term: declared.fold.combine, names: FOLD_NAMES });\n }\n if (declared.default !== undefined) out.push({ label: `tree.attributes.${name}.default`, term: declared.default, names: [] });\n }\n return out;\n}\n\n/**\n * This function checks the equations of the tree contract of a kind, each with the names of its rung (TREE.DOWN-NAMES).\n * An equation evaluates without capabilities, thus a check with capabilities gives it none. Each issue gets the place\n * of the document of the kind, and its reason names the equation.\n */\nfunction equationIssues(machine: Machine, kind: Kind, kindText: string, options: CheckOptions, seen: Set<Kind>): readonly Issue[] {\n const of = equationType(kind);\n const out: Issue[] = [];\n for (const { label, term, names } of equationsOf(kind)) {\n const inner: CheckOptions = { names, ...(of === undefined ? {} : { declaredType: of }), ...(options.caps === undefined ? {} : { caps: [] }) };\n for (const issue of checkAll(machine, term, inner, undefined, seen)) {\n out.push({ code: issue.code, place: [], reason: `In the equation ${label} of the kind ${kindText}: ${issue.reason}` });\n }\n }\n return out;\n}\n\n/**\n * This function finds the issues of `check`. With a list of nodes, it also records each document that it visits for\n * the pass of types. It marks each document with an issue. The set `seen` holds the kinds whose equations the check\n * walked, thus it walks the equations of each kind one time.\n */\nfunction checkAll(machine: Machine, doc: unknown, options: CheckOptions, nodes: TypeNode[] | undefined, seen: Set<Kind> = new Set()): readonly Issue[] {\n const issues: Issue[] = [];\n const verb = options.verb ?? \"eval\";\n const indices = nodes === undefined ? undefined : new Map<DocVisit, number>();\n let current: TypeNode | undefined;\n const push = (issue: Issue): void => {\n issues.push(issue);\n if (current !== undefined) current.marked = true;\n };\n // The field effects declares eval, and verbEffects declares the other verbs (VERB.EFFECTS). An effect of a verb\n // without a declaration meets its test when it happens (RUN.CAP).\n const allowed = options.caps === undefined ? undefined : permitsOf(machine);\n // In a run, a part that can wait needs a parent that can wait (RUN.CAN-WAIT). The map tells for each document with\n // code if its code passes a wait on: false for an evaluator, true for a runner whose waits reach the driver of the\n // run, and a drive for a runner under an evaluator. A document without code fails before its parts, thus it is not\n // in the map.\n const waits = options.run === true ? new Map<DocVisit, Waits>() : undefined;\n const drives: Drive[] = [];\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 (nodes !== undefined && indices !== undefined) {\n current = { visit: v, bound: v instanceof Visit ? v.bound : [], expect: v instanceof Visit ? v.expect : undefined, children: [], evaluator: undefined, marked: false };\n const parent = v.parent === undefined ? undefined : indices.get(v.parent);\n if (parent !== undefined) nodes[parent]?.children.push(nodes.length);\n indices.set(v, nodes.length);\n nodes.push(current);\n }\n if (v.depth > maxDepth) {\n 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, verb, v.declared ? { declaredType: typeName(v.doc.type) } : {});\n if (answer.error === \"unknown-kind\") {\n push({ code: \"#KIND?\", place: v.place, reason: `The world has no kind ${typeName(v.doc.type)}.`, at: v.at });\n return \"skip\";\n }\n // The equations of a kind are code of the kind. The check walks them at the first document of the kind (D42).\n if (v.kind?.tree !== undefined && !seen.has(v.kind)) {\n seen.add(v.kind);\n for (const issue of equationIssues(machine, v.kind, typeName(v.doc.type), options, seen)) push({ ...issue, place: v.place, at: v.at });\n }\n const name = answer.evaluator;\n if (current !== undefined) current.evaluator = name;\n // A runner hides the evaluator of its name (MACHINE.RUNNER), as in the compilation of a plan.\n const runner = name !== undefined && has(machine.runners, name);\n const coded = name !== undefined && (runner || has(machine.evaluators, name));\n if (name === undefined || !coded) {\n 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) push({ code: \"#NAME?\", place: v.place, reason: known, at: v.at });\n }\n const caps = v.caps;\n const stated = verbDeclared(v, verb);\n const declared = stated ?? NO_EFFECTS;\n if (allowed !== undefined && caps !== undefined) {\n for (const kind of declared) {\n if (!allowed(caps, kind)) push({ code: \"#CAP!\", place: v.place, reason: capReason(v, kind, allowed), at: v.at });\n }\n }\n if (waits !== undefined && coded) {\n // The parent of the root is the driver of the run, and it can wait. An evaluator gives its parts no wait.\n const up = v.parent === undefined ? true : waits.get(v.parent);\n let chain: Waits = false;\n if (runner && up === false) {\n // The run drives a runner under an evaluator, and only a real wait fails (RUN.DRIVE-NESTED). Its issue goes in\n // here, in the order of the document, when an effect of its runners can wait.\n const issue: Issue = { code: \"#CALC!\", place: v.place, reason: waitedReason(typeName(v.doc.type)), at: v.at };\n chain = { issue, index: issues.length, node: current, wait: false };\n drives.push(chain);\n } else if (runner) {\n chain = up ?? true;\n }\n waits.set(v, chain);\n // A runner waits only for an effect that reaches the host (C6). A refused effect gives #CAP! without a wait. A\n // runner without a declaration for the verb can cause each effect, thus it can wait.\n if (typeof chain === \"object\" && !chain.wait) {\n const rule = allowed ?? permits;\n chain.wait = stated === undefined || declared.some((kind) => caps === undefined || rule(caps, kind));\n }\n // In a run, the host does each effect, thus an evaluator cannot cause one.\n const first = declared[0];\n if (!runner && first !== undefined) {\n push({ code: \"#CALC!\", place: v.place, reason: `The effect ${first.join(\".\")} needs a runner: in a run, the host does each effect.`, at: v.at });\n }\n }\n const isPath = isRef(v.doc);\n if (!isPath && v.typePath?.length === 1 && v.typePath[0] === \"ref\") {\n 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 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 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 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 // The resolution finds the walker with the same function, thus the check and a run agree (VERB.LADDER).\n if (walkerOf(machine, step) === undefined) {\n 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 // Without capabilities, a check of the run narrows the least authority, as effectsOf does. Thus a mask of a kind\n // removes the effects that cannot wait. The check of the capabilities stays off.\n ...(options.caps === undefined ? (waits === undefined ? {} : { caps: EACH }) : { caps: options.caps }),\n problem: (problem) => {\n issues.push({ code: problem.code, place: problem.place, reason: problem.reason, at: problem.at });\n // A value without the shape of its kind is a problem of the document that the walk visited last. A part that is\n // not a document has no visit, thus it marks nothing.\n if (problem.code === \"#VALUE!\" && current !== undefined) current.marked = true;\n },\n },\n );\n // The issue of each drive that can wait goes in at its place. The last drive goes in first, thus each index stays.\n for (let index = drives.length - 1; index >= 0; index -= 1) {\n const drive = drives[index] as Drive;\n if (!drive.wait) continue;\n issues.splice(drive.index, 0, drive.issue);\n if (drive.node !== undefined) drive.node.marked = true;\n }\n return issues;\n}\n","import { type Json, type Key, isEnvelope, isKey } from \"./doc.ts\";\nimport { type Kind, type LazyRule, type Side, type World, lookupKind } from \"./world.ts\";\nimport { answerOf } from \"./ladder.ts\";\nimport { pathMatches, splitParts } from \"./parts.ts\";\nimport { type Root, ROOTS, isRef } from \"./deref.ts\";\nimport type { Machine } from \"./evaluate.ts\";\nimport { type DocVisit, declaredEffects, walk } from \"./static.ts\";\n\n/**\n * One read of a document: a free reference, with its marks (FACTS.READS). A plan resolves the path of the reference\n * when it evaluates the reference. The static read covers each path that the plan resolves there (FACTS.SOUND). A\n * root that a kind declares in `reads` is a read too, with the path of the root alone.\n */\nexport interface StaticRead {\n /** The root of the path. */\n readonly root: Root;\n /** The keys after the root, up to the first step that is not a key. */\n readonly keys: readonly Key[];\n /**\n * `true` when each step after the root is a key. Then the plan resolves this path and no other. A step document,\n * for example `nearest`, makes it `false`: the plan resolves a path that starts with the keys.\n */\n readonly exact: boolean;\n /** `true` when only a lazy part reaches the reference. An evaluation can then give a value without this read (FACTS.LAZY). */\n readonly lazy: boolean;\n /** `true` when the position of the reference declares an address. The read gives what the path reaches, not its value. */\n readonly address: boolean;\n /** The path of the reference: its root and its steps. */\n readonly path: readonly Json[];\n /** The keys from the root document to 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}\n\n/** The static facts of one document (D24). They depend only on the document and the machine, not on a context. */\nexport interface DocFacts {\n /**\n * The free references, in the order of the document (FACTS.READS). A reference to a name that a kind binds is not\n * here. The roots that a kind declares in `reads` are here too, each one at the place of its document.\n */\n readonly reads: readonly StaticRead[];\n /** `\"run\"` when one kind of the document is on the run side (FACTS.SIDE). */\n readonly side: Side;\n /** The kinds of the effects that the contracts declare, as texts with dots, each one time (FACTS.EFFECTS). */\n readonly effects: readonly string[];\n /**\n * `true` when each kind of the document declares `pure`, and the document has no effect and is not volatile. Then\n * its result depends only on what its reads give (FACTS.PURE).\n */\n readonly pure: boolean;\n /** `true` when the result can change while each read gives the same thing, for example with a clock (FACTS.VOLATILE). */\n readonly volatile: boolean;\n /** The number of documents in the document: a hint of the cost of an evaluation. */\n readonly size: number;\n}\n\n/** The options of `factsOf`. */\nexport interface FactsOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The verb whose evaluators the facts describe, as in `prepare`. The default is `eval`. The contract of a kind\n * describes the code of `eval` only. For another verb, only the hook `facts` describes the code (FACTS.VERB).\n */\n readonly verb?: string;\n /**\n * This function tells if a read reaches a volatile value of the host, for example a function that reads a clock.\n * A read that it marks makes the document volatile (FACTS.VOLATILE).\n *\n * @param read - The read.\n * @returns `true` when the read reaches a volatile value.\n */\n readonly volatile?: (read: StaticRead) => boolean;\n}\n\n/** The lazy rules that cover each part: the rules of a document whose evaluator the contract does not describe. */\nconst EACH = \"each\";\n\n/** An empty list. One frozen list serves each empty list of the facts, thus a store of many facts keeps less (PLAN.LEAN). */\nconst NONE: readonly never[] = /* @__PURE__ */ Object.freeze([]);\n\n/**\n * This function gives a list of the facts with no free room. A list that grows by `push` keeps room for more items,\n * thus a copy of a short list is smaller.\n */\nfunction tight<T>(list: readonly T[]): readonly T[] {\n return list.length === 0 ? NONE : list.slice();\n}\n\n/** What a document gives to its parts: its own lazy mark, and the lazy rules of its kind for the parts. */\ninterface Above {\n readonly lazy: boolean;\n readonly rules: readonly LazyRule[] | typeof EACH | undefined;\n /** The position of each part among the parts that a rule `after` covers. It is made at the first need. */\n positions?: Map<LazyRule, Map<string, number>>;\n}\n\n/**\n * This function gives the name of the evaluator that the ladder finds for a verb (VERB.LADDER). It also tells if\n * the contract of the kind describes that code. The contract describes the code of its kind for its verb `contract`.\n * An own entry for another evaluator has code that the contract does not describe.\n */\nfunction codeOf(\n world: World,\n own: Readonly<Record<string, string>> | undefined,\n kind: Kind,\n verb: string,\n contract: string,\n): { readonly name: string | undefined; readonly described: boolean } {\n const found = answerOf(world, own, kind, verb);\n if (verb !== contract) return { name: found?.name, described: false };\n if (found?.rung !== \"own\") return { name: found?.name, described: true };\n return { name: found.name, described: found.name === answerOf(world, undefined, kind, verb)?.name };\n}\n\n/** This function gives the position of a part among the parts that a rule covers, by the split of its document. */\nfunction positionOf(above: Above, parent: DocVisit, rule: LazyRule, slot: readonly Key[]): number {\n const positions = (above.positions ??= new Map());\n let table = positions.get(rule);\n if (table === undefined) {\n table = new Map();\n const split = splitParts(parent.kind?.parts, parent.doc.value);\n let count = 0;\n for (const part of split.ok ? split.parts : []) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(part.path, pattern))) continue;\n table.set(JSON.stringify(part.path), count);\n count += 1;\n }\n positions.set(rule, table);\n }\n return table.get(JSON.stringify(slot)) ?? 0;\n}\n\n/** This function tells if the lazy rules of a document cover one of its parts. */\nfunction partLazy(above: Above, parent: DocVisit, slot: readonly Key[]): boolean {\n const rules = above.rules;\n if (rules === undefined) return false;\n if (rules === EACH) return true;\n for (const rule of rules) {\n if (rule.in !== undefined && !rule.in.some((pattern) => pathMatches(slot, pattern))) continue;\n const after = rule.after ?? 0;\n if (after <= 0 || positionOf(above, parent, rule, slot) >= after) return true;\n }\n return false;\n}\n\n/**\n * This function gives the static facts of a document, for a schedule (R4 P2, D24). It walks the document one time,\n * by the contracts of its kinds:\n *\n * - `reads`: each free reference, with the root and the keys of its path. A read under a lazy part has the mark\n * `lazy`, for example a read in a branch of `if`. A read after a step document has `exact: false`. A kind that\n * declares `reads` adds a read of each of its roots at each document of the kind.\n * - `side` and `effects`: from the contract of each kind.\n * - `pure`: each kind declares `pure`, and the document has no effect and is not volatile.\n * - `volatile`: a kind, an operation or a step document declares `volatile`, or the host marks a read.\n *\n * The hook `facts` of the machine answers for a name that a fallback kind covers, for example an operation. Its\n * answer wins over the contract of the kind. The contract of a kind does not describe the evaluator of an own\n * entry. Thus a document with an own entry for another evaluator is not pure, and each of its parts is lazy. The\n * hook can still answer for that evaluator.\n *\n * The option `verb` names the verb whose code the facts describe (FACTS.VERB). A contract describes the code of\n * `eval`, thus the rule of an own entry applies to each document for another verb. The side and the effects come\n * from the contracts for each verb.\n *\n * A read is one resolution of its path. A reference that the resolution reaches and follows is a part of that read\n * (DEREF.COLLAPSE), not a separate read. The facts depend only on the document and the machine. Thus a host computes\n * them again only after an edit of the document or of the machine.\n *\n * @param machine - The world, the code and the hook `facts`.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value, the verb and the volatile reads of the host.\n * @returns The facts.\n */\nexport function factsOf(machine: Machine, doc: unknown, options: FactsOptions = {}): DocFacts {\n const world = machine.world;\n const hook = machine.facts;\n const verb = options.verb ?? \"eval\";\n const reads: StaticRead[] = [];\n const effects: string[] = [];\n const above = new Map<DocVisit, Above>();\n let side: Side = \"derive\";\n let pure = true;\n let volatile = false;\n let size = 0;\n const note = (isPure: boolean | undefined, isVolatile: boolean | undefined): void => {\n if (isPure !== true) pure = false;\n if (isVolatile === true) volatile = true;\n };\n walk(\n world,\n doc,\n (v) => {\n size += 1;\n const up = v.parent === undefined ? undefined : above.get(v.parent);\n const lazy = up !== undefined && v.parent !== undefined && (up.lazy || partLazy(up, v.parent, v.slot));\n const kind = v.kind;\n if (kind === undefined) {\n // A kind that the world does not have gives #KIND?, and the walk does not visit its value.\n pure = false;\n above.set(v, { lazy, rules: undefined });\n return undefined;\n }\n const code = codeOf(world, v.declared ? undefined : v.doc.own, kind, verb, \"eval\");\n const answer = code.name === undefined ? undefined : hook?.(v.typePath ?? [], code.name);\n let roots: readonly Root[] | undefined;\n if (code.described) {\n note(answer?.pure ?? kind.pure, answer?.volatile ?? kind.volatile);\n above.set(v, { lazy, rules: answer?.lazy ?? kind.lazy });\n roots = answer?.reads ?? kind.reads;\n } else {\n // The contract of the kind does not describe this code. Only the hook can.\n note(answer?.pure, answer?.volatile);\n above.set(v, { lazy, rules: answer?.lazy ?? EACH });\n roots = answer?.reads;\n }\n // The code of the kind resolves each of these roots as a whole, at the place of its document (FACTS.KIND-READS).\n for (const root of roots ?? NONE) {\n const read: StaticRead = { root, keys: NONE, exact: true, lazy, address: false, path: [root], place: tight(v.place), at: tight(v.at) };\n reads.push(read);\n if (options.volatile?.(read) === true) volatile = true;\n }\n if (kind.side === \"run\") side = \"run\";\n // check and effectsOf read the declared effects with the same function (D27).\n for (const keys of declaredEffects(v)) {\n const text = keys.join(\".\");\n if (!effects.includes(text)) effects.push(text);\n }\n if (!isRef(v.doc)) return undefined;\n const path = v.doc.value;\n const root = path[0];\n if (typeof root !== \"string\" || !(ROOTS as readonly string[]).includes(root)) return undefined;\n let exact = true;\n const keys: Key[] = [];\n for (let index = 1; index < path.length; index += 1) {\n const step = path[index];\n if (exact && isKey(step)) {\n keys.push(step);\n continue;\n }\n exact = false;\n // A step document runs the walker that the ladder finds for the verb step.\n const found = isEnvelope(step) ? lookupKind(world, step.type) : undefined;\n if (found?.ok !== true) {\n pure = false;\n continue;\n }\n const walker = codeOf(world, (step as { readonly own?: Readonly<Record<string, string>> }).own, found.kind, \"step\", \"step\");\n const stepAnswer = walker.name === undefined ? undefined : hook?.(found.path, walker.name);\n if (walker.described) note(stepAnswer?.pure ?? found.kind.pure, stepAnswer?.volatile ?? found.kind.volatile);\n else note(stepAnswer?.pure, stepAnswer?.volatile);\n }\n const first = path[1];\n // A reference to a name that a kind around it binds reads inside the document: it is not a read.\n if (root === \"names\" && isKey(first) && v.names.has(String(first))) return undefined;\n const read: StaticRead = { root: root as Root, keys: tight(keys), exact, lazy, address: v.address === true, path, place: tight(v.place), at: tight(v.at) };\n reads.push(read);\n if (options.volatile?.(read) === true) volatile = true;\n return undefined;\n },\n options.declaredType === undefined ? {} : { declaredType: options.declaredType },\n );\n return { reads: tight(reads), side, effects: tight(effects), pure: pure && !volatile && effects.length === 0 && side === \"derive\", volatile, size };\n}\n","import type { Key } from \"./doc.ts\";\nimport type { Cap } from \"./deref.ts\";\nimport { type Machine, capKeys, permits } from \"./evaluate.ts\";\nimport { type DocVisit, type Issue, declaredEffects, permitsOf, walk } from \"./static.ts\";\n\n/*\n * The effects that reach the host (R2 P3, D27). The contract of each kind declares the effects of its documents, and\n * its capability rules narrow the capabilities of its parts (D14). One walk narrows the capabilities as a run does. An\n * effect that the capabilities of its document do not permit fails in the run, thus it does not reach the host.\n *\n * A procedure value keeps the capabilities of the document that made it, as the closure of `fn` does. Thus its latent\n * effects are the effects of its body, under the capabilities of the body, and the fold needs no effect variables.\n */\n\n/** The options of `effectsOf`. */\nexport interface EffectsOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The capabilities at the root. With them, the result keeps only the effects that the rule of the machine permits at\n * their documents, as a run does (CAP.PERMITS). Without them, the root has each capability, and only the capability\n * rules of the kinds remove an effect.\n */\n readonly caps?: readonly Cap[];\n}\n\n/** Each capability: one capability with no keys. It permits each effect, because each kind starts with no keys (CAP.KEYS). */\nconst EACH: readonly Cap[] = /* @__PURE__ */ Object.freeze([[]]);\n\n/** One declared effect that can reach the host: its keys and the visit of its document. */\ninterface Reaching {\n readonly kind: readonly Key[];\n readonly visit: DocVisit;\n}\n\n/**\n * This function finds each declared effect that can reach the host, in the order of the document. It is the one\n * inference of `effectsOf` and `checkLatent`. `check` and `factsOf` read the same declarations (`declaredEffects`).\n */\nfunction reaching(machine: Machine, doc: unknown, options: EffectsOptions): readonly Reaching[] {\n const out: Reaching[] = [];\n // Without capabilities, the host has no rule to ask. The capability rules of the kinds still narrow each capability.\n const rule = options.caps === undefined ? permits : permitsOf(machine);\n walk(\n machine.world,\n doc,\n (v) => {\n const caps = v.caps ?? EACH;\n for (const kind of declaredEffects(v)) if (rule(caps, kind)) out.push({ kind, visit: v });\n return undefined;\n },\n { caps: options.caps ?? EACH, ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }) },\n );\n return out;\n}\n\n/**\n * This function gives the effects of a document that can reach the host (CAP.EFFECTS-OF, R2 P3). The result is the\n * effects that the contract of each kind declares, without the effects that the capability rules around them remove.\n * A rule `mask` removes each effect of its parts, and a rule `only` removes each effect outside its list.\n *\n * Without capabilities in the options, the result is the least authority of the document. A host that grants these\n * kinds as capabilities grants each effect that a run of the document can give it. With capabilities, the result keeps\n * only the effects that the rule of the machine permits at their documents.\n *\n * The result covers each effect that an evaluation or a run gives the host (CAP.EFFECTS-SOUND). A procedure value keeps\n * the capabilities of the document that made it, thus the effects of its body count at the body (CAP.LATENT). The\n * contract describes the code of its kind. The code of an own entry for another evaluator is outside the result.\n *\n * @param machine - The world and its contracts, and the hook `permits`.\n * @param doc - The document, as JSON.\n * @param options - The type of a bare root value and the capabilities at the root.\n * @returns The kinds of the effects, as texts with dots, each one time, in the order of the document.\n */\nexport function effectsOf(machine: Machine, doc: unknown, options: EffectsOptions = {}): readonly string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const { kind } of reaching(machine, doc, options)) {\n const text = kind.join(\".\");\n if (seen.has(text)) continue;\n seen.add(text);\n out.push(text);\n }\n return out;\n}\n\n/**\n * This function compares the latent effects that a procedure declares with the body of the procedure (CAP.LATENT). A\n * procedure entry is a kind whose code evaluates the document of a procedure. Its field `effects` declares the latent\n * effects: the effects that a call of the procedure can cause. `check` tests each call against this declaration.\n *\n * The function gives a `#CAP!` for each effect of the body that can reach the host and that the declaration does not\n * permit. An effect that a kind in the body masks fails in the body, thus it is not a latent effect.\n *\n * @param machine - The world and its contracts.\n * @param declared - The latent effects that the procedure declares, for example the field `effects` of its kind.\n * @param body - The document of the procedure, as JSON.\n * @param options - The type of a bare root value.\n * @returns The issues, in the order of the body.\n */\nexport function checkLatent(machine: Machine, declared: readonly Cap[], body: unknown, options: Omit<EffectsOptions, \"caps\"> = {}): readonly Issue[] {\n const issues: Issue[] = [];\n const list = declared.map((cap) => capKeys(cap).join(\".\")).join(\", \");\n const head = declared.length === 0 ? \"The procedure declares no latent effect\" : `The procedure declares the latent effects ${list}`;\n for (const { kind, visit } of reaching(machine, body, options.declaredType === undefined ? {} : { declaredType: options.declaredType })) {\n if (permits(declared, kind)) continue;\n issues.push({ code: \"#CAP!\", place: visit.place, reason: `${head}, and its body can cause the effect ${kind.join(\".\")} here.`, at: visit.at });\n }\n return issues;\n}\n","import { type Json, isEnvelope, isRecord } from \"./doc.ts\";\nimport { type Result, describe, fail, ok } from \"./errors.ts\";\nimport { type Machine, makeContext, prepare } from \"./evaluate.ts\";\nimport { type Domain, type DomainCodec, domainOf, member } from \"./types.ts\";\n\n/*\n * The codec of the values that JSON cannot write (K140, D40). A document holds such a value as a standard extension:\n * `ext.number` for `NaN`, an infinity and `-0`, `ext.undefined` for `undefined`, and `ext.domain` for a member of a\n * domain with a codec. Thus the same value has the same document in each language (D12).\n */\n\n/** The domains of a machine, by their names. */\ntype Domains = Readonly<Record<string, Domain>> | undefined;\n\n/** This function gives the codec of a domain, or `undefined` when the domain has no codec. */\nfunction codecOf(domain: Domain): DomainCodec | undefined {\n const codec: unknown = domain.codec;\n if (typeof codec !== \"object\" || codec === null) return undefined;\n const { encode, decode } = codec as Partial<DomainCodec>;\n return typeof encode === \"function\" && typeof decode === \"function\" ? (codec as DomainCodec) : undefined;\n}\n\n/**\n * This function reads the value of an extension `ext.domain` (EXT.DOMAIN). The value is a record with only the text\n * `domain` and the JSON `data`. The codec of the named domain reads the data, and the result must be a member of the\n * domain.\n *\n * @param data - The value of the extension document.\n * @param domains - The domains of the machine.\n * @returns The member, `#NAME?` for a domain without a codec, or `#VALUE!` for data that the codec cannot read.\n */\nexport function decodeDomain(data: Json, domains: Domains): Result {\n if (!isRecord(data) || typeof data[\"domain\"] !== \"string\" || !Object.hasOwn(data, \"data\") || Object.keys(data).length !== 2) {\n return fail(\"#VALUE!\", \"The value of ext.domain is a record with only the text domain and the data.\");\n }\n const name = data[\"domain\"];\n const domain = domainOf(name, domains);\n if (domain === undefined) return fail(\"#NAME?\", `The machine has no domain ${name}.`);\n const codec = codecOf(domain);\n if (codec === undefined) return fail(\"#NAME?\", `The domain ${name} has no codec.`);\n let value: unknown;\n try {\n value = codec.decode(data[\"data\"] as Json);\n } catch (error) {\n return fail(\"#VALUE!\", `The codec of the domain ${name} cannot read the data: ${describe(error)}`, { cause: error });\n }\n if (!member(value, name, domains)) return fail(\"#VALUE!\", `The codec of the domain ${name} gives a value that is not a member of the domain.`);\n return ok(value);\n}\n\n/**\n * This function gives the static type of an extension `ext.domain`: the name of its domain when that domain has a\n * codec. A run then gives a member of the domain or an error, because `decodeDomain` tests the membership.\n *\n * @param data - The value of the extension document.\n * @param domains - The domains of the machine.\n * @returns The name of the domain, or `unknown`.\n */\nexport function domainTypeOf(data: unknown, domains: Domains): string {\n if (!isRecord(data) || typeof data[\"domain\"] !== \"string\") return \"unknown\";\n const domain = domainOf(data[\"domain\"], domains);\n return domain !== undefined && codecOf(domain) !== undefined ? data[\"domain\"] : \"unknown\";\n}\n\n/** This function sets an own data property. Only the key `__proto__` needs `defineProperty`. */\nfunction setOwn(target: Record<string, Json>, key: string, value: Json): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\n/** The state of one call of `encodeValue`. */\ninterface Encoder {\n readonly domains: Domains;\n /** The domains with a codec, in the order of their names. */\n readonly codecs: readonly (readonly [string, DomainCodec])[];\n /** The answer of `isJson` for each container that it examined. */\n readonly json: WeakMap<object, boolean>;\n /** The containers on the way from the root to the value. A container on the way again is a cycle. */\n readonly open: Set<object>;\n}\n\n/**\n * This function tells if JSON writes a value exactly. Such a value is a finite number other than `-0`, a text, a truth\n * value, `null`, or a container of such values.\n */\nfunction isJson(value: unknown, encoder: Encoder): boolean {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value) && !Object.is(value, -0);\n const list = Array.isArray(value);\n if (!list && !isRecord(value)) return false;\n const container = value as object;\n const known = encoder.json.get(container);\n if (known !== undefined) return known;\n // A cycle is not JSON. The mark stays false until each item is JSON.\n encoder.json.set(container, false);\n let all = true;\n if (list) {\n const items = value as readonly unknown[];\n for (let index = 0; index < items.length && all; index += 1) all = isJson(items[index], encoder);\n } else {\n const record = value as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(record)) {\n if (!isJson(record[key], encoder)) {\n all = false;\n break;\n }\n }\n }\n encoder.json.set(container, all);\n return all;\n}\n\n/** This function gives the text of a number that JSON cannot write, for `ext.number`. */\nfunction numberText(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Number.POSITIVE_INFINITY) return \"Infinity\";\n if (value === Number.NEGATIVE_INFINITY) return \"-Infinity\";\n return \"-0\";\n}\n\n/** This function gives the term document of a value in one call of `encodeValue`. */\nfunction encodeTerm(value: unknown, encoder: Encoder): Json {\n if (isJson(value, encoder)) return isEnvelope(value) ? { type: \"lit\", value: value as Json } : (value as Json);\n if (value === undefined) return { type: [\"ext\", \"undefined\"], value: null };\n if (typeof value === \"number\") return { type: [\"ext\", \"number\"], value: numberText(value) };\n for (const [name, codec] of encoder.codecs) {\n if (member(value, name, encoder.domains)) return { type: [\"ext\", \"domain\"], value: { domain: name, data: codec.encode(value) } };\n }\n if (!Array.isArray(value) && !isRecord(value)) {\n throw new TypeError(`encodeValue cannot write the value ${describe(value)}: no domain of the machine with a codec holds it.`);\n }\n if (encoder.open.has(value)) throw new TypeError(\"encodeValue cannot write a value with a cycle.\");\n encoder.open.add(value);\n let out: Json;\n if (Array.isArray(value)) {\n // `Array.from` visits each hole of a sparse list as `undefined`.\n out = { type: \"list\", value: Array.from(value as readonly unknown[], (item) => encodeTerm(item, encoder)) };\n } else {\n const fields: Record<string, Json> = {};\n const record = value as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(record)) setOwn(fields, key, encodeTerm(record[key], encoder));\n out = { type: \"record\", value: fields };\n }\n encoder.open.delete(value);\n return out;\n}\n\n/**\n * This function writes a host value as a term document of the formula kit (EXT.ENCODE, D40). Thus the same value has\n * the same document in each language (D12).\n *\n * - A value that JSON writes exactly stays as it is. A literal with the shape of an envelope goes into `lit`.\n * - `NaN`, an infinity and `-0` become `ext.number`, and `undefined` becomes `ext.undefined`.\n * - A member of a domain with a codec becomes `ext.domain`. The domains go in the order of their names.\n * - A list or a plain record with such a value becomes the construct `list` or `record`.\n *\n * @param machine - The machine, or only its domains.\n * @param value - The host value.\n * @returns The document. `decodeValue` gives the value again (EXT.ROUNDTRIP).\n * @throws {TypeError} The value has a cycle, or it is not JSON and no domain with a codec holds it.\n */\nexport function encodeValue(machine: Pick<Machine, \"domains\">, value: unknown): Json {\n const domains = machine.domains;\n const codecs: (readonly [string, DomainCodec])[] = [];\n if (domains !== undefined) {\n for (const name of Object.keys(domains).sort()) {\n const domain = domainOf(name, domains);\n const codec = domain === undefined ? undefined : codecOf(domain);\n if (codec !== undefined) codecs.push([name, codec]);\n }\n }\n return encodeTerm(value, { domains, codecs, json: new WeakMap(), open: new Set() });\n}\n\n/**\n * This function reads a document of `encodeValue` again: it evaluates the document as a term, in an empty context.\n * A bare root value is a literal.\n *\n * @param machine - A machine of the formula kit, with the domains of the document.\n * @param doc - The document.\n * @returns The value, or the error of the evaluation.\n */\nexport function decodeValue(machine: Machine, doc: unknown): Result {\n return prepare(machine, doc, { declaredType: \"lit\" }).evaluate(makeContext());\n}\n","import { type Json, type Key, docEquals, isKey, isRecord } from \"./doc.ts\";\nimport type { Kind, KindFacts, LazyRule, WorldEntry } from \"./world.ts\";\nimport { type CompiledPath, type Context, type Resolution, compilePath, valueOfThing } from \"./deref.ts\";\nimport { type EvalError, type Failed, type Result, Failure, fail, ok, thrown } from \"./errors.ts\";\nimport { type Code, type CompileInput, type CompiledEvaluator, type CompiledPart, type Evaluator, type Machine, type Runtime, resolveCompiled, totalCode } from \"./evaluate.ts\";\nimport { type MachinePart, mergeMachines } from \"./merge.ts\";\nimport { type Domain, type ValueType, HEADER_KEYS, STD_DOMAINS, callable, fieldOf, fits, fnOf, holdsEnvelope, isPrecise, isUnknown, itemOf, join, member, stepType, typeText } from \"./types.ts\";\nimport type { TypeInput, TypeRule } from \"./typing.ts\";\nimport { decodeDomain, domainTypeOf } from \"./codec.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/**\n * The code of an extension: it gives the value of the data of an extension document, in the context of the document.\n * It also gets the domains of the machine, for the codecs of `ext.domain` (D40).\n */\nexport type ExtFn = (data: Json, context: Context, domains?: Readonly<Record<string, Domain>>) => 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`, `ext.number` and\n * `ext.domain`.\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 * - `pure`: the pure operations, for `factsOf` (D24). `true` names each operation that is not volatile. The default\n * names no operation.\n * - `pureExt`: the pure extensions of `ext`, by their name, for `factsOf` and the folds of a plan (PLAN.FOLD, D47).\n * The default names no extension. A standard extension is pure without a name here.\n * - `volatile`: the operations whose results can change while their arguments stay the same, for example a clock.\n * - `sigs`: the signatures of the operations, by their name, for a check of types (TYPE.SIGNATURE). A list gives\n * overloads. An operation without a signature takes and gives `unknown` (TYPE.GRADUAL).\n *\n * A check of types trusts the signatures. Each operation must give a member of the result of each signature that\n * its arguments match. The hook `check` must keep each result in that type.\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 readonly pure?: true | readonly string[];\n readonly pureExt?: readonly string[];\n readonly volatile?: readonly string[];\n readonly sigs?: Readonly<Record<string, Signature | readonly Signature[]>> | ((name: string) => Signature | readonly Signature[] | undefined);\n}\n\n/**\n * The signature of an operation: the value types of its parameters and of its result (TYPE.SIGNATURE). A parameter at\n * the end of `params` is optional when `undefined` is a member of its type, for example `unknown`. A later version can add a key, for example the type that a\n * true result proves.\n */\nexport interface Signature {\n /** The types of the parameters, in order. */\n readonly params: readonly ValueType[];\n /** The type of each argument after the parameters. Without it, the operation takes no more arguments. */\n readonly rest?: ValueType;\n /** The type of the result. */\n readonly to: ValueType;\n}\n\n/** The mark of a field that the profile leaves out of a record. */\nconst SKIPPED: unique symbol = /* @__PURE__ */ 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 = /* @__PURE__ */ 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/**\n * The standard extensions: the values that JSON cannot write. `ext.domain` reads a member of a domain through the\n * codec of the domain (EXT.DOMAIN, D40).\n */\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 domain: (data, _context, domains) => decodeDomain(data, domains),\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\" }, pure: true, summary: LIT_SUMMARY },\n ref: { verbs: { eval: \"formula.ref\" }, pure: true, 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\" }, pure: true, summary: \"A record: each field is a term.\" },\n list: { verbs: { eval: \"formula.list\" }, parts: terms, pure: true, 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 pure: true,\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 // The body evaluates only when something calls the function.\n pure: true,\n lazy: [{ 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 // A host function in a name is a value. When it is volatile, the host marks its read (FACTS.VOLATILE).\n pure: true,\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 pure: true,\n lazy: [{ in: [[\"then\"], [\"else\"]] }],\n summary: \"It evaluates the test, then only the branch that the test selects.\",\n },\n and: { verbs: { eval: \"formula.and\" }, parts: terms, pure: true, lazy: [{ after: 1 }], summary: \"True when each term is true. It stops at the first false term.\" },\n or: { verbs: { eval: \"formula.or\" }, parts: terms, pure: true, lazy: [{ after: 1 }], 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 gives the type of a value of a profile: the value itself as `one`. `undefined` gives the base type\n * `undefined`, because JSON and thus `one` cannot hold it (D48). A function gives `unknown`.\n */\nfunction valueType(value: unknown): ValueType {\n if (value === undefined) return \"undefined\";\n return typeof value === \"function\" ? \"unknown\" : { one: [value as Json] };\n}\n\n/** This function tells if a value has the form of a signature: a record with `params` as a list, and `to`. */\nfunction isSignature(value: unknown): value is Signature {\n return typeof value === \"object\" && value !== null && Array.isArray((value as { readonly params?: unknown }).params) && Object.hasOwn(value, \"to\");\n}\n\n/** This function gives the text of a signature, for the reason of an issue. */\nfunction signatureText(sig: Signature): string {\n const params = sig.params.map(typeText);\n if (sig.rest !== undefined) params.push(`...${typeText(sig.rest)}`);\n return `(${params.join(\", \")}) => ${typeText(sig.to)}`;\n}\n\nfunction argumentsText(count: number): string {\n return `${count} argument${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** This function gives the text of a list of names for a reason, for example `a, b and c`. */\nfunction listText(names: readonly string[]): string {\n return names.length < 2 ? names.join(\"\") : `${names.slice(0, -1).join(\", \")} and ${names[names.length - 1] as string}`;\n}\n\n/**\n * This function tells if a signature takes a count of arguments. A parameter at the end is optional when its type\n * holds `undefined`, because a missing argument is `undefined`. `unknown` and the base type `undefined` hold it.\n *\n * @returns `undefined` when the number is correct, or else the text of the numbers that the signature takes.\n */\nfunction arityOf(sig: Signature, count: number, domains: Machine[\"domains\"]): string | undefined {\n let least = sig.params.length;\n while (least > 0 && member(undefined, sig.params[least - 1] as ValueType, domains)) least -= 1;\n const most = sig.rest === undefined ? sig.params.length : Number.POSITIVE_INFINITY;\n if (count >= least && count <= most) return undefined;\n if (most === Number.POSITIVE_INFINITY) return `at least ${argumentsText(least)}`;\n return least === most ? argumentsText(most) : `${least} to ${argumentsText(most)}`;\n}\n\n/** This function gives the parameters of a document of `fn`: the texts of its list `params`. */\nfunction paramsOf(value: unknown): readonly string[] {\n const params = isRecord(value) ? value[\"params\"] : undefined;\n return Array.isArray(params) ? params.filter((param): param is string => typeof param === \"string\") : [];\n}\n\n/**\n * This function makes the type rules of the formula kit for one profile (TYPE.SYNTH, D25). Each evaluator of the kit\n * holds its rule. The rules read the rules of the profile that change a type: `truthy`, `logic`, `otherwise`, `omit`\n * and `sigs`.\n */\nfunction formulaTypes(profile: FormulaProfile): Readonly<Record<string, TypeRule>> {\n // Only the default truth accepts nothing but a truth value. A truth of the profile accepts each value.\n const truth: ValueType | undefined = profile.truthy === undefined ? \"bool\" : undefined;\n const logicValue = profile.logic === \"value\";\n const otherwise = Object.hasOwn(profile, \"otherwise\") ? valueType(profile.otherwise) : \"null\";\n const lookup = (name: string): readonly unknown[] | undefined => {\n const sigs = profile.sigs;\n if (sigs === undefined) return undefined;\n let found: unknown;\n if (typeof sigs === \"function\") {\n try {\n found = sigs(name);\n } catch {\n return undefined;\n }\n } else {\n found = Object.hasOwn(sigs, name) ? sigs[name] : undefined;\n }\n if (found === undefined) return undefined;\n return Array.isArray(found) ? found : [found];\n };\n const nameOf = (input: TypeInput): string => input.typePath.slice(1).join(\".\");\n /** The signatures of an operation. Each type of a signature is a contract, thus the check examines it one time. */\n const signatures = (input: TypeInput): { readonly sigs: readonly Signature[]; readonly bad: boolean } | undefined => {\n const name = nameOf(input);\n const raw = lookup(name);\n if (raw === undefined) return undefined;\n const sigs: Signature[] = [];\n for (const sig of raw) {\n if (!isSignature(sig)) continue;\n sig.params.forEach((param, index) => input.contract(param, `parameter ${index + 1} of a signature of ops.${name}`));\n if (sig.rest !== undefined) input.contract(sig.rest, `rest parameter of a signature of ops.${name}`);\n input.contract(sig.to, `result of a signature of ops.${name}`);\n sigs.push(sig);\n }\n return { sigs, bad: sigs.length !== raw.length };\n };\n const logic = (word: \"and\" | \"or\"): TypeRule => ({\n part: (_input, path) => (truth === undefined ? {} : { expect: truth, what: `term ${Number(path[0]) + 1} of ${word}` }),\n synth: (input) => {\n if (!logicValue) return \"bool\";\n // With the logic \"value\", the result is the term that decided, or the last term.\n if (input.paths.length === 0) return { one: [word === \"and\"] };\n return input.paths.reduce<ValueType>((type, path) => join(type, input.typeOf(path), input.machine.domains), \"never\");\n },\n });\n\n return {\n \"formula.lit\": { synth: (input) => valueType(input.doc.value) },\n\n \"formula.ref\": {\n synth: (input, report) => {\n const path = input.doc.value;\n // An address gives a thing, not a value. The check gives #VALUE! for a path that is not a list.\n if (input.address || !Array.isArray(path) || path.length === 0) return \"unknown\";\n const domains = input.machine.domains;\n const plain = input.machine.plain === true;\n let type: ValueType;\n let start: number;\n if (path[0] === \"names\") {\n const name = path[1];\n // The record of the names holds the error of a failed binding, thus the path [\"names\"] has no type. A record\n // of names with only the keys of a header is an envelope, and a path into it asks the ladder.\n if (!isKey(name) || (!plain && HEADER_KEYS.has(String(name)))) return \"unknown\";\n type = input.nameType(String(name)) ?? \"unknown\";\n start = 2;\n } else {\n type = input.rootType(String(path[0]));\n start = 1;\n }\n for (let index = start; ; index += 1) {\n // A path follows a reference document that it reaches, and it asks the ladder for a step into an envelope.\n if (isUnknown(type, domains) || (!plain && holdsEnvelope(type, domains))) return \"unknown\";\n if (index >= path.length) return type;\n const step = path[index];\n // A step document gives what its walker reaches. It has no type yet.\n if (!isKey(step)) return \"unknown\";\n const next = stepType(type, step, domains, input.contract);\n if (\"missing\" in next) {\n const fields = next.missing.length === 0 ? \"\" : ` Its fields are ${listText(next.missing)}.`;\n report({ reason: `The value at ${path.slice(0, index).map(String).join(\".\")} has no field ${String(step)}.${fields}` });\n return \"unknown\";\n }\n type = next.type;\n }\n },\n },\n\n \"formula.record\": {\n part: (input, path) => {\n const want = fieldOf(input.expected, String(path[0]), input.machine.domains);\n return want === undefined ? {} : { expect: want, what: `field ${String(path[0])} of the record` };\n },\n synth: (input) => {\n const fields: Record<string, ValueType> = {};\n for (const path of input.paths) setOwn(fields, String(path[0]), input.typeOf(path));\n const keys = Object.keys(fields);\n // A profile with omit can leave out each field, thus each field is optional.\n return { record: fields, ...(profile.omit !== undefined && keys.length > 0 ? { optional: keys } : {}), closed: true };\n },\n },\n\n \"formula.list\": {\n part: (input, path) => {\n const want = itemOf(input.expected, input.machine.domains);\n return want === undefined ? {} : { expect: want, what: `item ${Number(path[0]) + 1} of the list` };\n },\n synth: (input) => ({ list: input.paths.reduce<ValueType>((type, path) => join(type, input.typeOf(path), input.machine.domains), \"never\") }),\n },\n\n \"formula.let\": {\n part: (input, path) => {\n if (path[0] !== \"body\") return {};\n // The scope rule keysAt puts the bindings first, thus their types are known here.\n const names: Record<string, ValueType> = {};\n for (const each of input.paths) if (each[0] === \"bind\" && each.length === 2) setOwn(names, String(each[1]), input.typeOf(each));\n return { names, ...(isUnknown(input.expected, input.machine.domains) ? {} : { expect: input.expected, what: \"body of let\" }) };\n },\n synth: (input) => input.typeOf([\"body\"]),\n },\n\n \"formula.fn\": {\n part: (input, path) => {\n if (path[0] !== \"body\") return {};\n // An expected function type gives the types of the parameters. Without it, each parameter is unknown.\n const want = fnOf(input.expected, input.machine.domains);\n const names: Record<string, ValueType> = {};\n paramsOf(input.doc.value).forEach((name, index) => setOwn(names, name, want?.params[index] ?? \"unknown\"));\n return { names, ...(want === undefined || isUnknown(want.to, input.machine.domains) ? {} : { expect: want.to, what: \"body of fn\" }) };\n },\n synth: (input) => {\n const want = fnOf(input.expected, input.machine.domains);\n return { fn: paramsOf(input.doc.value).map((_name, index) => want?.params[index] ?? \"unknown\"), to: input.typeOf([\"body\"]) };\n },\n },\n\n \"formula.call\": {\n synth: (input, report) => {\n const domains = input.machine.domains;\n const target = input.typeOf([\"fn\"]);\n if (isUnknown(target, domains)) return \"unknown\";\n const want = fnOf(target, domains);\n if (want === undefined) {\n if (callable(target, domains)) return \"unknown\";\n report({ path: [\"fn\"], reason: `The fn of call has the type ${typeText(target)}. It must give a function.`, found: target });\n return \"unknown\";\n }\n const args = input.paths.filter((path) => path[0] === \"args\");\n for (const path of args) {\n const index = Number(path[1]);\n const param = want.params[index];\n // The function does not read an argument after its parameters.\n if (param === undefined) continue;\n const found = input.typeOf(path);\n if (!fits(found, param, domains)) {\n report({ path, reason: `The argument ${index + 1} of the call has the type ${typeText(found)}. The function expects the type ${typeText(param)}.`, expected: param, found });\n }\n }\n const missing = want.params.findIndex((param, index) => index >= args.length && !isUnknown(param, domains));\n if (missing !== -1) {\n const param = want.params[missing] as ValueType;\n report({ reason: `The call gives ${argumentsText(args.length)}. The function expects the type ${typeText(param)} for the argument ${missing + 1}.`, expected: param });\n }\n return want.to;\n },\n },\n\n \"formula.if\": {\n part: (input, path) => {\n if (path[0] === \"test\") return truth === undefined ? {} : { expect: truth, what: \"test of if\" };\n return isUnknown(input.expected, input.machine.domains) ? {} : { expect: input.expected, what: `${String(path[0])} branch of if` };\n },\n synth: (input) => {\n const value = input.doc.value;\n const other = isRecord(value) && Object.hasOwn(value, \"else\") ? input.typeOf([\"else\"]) : otherwise;\n return join(input.typeOf([\"then\"]), other, input.machine.domains);\n },\n },\n\n \"formula.and\": logic(\"and\"),\n \"formula.or\": logic(\"or\"),\n\n \"formula.op\": {\n part: (input, path) => {\n const read = signatures(input);\n // Only one signature gives the types of the arguments before their check. Overloads select after it.\n if (read === undefined || read.sigs.length !== 1) return {};\n const sig = read.sigs[0] as Signature;\n const index = Number(path[0]);\n const want = index < sig.params.length ? sig.params[index] : sig.rest;\n return want === undefined ? {} : { expect: want, what: `argument ${index + 1} of ops.${nameOf(input)}` };\n },\n synth: (input, report) => {\n const read = signatures(input);\n if (read === undefined) return \"unknown\";\n const name = nameOf(input);\n const domains = input.machine.domains;\n if (read.bad) report({ reason: `A signature of ops.${name} is not a record with params and to. The check does not read it.` });\n const { sigs } = read;\n if (sigs.length === 0) return \"unknown\";\n const args = input.paths.map((path) => input.typeOf(path));\n if (sigs.length === 1) {\n const sig = sigs[0] as Signature;\n const takes = arityOf(sig, args.length, domains);\n if (takes !== undefined) report({ reason: `The operation ops.${name} takes ${takes}. It gets ${args.length}.` });\n return sig.to;\n }\n const paramAt = (sig: Signature, index: number): ValueType => sig.params[index] ?? sig.rest ?? \"unknown\";\n const fitting = sigs.filter((sig) => arityOf(sig, args.length, domains) === undefined && args.every((arg, index) => fits(arg, paramAt(sig, index), domains)));\n if (fitting.length === 0) {\n const given = args.map(typeText).join(\", \");\n report({ reason: `No signature of ops.${name} fits the arguments (${given}). The signatures are ${sigs.map(signatureText).join(\" and \")}.` });\n return \"unknown\";\n }\n const first = fitting[0] as Signature;\n // Precise arguments are members of the first signature that fits. An argument with unknown can match a later one.\n if (fitting.length === 1 || args.every((arg) => isPrecise(arg, domains))) return first.to;\n return fitting.every((sig) => docEquals(sig.to, first.to)) ? first.to : \"unknown\";\n },\n },\n\n \"formula.ext\": {\n synth: (input) => {\n const name = nameOf(input);\n const own = profile.ext !== undefined && Object.hasOwn(profile.ext, name);\n if (own) return \"unknown\";\n // The standard extensions give the values that JSON cannot write, thus each has a base type (D48).\n if (name === \"undefined\") return \"undefined\";\n if (name === \"number\") return \"number\";\n return name === \"domain\" ? domainTypeOf(input.doc.value, input.machine.domains) : \"unknown\";\n },\n },\n };\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. Each evaluator also holds its type rule, for a check of types (TYPE.SYNTH).\n *\n * Equal profiles give the same evaluator objects (COMPOSE.UNIFY, D46). Thus two machines of one profile merge without\n * a conflict. Each call gives a new record. Each evaluator object is frozen, because many machines can share it.\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 return { ...kitOf(profile).evaluators };\n}\n\n/** This function makes new evaluators of the formula kit for the fields of one profile. */\nfunction makeEvaluators(profile: FormulaProfile): Readonly<Record<string, Evaluator>> {\n const evaluators = formulaCode(profile);\n const types = formulaTypes(profile);\n const out: Record<string, Evaluator> = {};\n for (const name of Object.keys(evaluators)) {\n const evaluator = evaluators[name] as CompiledEvaluator;\n const type = Object.hasOwn(types, name) ? types[name] : undefined;\n out[name] = Object.freeze(type === undefined ? evaluator : { compile: evaluator.compile, type });\n }\n return Object.freeze(out);\n}\n\n/** The keys of a profile that the kit reads. The kit ignores each other key. */\nconst PROFILE_KEYS = /* @__PURE__ */ Object.freeze([\n \"ops\",\n \"lazy\",\n \"ext\",\n \"truthy\",\n \"otherwise\",\n \"logic\",\n \"omit\",\n \"missing\",\n \"check\",\n \"combine\",\n \"pure\",\n \"pureExt\",\n \"volatile\",\n \"sigs\",\n] as const satisfies readonly (keyof FormulaProfile)[]);\n\n/** The evaluators and the hooks of the formula kit for one profile, with the fields that made them. */\ninterface Kit {\n readonly fields: FormulaProfile;\n readonly evaluators: Readonly<Record<string, Evaluator>>;\n readonly known: (path: readonly Key[], evaluator: string) => true | string;\n readonly facts: (path: readonly Key[], code: string) => KindFacts | undefined;\n}\n\n/** The number of recent kits that a profile in a new object can find by its fields. */\nconst RECENT_KITS = 16;\n\n/** The kit of each profile object. A kit goes when its profile object goes. */\nconst kitsByProfile = /* @__PURE__ */ new WeakMap<object, Kit>();\n\n/** The recent kits, the most recent first. The list holds `RECENT_KITS` kits or fewer. */\nconst recentKits: Kit[] = [];\n\n/**\n * This function gives the canonical form of a profile: a frozen record of the fields that the kit reads. A field\n * with the value `undefined` is absent, but `otherwise` is present when the profile has it as an own key. A list\n * is a frozen copy. Each other value stays the same object.\n */\nfunction fieldsOf(profile: FormulaProfile): FormulaProfile {\n const out: Record<string, unknown> = {};\n for (const key of PROFILE_KEYS) {\n if (key === \"otherwise\" ? !Object.hasOwn(profile, key) : profile[key] === undefined) continue;\n const value: unknown = profile[key];\n out[key] = Array.isArray(value) ? Object.freeze([...(value as unknown[])]) : value;\n }\n return Object.freeze(out);\n}\n\n/**\n * This function tells if two canonical forms are equal. They must have the same keys. A function, a record and a host\n * value are equal only to themselves. Two lists are equal when their items are the same, in order.\n */\nfunction sameFields(a: FormulaProfile, b: FormulaProfile): boolean {\n const left = a as Readonly<Record<string, unknown>>;\n const right = b as Readonly<Record<string, unknown>>;\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) return false;\n return keys.every((key) => {\n if (!Object.hasOwn(right, key)) return false;\n const x = left[key];\n const y = right[key];\n if (Object.is(x, y)) return true;\n return Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((item, index) => Object.is(item, y[index]));\n });\n}\n\n/**\n * This function gives the kit of a profile (D46). A profile object that the kit knows, with the same fields, gives its\n * kit. Then a recent kit with equal fields serves a new profile object. Else the function makes a new kit from the\n * canonical form. Thus a later change of a field of the profile object gives a new kit, and an old kit does not change.\n */\nfunction kitOf(profile: FormulaProfile): Kit {\n const fields = fieldsOf(profile);\n const known = kitsByProfile.get(profile);\n if (known !== undefined && sameFields(known.fields, fields)) return known;\n const index = recentKits.findIndex((kit) => sameFields(kit.fields, fields));\n let kit: Kit;\n if (index >= 0) {\n kit = recentKits[index] as Kit;\n recentKits.splice(index, 1);\n } else {\n const hook = makeKnown(fields);\n kit = { fields, evaluators: makeEvaluators(fields), known: hook, facts: makeFacts(fields, hook) };\n }\n recentKits.unshift(kit);\n if (recentKits.length > RECENT_KITS) recentKits.length = RECENT_KITS;\n kitsByProfile.set(profile, kit);\n return kit;\n}\n\n/** This function makes the code of the evaluators of the formula kit, without their type rules. */\nfunction formulaCode(profile: FormulaProfile): Readonly<Record<string, CompiledEvaluator>> {\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 /*\n * The code of a reference (PLAN.LEAN). The helpers below serve each reference of the language. Each code keeps only\n * what its own reference needs. A reference with a static path keeps its compiled path, its first name and its mark\n * `address`. It does not keep its document, its split or the functions of the other form.\n */\n\n /** This function gives the result of a resolution of a reference. An address gives what the path reaches: a host thing stays a thing. */\n const give = (found: Resolution, address: boolean): Result => {\n if (!found.ok) return fail(found.code, found.reason);\n if (address) 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 /** This function gives the error of a name whose binding failed, or `undefined` when the binding holds no error. */\n const held = (ctx: Context, rt: Runtime, head: string | undefined): Failed | undefined => {\n if (head === undefined || !Object.hasOwn(ctx.names, head)) return undefined;\n const bound = ctx.names[head];\n if (!(bound instanceof Held)) return undefined;\n // The result comes from the binding of the name, thus the runtime resolves the name for the list of reads (READS.RECORD).\n rt.resolve(ctx, [\"names\", head]);\n return { ok: false, error: bound.error };\n };\n /** This function gives the code of a reference with a static path. A path without a first name does not test a binding. */\n const staticRef = (compiledPath: CompiledPath, head: string | undefined, address: boolean): Code =>\n head === undefined\n ? (ctx, rt) => give(resolveCompiled(rt, ctx, compiledPath), address)\n : (ctx, rt) => held(ctx, rt, head) ?? give(resolveCompiled(rt, ctx, compiledPath), address);\n /**\n * This function gives the code of a reference whose step documents are parts, when the kind ref has a deep shape.\n * The steps evaluate first, in order, thus the error of a step comes before the error of a binding (FORMULA.STEPS).\n */\n const stepsRef = (parts: readonly CompiledPart[], fill: CompileInput[\"fill\"], head: string | undefined, address: boolean): Code => {\n return (ctx, rt) => {\n const steps = valuesOf(parts, ctx, rt);\n if (!Array.isArray(steps)) return steps;\n return held(ctx, rt, head) ?? give(rt.resolve(ctx, fill(steps) as readonly unknown[]), address);\n };\n };\n\n return {\n \"formula.lit\": compiled(({ doc }) => {\n // A literal cannot fail, thus its code needs no place (PLAN.TOTAL).\n const result = ok(doc.value);\n return totalCode(() => result);\n }),\n\n \"formula.ref\": compiled(({ doc, parts, fill, address, machine }) => {\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 // A path without parts is static, thus it compiles one time for the machine of the plan (PLAN.PATH).\n if (parts.length === 0) return staticRef(compilePath(machine, path), head, address === true);\n return stepsRef(parts, fill, head, address === true);\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 totalCode(() => 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 // A closure keeps the context for each later use, thus the list of reads gets each root (READS.KEPT).\n rt.keepsContext?.();\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, machine }) => {\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, machine.domains);\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 * Equal profiles give the same hook (D46).\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 return kitOf(profile).known;\n}\n\n/** This function makes a new hook `known` for the fields of one profile. */\nfunction makeKnown(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 * The facts of an extension of the profile that `pureExt` does not name. It gets the context, thus it can read outside\n * `resolve`.\n */\nconst NOT_PURE: KindFacts = /* @__PURE__ */ Object.freeze({ pure: false });\n\n/** The facts of a standard extension, and of an extension that `pureExt` names. */\nconst PURE: KindFacts = /* @__PURE__ */ Object.freeze({ pure: true });\n\n/** The lazy rule of a lazy operation: it covers each argument. */\nconst EACH_PART: readonly LazyRule[] = /* @__PURE__ */ Object.freeze([/* @__PURE__ */ Object.freeze({})]);\n\n/**\n * This function makes the hook `facts` of the formula kit for one profile (FACTS.PROFILE, D24). It answers for the\n * operations and the extensions, because one fallback kind covers each of them.\n *\n * - An operation of `lazy` has a lazy rule for each argument.\n * - An operation is pure when the profile names it in `pure`, or when `pure` is `true`. A volatile operation is not pure.\n * - A standard extension is pure. An extension of the profile is pure only when the profile names it in `pureExt` (D47).\n * Such an extension keeps C4: it reads the context only through `resolve`.\n *\n * Equal profiles give the same hook (D46).\n *\n * @param profile - The operations, the extensions and their facts.\n * @returns The hook: the facts of a name, or `undefined` for the facts of the contract.\n */\nexport function formulaFacts(profile: FormulaProfile = {}): (path: readonly Key[], code: string) => KindFacts | undefined {\n return kitOf(profile).facts;\n}\n\n/** This function makes a new hook `facts` for the fields of one profile, with the hook `known` of the same fields. */\nfunction makeFacts(profile: FormulaProfile, known: (path: readonly Key[], evaluator: string) => true | string): (path: readonly Key[], code: string) => KindFacts | undefined {\n const volatile = new Set(profile.volatile ?? []);\n const pure = profile.pure === true ? undefined : new Set(profile.pure ?? []);\n const pureExt = new Set(profile.pureExt ?? []);\n return (path, code) => {\n if (code !== \"formula.op\" && code !== \"formula.ext\") return undefined;\n const name = path.slice(1).join(\".\");\n if (code === \"formula.ext\") {\n if (profile.ext !== undefined && Object.hasOwn(profile.ext, name)) return pureExt.has(name) ? PURE : NOT_PURE;\n return Object.hasOwn(STD_EXT, name) ? PURE : undefined;\n }\n // An operation that the language does not have gives #NAME?. The kit gives it no facts.\n if (known(path, code) !== true) return undefined;\n const isVolatile = volatile.has(name);\n const lazy = profile.lazy !== undefined && Object.hasOwn(profile.lazy, name);\n return { pure: !isVolatile && (pure === undefined || pure.has(name)), volatile: isVolatile, ...(lazy ? { lazy: EACH_PART } : {}) };\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. The hook `facts` of the kit comes from the profile too (`formulaFacts`).\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 * The kit gives the domains of the kernel (`STD_DOMAINS`). Thus a domain of the language with the name `number` is a\n * conflict. The language names `[\"domains\", \"number\"]` in `replaces` to replace it.\n *\n * Equal profiles give the same evaluators and the same hooks (COMPOSE.UNIFY, D46). Thus two machines of one profile\n * merge, also when each adds its own language. Two profiles with different fields give different evaluators, and\n * their machines conflict at each evaluator name of the kit.\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 const kit = kitOf(profile);\n return mergeMachines({ world: { kinds: formulaKinds() }, evaluators: { ...kit.evaluators }, domains: STD_DOMAINS, known: kit.known, facts: kit.facts }, more);\n}\n","import { type Json, type Key, isEnvelope, isRecord, typePath } from \"./doc.ts\";\nimport { type Result, describe, fail, isStackOverflow, ok } from \"./errors.ts\";\nimport type { EvalFn, Part } from \"./evaluate.ts\";\nimport type { MachinePart } from \"./merge.ts\";\nimport { encodeValue } from \"./codec.ts\";\n\n/** The place of an operator: before its term, between two terms, or after its term. */\nexport type SyntaxFixity = \"prefix\" | \"infix\" | \"postfix\";\n\n/**\n * The grouping of a chain of one infix operator. `left` reads `a - b - c` as `(a - b) - c`, and `right` reads\n * `a ^ b ^ c` as `a ^ (b ^ c)`. `none` refuses a chain. `flat` reads a chain as one document with each term.\n */\nexport type SyntaxAssoc = \"left\" | \"right\" | \"none\" | \"flat\";\n\n/** One operator of a syntax profile. */\nexport interface SyntaxOperator {\n /** The text of the operator, for example `+`, `<>` or `and`. A word operator is a plain name. */\n readonly symbol: string;\n /** The place of the operator. */\n readonly fixity: SyntaxFixity;\n /** The precedence. A larger number binds more tightly. */\n readonly prec: number;\n /** The grouping of a chain of an infix operator. The default is `left`. */\n readonly assoc?: SyntaxAssoc;\n /** The type of the document that the operator makes, with dots between the keys, for example `ops.add` or `and`. */\n readonly kind: string;\n}\n\n/** The literal rules of a syntax profile. */\nexport interface SyntaxLiterals {\n /** `false` removes the decimal numbers. The default is `true`. */\n readonly numbers?: boolean;\n /** `true` puts a minus sign right before a digit into the number, where a term starts. The default is `true`. */\n readonly signed?: boolean;\n /** The texts: the quote and the escape of a quote. `false` removes the texts. The default is `\"` with backslashes. */\n readonly strings?: false | { readonly quote?: '\"' | \"'\"; readonly escape?: \"backslash\" | \"double\" };\n /** The words that are literals, with their values. The default is `true`, `false` and `null`. */\n readonly words?: Readonly<Record<string, unknown>>;\n}\n\n/** A reference syntax that a pattern gives, for example the address `A1` of a cell. */\nexport interface SyntaxRefPattern {\n /** The pattern of the text of a reference. The parser tries it before a name. */\n readonly pattern: RegExp;\n /** This function gives the path of the reference from its text. */\n readonly read: (text: string) => readonly Key[];\n /** This function gives the text of a path, or `undefined` when the pattern does not write the path. */\n readonly write: (path: readonly unknown[]) => string | undefined;\n}\n\n/** The reference syntax of a syntax profile. */\nexport interface SyntaxRefs {\n /** The root of a bare name. The default is `names`. Thus `x` is the path `[\"names\", \"x\"]`. */\n readonly bare?: string;\n /** The roots that the text names first, for example `self.price`. The default is `self`, `world`, `event` and `caps`. */\n readonly roots?: readonly string[];\n /** `false` removes the field steps `a.b`. The default is `true`. */\n readonly fields?: boolean;\n /** The patterns of other references. */\n readonly patterns?: readonly SyntaxRefPattern[];\n}\n\n/** A call form: a name with arguments in parentheses that makes a construct, for example `if(test, then, else)`. */\nexport interface SyntaxForm {\n /** The name in the text. */\n readonly name: string;\n /** The type of the document, with dots between the keys. */\n readonly kind: string;\n /** The fields of the value, in the order of the arguments. Without them, the value is the list of the arguments. */\n readonly fields?: readonly string[];\n /** The smallest number of arguments. The default is the number of the fields, or `0`. */\n readonly min?: number;\n}\n\n/** The call syntax of a syntax profile. */\nexport interface SyntaxCalls {\n /** The operations that a call `name(args)` can name. `true` permits each name. The default is `true`. */\n readonly ops?: boolean | readonly string[];\n /** The call forms of constructs. A form wins over an operation with the same name. */\n readonly forms?: readonly SyntaxForm[];\n /** The text between two arguments. The default is `,`. */\n readonly separator?: string;\n}\n\n/**\n * The text syntax of a language (D41): an operator table, literal rules, reference syntax and call syntax. `parse`\n * reads a text into a document, and `print` writes a document as text. The profile is data, thus a site, an editor\n * and a language read the same rules.\n */\nexport interface SyntaxProfile {\n /** The operators. */\n readonly operators?: readonly SyntaxOperator[];\n /** The literal rules. */\n readonly literals?: SyntaxLiterals;\n /** The reference syntax. */\n readonly refs?: SyntaxRefs;\n /** The call syntax. */\n readonly calls?: SyntaxCalls;\n /** The deepest nesting that `parse` accepts. The default is `256`. */\n readonly maxDepth?: number;\n}\n\n/** A problem of a text: its character offset, its length and a message. */\nexport interface SyntaxIssue {\n /** The 0-based character offset of the problem. */\n readonly offset: number;\n /** The number of characters of the problem. `0` marks a place between two characters. */\n readonly length: number;\n /** The message. */\n readonly message: string;\n}\n\n/** The result of `parse`: a document, or the problems of the text. */\nexport type ParseResult = { readonly ok: true; readonly doc: Json } | { readonly ok: false; readonly issues: readonly SyntaxIssue[] };\n\n/**\n * The standard syntax of the formula kit. It gives the site and the playground a text form. The operators are\n * `or`, `and`, `not`, the comparisons, `+ - * / %`, a minus sign and `^`, from the loosest to the tightest. A call\n * `name(args)` applies the operation `ops.name`. `if(test, then, else)` and `list(items)` make the constructs.\n */\nexport const STD_SYNTAX: SyntaxProfile = /* @__PURE__ */ Object.freeze({\n operators: [\n { symbol: \"or\", fixity: \"infix\", prec: 1, assoc: \"flat\", kind: \"or\" },\n { symbol: \"and\", fixity: \"infix\", prec: 2, assoc: \"flat\", kind: \"and\" },\n { symbol: \"not\", fixity: \"prefix\", prec: 3, kind: \"ops.not\" },\n { symbol: \"==\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.eq\" },\n { symbol: \"!=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.ne\" },\n { symbol: \"<\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.lt\" },\n { symbol: \"<=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.le\" },\n { symbol: \">\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.gt\" },\n { symbol: \">=\", fixity: \"infix\", prec: 4, assoc: \"none\", kind: \"ops.ge\" },\n { symbol: \"+\", fixity: \"infix\", prec: 5, kind: \"ops.add\" },\n { symbol: \"-\", fixity: \"infix\", prec: 5, kind: \"ops.sub\" },\n { symbol: \"*\", fixity: \"infix\", prec: 6, kind: \"ops.mul\" },\n { symbol: \"/\", fixity: \"infix\", prec: 6, kind: \"ops.div\" },\n { symbol: \"%\", fixity: \"infix\", prec: 6, kind: \"ops.mod\" },\n { symbol: \"-\", fixity: \"prefix\", prec: 7, kind: \"ops.neg\" },\n { symbol: \"^\", fixity: \"infix\", prec: 8, assoc: \"right\", kind: \"ops.pow\" },\n ],\n literals: { words: { true: true, false: false, null: null, undefined: undefined, NaN: NaN, Infinity: Infinity } },\n calls: {\n forms: [\n { name: \"if\", kind: \"if\", fields: [\"test\", \"then\", \"else\"], min: 2 },\n { name: \"list\", kind: \"list\" },\n ],\n },\n} satisfies SyntaxProfile);\n\n// === The compiled profile ===\n\ninterface Op {\n readonly symbol: string;\n readonly fixity: SyntaxFixity;\n readonly prec: number;\n readonly assoc: SyntaxAssoc;\n readonly type: Json;\n readonly kindKey: string;\n readonly word: boolean;\n}\n\ninterface Form {\n readonly name: string;\n readonly type: Json;\n readonly fields: readonly string[] | undefined;\n readonly min: number;\n}\n\ninterface Pattern {\n readonly sticky: RegExp;\n readonly whole: RegExp;\n readonly read: (text: string) => readonly Key[];\n readonly write: (path: readonly unknown[]) => string | undefined;\n}\n\ninterface Compiled {\n readonly prefix: ReadonlyMap<string, Op>;\n readonly binary: ReadonlyMap<string, Op>;\n readonly prefixSymbols: readonly string[];\n readonly binarySymbols: readonly string[];\n readonly byKind: ReadonlyMap<string, readonly Op[]>;\n readonly numbers: boolean;\n readonly signed: boolean;\n readonly quote: string | undefined;\n readonly doubled: boolean;\n readonly words: ReadonlyMap<string, unknown>;\n readonly bare: string;\n readonly roots: ReadonlySet<string>;\n readonly fields: boolean;\n readonly patterns: readonly Pattern[];\n readonly ops: true | ReadonlySet<string>;\n readonly forms: ReadonlyMap<string, Form>;\n readonly formsByKind: ReadonlyMap<string, readonly Form[]>;\n readonly separator: string;\n readonly reserved: ReadonlySet<string>;\n readonly opWords: ReadonlySet<string>;\n readonly maxDepth: number;\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst NAME_AT = /[A-Za-z_][A-Za-z0-9_]*/y;\nconst DIGITS_AT = /[0-9]+/y;\nconst NUMBER_AT = /(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\nconst SYMBOL = /^[^\\sA-Za-z0-9_\"'`()$.]+$/;\nconst DEFAULT_WORDS: Readonly<Record<string, unknown>> = { true: true, false: false, null: null };\nconst DEFAULT_ROOTS: readonly string[] = [\"self\", \"world\", \"event\", \"caps\"];\n\nconst compiledProfiles = new WeakMap<SyntaxProfile, Compiled>();\n\nfunction typeOfKind(kind: string): { readonly type: Json; readonly key: string } {\n const keys = kind.split(\".\");\n if (kind === \"\" || keys.some((key) => key === \"\")) throw new TypeError(`The kind \"${kind}\" of a syntax profile has an empty key.`);\n return { type: keys.length === 1 ? (keys[0] as string) : keys, key: JSON.stringify(keys) };\n}\n\nfunction addTo<V>(map: Map<string, V[]>, key: string, value: V): void {\n const list = map.get(key);\n if (list === undefined) map.set(key, [value]);\n else list.push(value);\n}\n\nfunction compileOps(profile: SyntaxProfile, separator: string): Pick<Compiled, \"prefix\" | \"binary\" | \"prefixSymbols\" | \"binarySymbols\" | \"byKind\" | \"opWords\"> {\n const prefix = new Map<string, Op>();\n const binary = new Map<string, Op>();\n const byKind = new Map<string, Op[]>();\n const assocAt = new Map<number, SyntaxAssoc>();\n const opWords = new Set<string>();\n for (const given of profile.operators ?? []) {\n const word = NAME.test(given.symbol);\n if (!word && (!SYMBOL.test(given.symbol) || given.symbol.includes(separator))) {\n throw new TypeError(`The operator \"${given.symbol}\" is not a plain name or a group of symbols.`);\n }\n if (!Number.isFinite(given.prec)) throw new TypeError(`The operator \"${given.symbol}\" has no finite precedence.`);\n const { type, key } = typeOfKind(given.kind);\n const op: Op = { symbol: given.symbol, fixity: given.fixity, prec: given.prec, assoc: given.assoc ?? \"left\", type, kindKey: key, word };\n const table = op.fixity === \"prefix\" ? prefix : binary;\n if (table.has(op.symbol)) throw new TypeError(`The operator \"${op.symbol}\" has two entries of the same place.`);\n table.set(op.symbol, op);\n if (op.fixity === \"infix\") {\n const assoc = assocAt.get(op.prec);\n if (assoc !== undefined && assoc !== op.assoc) throw new TypeError(`The infix operators of the precedence ${String(op.prec)} have different groupings.`);\n assocAt.set(op.prec, op.assoc);\n }\n if (word) opWords.add(op.symbol);\n addTo(byKind, key, op);\n }\n const longestFirst = (table: Map<string, Op>): string[] =>\n [...table.keys()].filter((symbol) => !NAME.test(symbol)).sort((a, b) => b.length - a.length);\n return { prefix, binary, prefixSymbols: longestFirst(prefix), binarySymbols: longestFirst(binary), byKind, opWords };\n}\n\nfunction compileProfile(profile: SyntaxProfile): Compiled {\n const cached = compiledProfiles.get(profile);\n if (cached !== undefined) return cached;\n const calls = profile.calls ?? {};\n const separator = calls.separator ?? \",\";\n const ops = compileOps(profile, separator);\n const literals = profile.literals ?? {};\n const strings = literals.strings === false ? undefined : (literals.strings ?? {});\n const words = new Map(Object.entries(literals.words ?? DEFAULT_WORDS));\n const refs = profile.refs ?? {};\n const roots = new Set(refs.roots ?? DEFAULT_ROOTS);\n const forms = new Map<string, Form>();\n const formsByKind = new Map<string, Form[]>();\n for (const given of calls.forms ?? []) {\n if (!NAME.test(given.name)) throw new TypeError(`The call form \"${given.name}\" is not a plain name.`);\n const { type, key } = typeOfKind(given.kind);\n const form: Form = { name: given.name, type, fields: given.fields, min: given.min ?? given.fields?.length ?? 0 };\n forms.set(form.name, form);\n addTo(formsByKind, key, form);\n }\n const compiled: Compiled = {\n ...ops,\n numbers: literals.numbers ?? true,\n signed: literals.signed ?? true,\n quote: strings === undefined ? undefined : (strings.quote ?? '\"'),\n doubled: strings !== undefined && strings.escape === \"double\",\n words,\n bare: refs.bare ?? \"names\",\n roots,\n fields: refs.fields ?? true,\n patterns: (refs.patterns ?? []).map((p) => {\n const flags = p.pattern.flags.replace(/[gy]/g, \"\");\n return { sticky: new RegExp(p.pattern.source, `${flags}y`), whole: new RegExp(`^(?:${p.pattern.source})$`, flags), read: p.read, write: p.write };\n }),\n ops: calls.ops === undefined || calls.ops === true ? true : new Set(calls.ops === false ? [] : calls.ops),\n forms,\n formsByKind,\n separator,\n reserved: new Set([...words.keys(), ...ops.opWords, ...roots]),\n maxDepth: profile.maxDepth ?? 256,\n };\n compiledProfiles.set(profile, compiled);\n return compiled;\n}\n\n// === Parse ===\n\n/** The stop of a parse. The parser throws it, and `parse` gives its issue. */\nclass Stop {\n constructor(readonly issue: SyntaxIssue) {}\n}\n\nfunction literalDoc(value: unknown): Json {\n return encodeValue({}, value);\n}\n\nfunction opDoc(op: Op | Form, value: Json): Json {\n return { type: op.type, value };\n}\n\nconst ESCAPES: Readonly<Record<string, string>> = { '\"': '\"', \"'\": \"'\", \"\\\\\": \"\\\\\", \"/\": \"/\", b: \"\\b\", f: \"\\f\", n: \"\\n\", r: \"\\r\", t: \"\\t\" };\n\nclass Parser {\n private pos = 0;\n private depth = 0;\n\n constructor(\n private readonly syn: Compiled,\n private readonly text: string,\n ) {}\n\n parse(): Json {\n this.skip();\n if (this.pos >= this.text.length) this.stop(\"The text is empty.\", 0, 0);\n const doc = this.expr(0);\n this.skip();\n if (this.pos < this.text.length) this.stop(\"The text continues after the expression.\", this.pos, this.tokenLength());\n return doc;\n }\n\n position(): number {\n return this.pos;\n }\n\n private stop(message: string, offset: number, length: number): never {\n throw new Stop({ offset, length, message });\n }\n\n private skip(): void {\n while (this.pos < this.text.length && /\\s/.test(this.text[this.pos] as string)) this.pos += 1;\n }\n\n private at(pattern: RegExp, pos: number = this.pos): string | undefined {\n pattern.lastIndex = pos;\n return pattern.exec(this.text)?.[0];\n }\n\n private tokenLength(): number {\n return (this.at(NAME_AT) ?? this.at(DIGITS_AT) ?? \"x\").length;\n }\n\n /** This method reads an expression by precedence climbing. It stops at an operator below `min`. */\n private expr(min: number): Json {\n const start = this.pos;\n this.depth += 1;\n if (this.depth > this.syn.maxDepth) this.stop(`The text is deeper than ${String(this.syn.maxDepth)} levels.`, start, 0);\n let left = this.operand();\n for (;;) {\n this.skip();\n const found = this.operatorAt();\n if (found === undefined || found.op.prec < min) break;\n const op = found.op;\n this.pos += found.length;\n if (op.fixity === \"postfix\") {\n left = opDoc(op, [left]);\n continue;\n }\n if (op.assoc === \"flat\") {\n const terms = [left, this.expr(op.prec + 1)];\n for (;;) {\n this.skip();\n const next = this.operatorAt();\n if (next === undefined || next.op.fixity !== \"infix\" || next.op.kindKey !== op.kindKey) break;\n this.pos += next.length;\n terms.push(this.expr(op.prec + 1));\n }\n left = opDoc(op, terms);\n continue;\n }\n left = opDoc(op, [left, this.expr(op.assoc === \"right\" ? op.prec : op.prec + 1)]);\n if (op.assoc === \"none\") {\n this.skip();\n const next = this.operatorAt();\n if (next !== undefined && next.op.fixity === \"infix\" && next.op.prec === op.prec) {\n this.stop(`The operator ${next.op.symbol} does not chain after ${op.symbol}. Add parentheses.`, this.pos, next.length);\n }\n }\n }\n this.depth -= 1;\n return left;\n }\n\n /** This method finds an infix or a postfix operator at the position. */\n private operatorAt(): { readonly op: Op; readonly length: number } | undefined {\n const name = this.at(NAME_AT);\n if (name !== undefined) {\n const op = this.syn.binary.get(name);\n return op !== undefined && op.word ? { op, length: name.length } : undefined;\n }\n for (const symbol of this.syn.binarySymbols) {\n if (this.text.startsWith(symbol, this.pos)) return { op: this.syn.binary.get(symbol) as Op, length: symbol.length };\n }\n return undefined;\n }\n\n private operand(): Json {\n this.skip();\n const start = this.pos;\n const c = this.text[start];\n if (c === undefined) return this.stop(\"A term is missing at the end of the text.\", start, 0);\n for (const pattern of this.syn.patterns) {\n const match = this.at(pattern.sticky);\n if (match !== undefined && match !== \"\" && !/[A-Za-z0-9_$(]/.test(this.text[start + match.length] ?? \"\")) {\n this.pos += match.length;\n return { type: \"ref\", value: pattern.read(match) as Json };\n }\n }\n if (/[0-9]/.test(c)) return this.number(false);\n if (c === \"-\" && this.syn.signed && /[0-9]/.test(this.text[start + 1] ?? \"\")) return this.number(true);\n if (c === this.syn.quote) return this.string();\n if (c === \"(\") return this.group();\n if (c === \"`\" || /[A-Za-z_]/.test(c)) return this.named();\n for (const symbol of this.syn.prefixSymbols) {\n if (this.text.startsWith(symbol, start)) {\n this.pos += symbol.length;\n const op = this.syn.prefix.get(symbol) as Op;\n return opDoc(op, [this.expr(op.prec + 1)]);\n }\n }\n if (c === \")\" || this.text.startsWith(this.syn.separator, start)) return this.stop(\"A term is missing.\", start, 0);\n return this.stop(`The text \"${c}\" cannot start a term.`, start, 1);\n }\n\n private number(negative: boolean): Json {\n const start = this.pos;\n if (!this.syn.numbers) this.stop(\"This syntax has no numbers.\", start, this.tokenLength());\n if (negative) this.pos += 1;\n const digits = this.at(NUMBER_AT) as string;\n this.pos += digits.length;\n const value = Number(digits);\n return literalDoc(negative ? -value : value);\n }\n\n private string(): Json {\n const start = this.pos;\n const quote = this.syn.quote as string;\n let out = \"\";\n this.pos += 1;\n for (;;) {\n const c = this.text[this.pos];\n if (c === undefined) return this.stop(\"A closing quote is missing.\", start, this.text.length - start);\n if (c === quote) {\n if (this.syn.doubled && this.text[this.pos + 1] === quote) {\n out += quote;\n this.pos += 2;\n continue;\n }\n this.pos += 1;\n return literalDoc(out);\n }\n if (c === \"\\\\\" && !this.syn.doubled) {\n out += this.escape();\n continue;\n }\n out += c;\n this.pos += 1;\n }\n }\n\n private escape(): string {\n const start = this.pos;\n const c = this.text[start + 1] ?? \"\";\n if (c === \"u\") {\n const hex = this.text.slice(start + 2, start + 6);\n if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return this.stop(\"The escape \\\\u needs four hex digits.\", start, 2);\n this.pos += 6;\n return String.fromCharCode(Number.parseInt(hex, 16));\n }\n const out = Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : undefined;\n if (out === undefined) return this.stop(`The escape \\\\${c} is not valid.`, start, 2);\n this.pos += 2;\n return out;\n }\n\n private group(): Json {\n const open = this.pos;\n this.pos += 1;\n const inner = this.expr(0);\n this.skip();\n if (this.text[this.pos] !== \")\") {\n if (this.pos >= this.text.length) this.stop(\"A closing parenthesis is missing.\", open, 1);\n this.stop(\"A closing parenthesis is missing.\", this.pos, this.tokenLength());\n }\n this.pos += 1;\n return inner;\n }\n\n /** This method reads a name in backticks. Two backticks in the name are one backtick. */\n private quoted(): string {\n const start = this.pos;\n let out = \"\";\n this.pos += 1;\n for (;;) {\n const c = this.text[this.pos];\n if (c === undefined) return this.stop(\"A closing backtick is missing.\", start, this.text.length - start);\n if (c === \"`\") {\n if (this.text[this.pos + 1] !== \"`\") {\n this.pos += 1;\n return out;\n }\n this.pos += 1;\n }\n out += c;\n this.pos += 1;\n }\n }\n\n /** This method reads a name: a word operator, a call, a literal word or a reference. */\n private named(): Json {\n const start = this.pos;\n const plain = this.text[start] !== \"`\";\n const first = plain ? (this.at(NAME_AT) as string) : this.quoted();\n if (plain) {\n this.pos += first.length;\n const prefix = this.syn.prefix.get(first);\n if (prefix !== undefined && prefix.word) return opDoc(prefix, [this.expr(prefix.prec + 1)]);\n if (this.syn.binary.get(first)?.word === true) this.stop(`A term is missing before ${first}.`, start, first.length);\n }\n const path: Key[] = [first];\n let allPlain = plain;\n for (;;) {\n const back = this.pos;\n this.skip();\n if (!this.syn.fields || this.text[this.pos] !== \".\") {\n this.pos = back;\n break;\n }\n this.pos += 1;\n this.skip();\n if (this.text[this.pos] === \"`\") {\n path.push(this.quoted());\n allPlain = false;\n continue;\n }\n const name = this.at(NAME_AT);\n const digits = name === undefined ? this.at(DIGITS_AT) : undefined;\n if (name === undefined && digits === undefined) this.stop(\"A name is missing after the dot.\", this.pos, 0);\n this.pos += (name ?? (digits as string)).length;\n path.push(name ?? Number(digits));\n if (name === undefined) allPlain = false;\n }\n const back = this.pos;\n this.skip();\n if (this.text[this.pos] === \"(\") {\n if (!allPlain) this.stop(\"The name of a call is a plain name.\", start, back - start);\n return this.call(path.join(\".\"), start, back - start);\n }\n this.pos = back;\n if (plain && path.length === 1 && this.syn.words.has(first)) return literalDoc(this.syn.words.get(first));\n const full = plain && this.syn.roots.has(first) ? path : [this.syn.bare, ...path];\n return { type: \"ref\", value: full };\n }\n\n private call(name: string, start: number, nameLength: number): Json {\n const open = this.pos;\n const args: Json[] = [];\n this.pos += 1;\n this.skip();\n if (this.text[this.pos] === \")\") this.pos += 1;\n else {\n for (;;) {\n args.push(this.expr(0));\n this.skip();\n if (this.text.startsWith(this.syn.separator, this.pos)) {\n this.pos += this.syn.separator.length;\n continue;\n }\n if (this.text[this.pos] === \")\") {\n this.pos += 1;\n break;\n }\n if (this.pos >= this.text.length) this.stop(\"A closing parenthesis is missing.\", open, 1);\n this.stop(`A \"${this.syn.separator}\" or a closing parenthesis is missing.`, this.pos, this.tokenLength());\n }\n }\n const form = this.syn.forms.get(name);\n if (form !== undefined) {\n const most = form.fields?.length ?? Number.POSITIVE_INFINITY;\n if (args.length < form.min || args.length > most) {\n const range = most === form.min ? String(most) : most === Number.POSITIVE_INFINITY ? `${String(form.min)} or more` : `${String(form.min)} to ${String(most)}`;\n this.stop(`The form ${name} takes ${range} arguments.`, start, this.pos - start);\n }\n if (form.fields === undefined) return opDoc(form, args);\n const value: Record<string, Json> = {};\n args.forEach((arg, index) => {\n value[form.fields?.[index] as string] = arg;\n });\n return opDoc(form, value);\n }\n if (this.syn.ops !== true && !this.syn.ops.has(name)) this.stop(`This syntax has no function ${name}.`, start, nameLength);\n return { type: [\"ops\", ...name.split(\".\")], value: args };\n }\n}\n\n/**\n * This function reads a text into a document with the rules of a profile (SYNTAX.PARSE). It does not throw for a\n * bad text. The issue gives the offset, the length and a message (SYNTAX.SPAN).\n *\n * @param profile - The syntax profile.\n * @param text - The text.\n * @returns The document, or the issues of the text.\n * @throws {TypeError} The profile is not valid, for example an operator has two entries of the same place.\n */\nexport function parse(profile: SyntaxProfile, text: string): ParseResult {\n const parser = new Parser(compileProfile(profile), text);\n try {\n return { ok: true, doc: parser.parse() };\n } catch (error) {\n if (error instanceof Stop) return { ok: false, issues: [error.issue] };\n if (isStackOverflow(error)) return { ok: false, issues: [{ offset: parser.position(), length: 0, message: \"The text is too deep for the stack of the host.\" }] };\n throw error;\n }\n}\n\n// === Print ===\n\n/** The text of a part, from its document and its path in the value of the parent. */\ntype SubText = (child: unknown, path: readonly Key[]) => Result<string>;\n\ntype Shape =\n | { readonly tag: \"text\"; readonly text: string }\n | { readonly tag: \"op\"; readonly op: Op; readonly terms: readonly unknown[] }\n | { readonly tag: \"call\"; readonly name: string; readonly args: readonly (readonly [Key, unknown])[] }\n | { readonly tag: \"none\"; readonly reason: string };\n\nfunction none(reason: string): Shape {\n return { tag: \"none\", reason };\n}\n\nfunction quoteName(name: string): string {\n return `\\`${name.replaceAll(\"`\", \"``\")}\\``;\n}\n\nfunction wordFor(syn: Compiled, value: unknown): string | undefined {\n for (const [word, held] of syn.words) if (Object.is(held, value)) return word;\n return undefined;\n}\n\nfunction textOfString(syn: Compiled, value: string): string | undefined {\n const quote = syn.quote;\n if (quote === undefined) return undefined;\n if (syn.doubled) return `${quote}${value.replaceAll(quote, quote + quote)}${quote}`;\n const json = JSON.stringify(value);\n return quote === '\"' ? json : `'${json.slice(1, -1).replaceAll('\\\\\"', '\"').replaceAll(\"'\", \"\\\\'\")}'`;\n}\n\nfunction textOfNumber(syn: Compiled, value: number): string | undefined {\n if (!syn.numbers) return wordFor(syn, value);\n const negative = value < 0 || Object.is(value, -0);\n if (negative && !syn.signed) return wordFor(syn, value);\n if (Number.isFinite(value)) return negative ? `-${String(-value)}` : String(value);\n return wordFor(syn, value) ?? (Number.isNaN(value) ? undefined : negative ? \"-1e999\" : \"1e999\");\n}\n\nfunction literalShape(syn: Compiled, value: unknown): Shape {\n const text = typeof value === \"string\" ? textOfString(syn, value) : typeof value === \"number\" ? textOfNumber(syn, value) : wordFor(syn, value);\n return text === undefined ? none(`This syntax has no text for the literal ${describe(value)}.`) : { tag: \"text\", text };\n}\n\nfunction plainSegment(syn: Compiled, name: string): boolean {\n return NAME.test(name) && !syn.reserved.has(name) && !syn.patterns.some((p) => p.whole.test(name));\n}\n\nfunction laterSegment(step: unknown): string | undefined {\n if (typeof step === \"string\") return NAME.test(step) ? step : quoteName(step);\n return typeof step === \"number\" && Number.isSafeInteger(step) && step >= 0 ? String(step) : undefined;\n}\n\nfunction refShape(syn: Compiled, value: unknown): Shape {\n if (!Array.isArray(value) || value.length === 0) return none(\"The path of the reference is empty.\");\n for (const pattern of syn.patterns) {\n const text = pattern.write(value);\n if (text !== undefined) return { tag: \"text\", text };\n }\n const [root, ...rest] = value as readonly unknown[];\n const many = rest.length > 1 || (root !== syn.bare && rest.length > 0);\n if (many && !syn.fields) return none(\"This syntax has no field steps.\");\n const later = rest.slice(1).map(laterSegment);\n let first: string | undefined;\n let tail = later;\n if (root === syn.bare && typeof rest[0] === \"string\") first = plainSegment(syn, rest[0]) ? rest[0] : quoteName(rest[0]);\n else if (typeof root === \"string\" && syn.roots.has(root) && !syn.patterns.some((p) => p.whole.test(root))) {\n first = root;\n tail = rest.map(laterSegment);\n }\n if (first === undefined || tail.includes(undefined)) return none(\"This syntax has no text for the path of the reference.\");\n return { tag: \"text\", text: [first, ...tail].join(\".\") };\n}\n\nfunction callName(syn: Compiled, keys: readonly Key[]): string | undefined {\n if (keys.length === 0 || !keys.every((key) => typeof key === \"string\" && NAME.test(key))) return undefined;\n const name = keys.join(\".\");\n if (syn.forms.has(name) || syn.opWords.has(keys[0] as string)) return undefined;\n return syn.ops === true || syn.ops.has(name) ? name : undefined;\n}\n\nfunction formShape(form: Form, value: unknown): Shape | undefined {\n if (form.fields === undefined) {\n if (!Array.isArray(value) || value.length < form.min) return undefined;\n return { tag: \"call\", name: form.name, args: value.map((item, index) => [index, item] as const) };\n }\n if (!isRecord(value)) return undefined;\n // The fields that the value holds must be the first fields of the form, because the arguments go in order.\n const count = Object.keys(value).length;\n const present = form.fields.slice(0, count);\n if (count < form.min || present.length < count || !present.every((key) => Object.hasOwn(value, key))) return undefined;\n return { tag: \"call\", name: form.name, args: present.map((key) => [key, value[key]] as const) };\n}\n\nfunction opShape(syn: Compiled, key: string, terms: readonly unknown[]): Shape | undefined {\n for (const op of syn.byKind.get(key) ?? []) {\n const fits = op.fixity === \"infix\" ? terms.length === 2 || (op.assoc === \"flat\" && terms.length > 2) : terms.length === 1;\n if (fits) return { tag: \"op\", op, terms };\n }\n return undefined;\n}\n\n/** This function gives the shape of a document: a literal or a reference, an operator, a call, or no text. */\nfunction shapeOf(syn: Compiled, doc: unknown): Shape {\n if (!isEnvelope(doc)) return Array.isArray(doc) || isRecord(doc) ? none(\"This syntax has no text for a list or a record literal.\") : literalShape(syn, doc);\n if (doc.name !== undefined || doc.own !== undefined) return none(\"This syntax has no text for the header of a document.\");\n const path = typePath(doc.type);\n if (path === undefined) return none(\"This syntax has no text for a computed type.\");\n const value: unknown = doc.value;\n const name = path.join(\".\");\n if (name === \"lit\") return isEnvelope(value) || Array.isArray(value) || isRecord(value) ? none(\"This syntax has no text for a list or a record literal.\") : literalShape(syn, value);\n if (name === \"ext.undefined\") return literalShape(syn, undefined);\n if (name === \"ext.number\") {\n const numbers: Readonly<Record<string, number>> = { NaN: Number.NaN, Infinity: Number.POSITIVE_INFINITY, \"-Infinity\": Number.NEGATIVE_INFINITY, \"-0\": -0 };\n return typeof value === \"string\" && Object.hasOwn(numbers, value) ? literalShape(syn, numbers[value]) : none(\"The value of ext.number is not valid.\");\n }\n if (name === \"ref\") return refShape(syn, value);\n const key = JSON.stringify(path);\n const op = Array.isArray(value) ? opShape(syn, key, value) : undefined;\n if (op !== undefined) return op;\n for (const form of syn.formsByKind.get(key) ?? []) {\n const shape = formShape(form, value);\n if (shape !== undefined) return shape;\n }\n const called = path[0] === \"ops\" && Array.isArray(value) ? callName(syn, path.slice(1)) : undefined;\n if (called !== undefined) return { tag: \"call\", name: called, args: (value as readonly unknown[]).map((item, index) => [index, item] as const) };\n return none(`This syntax has no text for the kind ${name}.`);\n}\n\nfunction levelOf(syn: Compiled, doc: unknown): number {\n const shape = shapeOf(syn, doc);\n return shape.tag === \"op\" ? shape.op.prec : Number.POSITIVE_INFINITY;\n}\n\n/** This function tells if a term needs parentheses in its position, so that `parse` reads the same tree. */\nfunction needsGroup(op: Op, index: number, level: number): boolean {\n if (op.fixity === \"postfix\") return level < op.prec;\n if (op.fixity === \"prefix\" || op.assoc === \"none\" || op.assoc === \"flat\") return level <= op.prec;\n const looser = op.assoc === \"left\" ? index === 0 : index !== 0;\n return looser ? level < op.prec : level <= op.prec;\n}\n\nfunction opText(syn: Compiled, op: Op, terms: readonly unknown[], sub: SubText): Result<string> {\n const texts: string[] = [];\n for (let index = 0; index < terms.length; index += 1) {\n const term = terms[index];\n const result = sub(term, [index]);\n if (!result.ok) return result;\n let text = result.value;\n const signedDigit = op.fixity === \"prefix\" && op.symbol === \"-\" && syn.signed && /^[0-9]/.test(text);\n if (needsGroup(op, index, levelOf(syn, term)) || signedDigit) text = `(${text})`;\n texts.push(text);\n }\n const [only = \"\"] = texts;\n if (op.fixity === \"prefix\") return ok(op.word || /^[^A-Za-z0-9_(\"'`$]/.test(only) ? `${op.symbol} ${only}` : `${op.symbol}${only}`);\n if (op.fixity === \"postfix\") return ok(op.word ? `${only} ${op.symbol}` : `${only}${op.symbol}`);\n return ok(texts.join(` ${op.symbol} `));\n}\n\n/** This function writes one document. `sub` gives the text of each part. */\nfunction printNode(syn: Compiled, doc: unknown, sub: SubText): Result<string> {\n const shape = shapeOf(syn, doc);\n if (shape.tag === \"text\") return ok(shape.text);\n if (shape.tag === \"none\") return fail(\"#VALUE!\", shape.reason);\n if (shape.tag === \"op\") return opText(syn, shape.op, shape.terms, sub);\n const texts: string[] = [];\n for (const [key, arg] of shape.args) {\n const result = sub(arg, [key]);\n if (!result.ok) return result;\n texts.push(result.value);\n }\n return ok(`${shape.name}(${texts.join(`${syn.separator} `)})`);\n}\n\nfunction printTree(syn: Compiled, doc: unknown, place: readonly Key[]): Result<string> {\n const result = printNode(syn, doc, (child, path) => printTree(syn, child, [...place, ...path]));\n return result.ok || result.error.place !== undefined ? result : fail(result.error.code, result.error.reason, { place });\n}\n\n/**\n * This function writes a document as text with the rules of a profile (SYNTAX.PRINT). It writes the fewest\n * parentheses that keep the tree. `parse` reads the text back to the same document (SYNTAX.ROUNDTRIP).\n *\n * @param profile - The syntax profile.\n * @param doc - The document.\n * @returns The text, or `#VALUE!` at the place of a document that the profile cannot write.\n * @throws {TypeError} The profile is not valid.\n */\nexport function print(profile: SyntaxProfile, doc: unknown): Result<string> {\n const syn = compileProfile(profile);\n try {\n return printTree(syn, doc, []);\n } catch (error) {\n if (isStackOverflow(error)) return fail(\"#DEPTH!\", \"The document is too deep for the stack of the host.\", { cause: error });\n throw error;\n }\n}\n\n/**\n * This function makes the part of a merge that adds the verb `format` to a machine (D23, D41). Its default writes\n * each document with the printer of the profile. A part gives its own text through the ladder, thus an own entry or\n * a kind entry of `format` still wins.\n *\n * @param profile - The syntax profile.\n * @returns The part for `mergeMachines`.\n */\nexport function syntaxFormat(profile: SyntaxProfile): MachinePart {\n const syn = compileProfile(profile);\n const code: EvalFn = ({ doc, parts, place }) => {\n const byPath = new Map<string, Part>(parts.map((part) => [JSON.stringify(part.path), part]));\n return printNode(syn, doc, (child, path) => {\n const part = byPath.get(JSON.stringify(path));\n if (part === undefined) return printTree(syn, child, [...place, ...path]);\n const result = part.evaluate();\n if (!result.ok) return result;\n return typeof result.value === \"string\" ? ok(result.value) : fail(\"#VALUE!\", `The verb format of a part gave ${describe(result.value)}, not a text.`, { place: [...place, ...path] });\n });\n };\n return { world: { defaults: { format: \"syntax.format\" } }, evaluators: { \"syntax.format\": code } };\n}\n","import { type Envelope, type Json, type Key, isEnvelope, isRecord, typeName } from \"./doc.ts\";\nimport { ask } from \"./ladder.ts\";\nimport { type AttributeDeclaration, type CapsRule, type Kind, type TreeContract, equationType, lookupKind } 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 { type AttributeRung, STD_EVALUATORS } from \"./stdlib.ts\";\nimport { type EvalError, type Failed, type Result, Failure, describe, 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 Perform,\n type RunFn,\n type RunInput,\n type RunPart,\n type Steps,\n makeContext,\n permits,\n placeText,\n waitedReason,\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 /** The mock of the host (RUN.MOCK). It answers each effect at once. Without it, an effect gives its payload. */\n readonly perform?: Perform;\n /**\n * The verb that goes up the ladder at each document, as in `prepare`. The default is `eval`. The reference reads\n * each verb by the same rules (VERB.AGREE).\n */\n readonly verb?: string;\n}\n\n/** The scope of the addresses of effects (RUN.ADDRESS): the root of the evaluation, or one item of `all`. */\ninterface Scope {\n /** The text before each address of the scope. */\n readonly prefix: string;\n /** The number of earlier effects at each place of the scope, by the text of the place. */\n readonly counts: Map<string, number>;\n /** The number of earlier uses of `all` in the scope. */\n alls: number;\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 readonly perform: Perform | undefined;\n /** The verb that goes up the ladder at each document. Each part evaluates with the same verb. */\n readonly verb: string;\n /** The scope of the code that evaluates at this time. `all` changes it for each item. */\n scope: Scope;\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 of the verb (LADDER.*, VERB.LADDER), an\n * evaluator and the shape 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, env.verb, 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/**\n * This function gives the effects that two lists of capabilities both permit (CAP.ONLY). The reference reads the rule\n * from SPEC directly, and not from the intersection of the plan. Thus `agree` finds a bug in either one (D15).\n */\nfunction bothPermit(a: readonly Cap[], b: readonly Cap[]): readonly Cap[] {\n const out: Cap[] = [];\n for (const cap of [...a, ...b]) if (permits(a, cap) && permits(b, cap) && !permits(out, cap)) out.push(cap);\n return out;\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 = bothPermit(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/**\n * This function causes an effect when the capabilities permit it (RUN.CAP, CAP.HOOK). It records the effect with its\n * address (RUN.ADDRESS) and its outcome (RUN.OUTCOME). The mock answers the effect at once (RUN.MOCK). Without a\n * mock, the effect gives its payload (RUN.EVAL).\n */\nfunction cause(env: Env, ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\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 const at = placeText(place);\n const count = env.scope.counts.get(at) ?? 0;\n env.scope.counts.set(at, count + 1);\n const effect: { -readonly [K in keyof Effect]: Effect[K] } = {\n index: env.effects.length,\n kind: text,\n path: keys,\n payload,\n node: -1,\n at: 0,\n place,\n context: ctx,\n address: `${env.scope.prefix}${at}#${count}`,\n };\n env.effects.push(effect);\n effect.outcome = answer(env.perform, effect, place);\n return effect.outcome;\n}\n\n/**\n * This function gives the answer of the mock to an effect. A throw gives `#CALC!` with the cause, and a `Failure`\n * gives its own error value. A promise gives `#CALC!`, because an evaluation does not wait.\n */\nfunction answer(perform: Perform | undefined, effect: Effect, place: readonly Key[]): Result {\n if (perform === undefined) return ok(effect.payload);\n let given: unknown;\n try {\n given = perform(effect);\n } catch (error) {\n if (error instanceof Failure) return placed({ ok: false, error: error.error }, place);\n return fail(\"#CALC!\", `The host failed the effect ${effect.kind}: ${describe(error)}`, { place, cause: error });\n }\n if (!(given instanceof Promise)) return ok(given);\n void given.catch(() => undefined);\n return fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place });\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, seen.kindText);\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[], kindText: string): 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!\", waitedReason(kindText), { 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 machine: env.machine,\n ...(at.address ? { address: true } : {}),\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: (kind, payload) => cause(env, at.ctx, kind, payload, at.place),\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 machine: env.machine,\n resolve: (path, options) => resolveFully(env.machine, at.ctx, path, options),\n effect: function* (kind, payload) {\n return cause(env, at.ctx, kind, payload, at.place);\n },\n all: (list, options) => together(env, 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 *\n * Each part has its own scope of addresses. Its prefix names the use of `all` in the scope around it, and the part\n * (RUN.ADDRESS).\n */\nfunction* together(env: Env, 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 const outer = env.scope;\n const address = `${outer.prefix}all${outer.alls}`;\n outer.alls += 1;\n let failed = false;\n for (let index = 0; index < list.length && !failed && waiting.length < limit; index += 1) {\n let result: Result | undefined;\n env.scope = { prefix: `${address}.${index}/`, counts: new Map(), alls: 0 };\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 } finally {\n env.scope = outer;\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 the answer of the mock or its payload, and a part that waits gives `#CALC!`.\n *\n * The verb of the options goes up the ladder at each document, as in `prepare`. Each verb has the same rules: the\n * ladder, the contract of the kind and the sealed parts (VERB.AGREE).\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, a list for the effects, a mock and the verb.\n * @returns The result.\n */\nexport function reference(machine: Machine, doc: unknown, context: Context = makeContext(), options: ReferenceOptions = {}): Result {\n const env: Env = {\n machine,\n definitions: options.definitions ?? {},\n effects: options.effects ?? [],\n maxDepth: machine.maxDepth ?? 1000,\n perform: options.perform,\n verb: options.verb ?? \"eval\",\n scope: { prefix: \"\", counts: new Map(), alls: 0 },\n };\n const ctx = context.world === null ? { ...context, world: worldThing(machine.world) } : context;\n // A node of a tree reads the definitions of this evaluation for its equations (TREE.LADDER).\n activeEnvs.push(env);\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 } finally {\n activeEnvs.pop();\n }\n}\n\n/** The evaluations of the reference that run at this time, the innermost last. */\nconst activeEnvs: Env[] = [];\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 tree contract of the kind of the node (D42). */\n readonly contract: TreeContract | undefined;\n /** The type of a bare equation: the type `of` of the parts of the kind. */\n readonly of: string | undefined;\n /** The parent node in the same tree, for the rungs `parent` and `copy`. */\n readonly up: RefNode | undefined;\n /** The evaluation of the reference that made the node. Its equations evaluate with its definitions. */\n readonly env: Env | undefined;\n /** The host thing of the node. */\n thing: HostThing;\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 = /* @__PURE__ */ 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/**\n * TREE.LADDER: an equation of the kind of a node evaluates in the reference. It gets the node as `self`, the names of\n * its rung and no capabilities. A bare equation gets the type `of` of the parts of the kind.\n */\nfunction equationOf(node: RefNode, term: Json, names: Readonly<Record<string, unknown>>): Result {\n const env = node.env;\n if (env === undefined) return fail(\"#NOEVAL\", \"The evaluation of an equation needs the machine.\");\n const ctx: Context = { ...node.ctx, names, caps: [], self: node.thing };\n return reference(env.machine, term, ctx, { definitions: env.definitions, ...(node.of === undefined ? {} : { declaredType: node.of }) });\n}\n\nfunction termIn<T>(table: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return table === undefined || !Object.hasOwn(table, name) ? undefined : table[name];\n}\n\n/** TREE.DOWN: the names of a child for an equation of `down` of its parent: `child`, `index` and `prev`. */\nfunction namesOfChild(up: RefNode, child: RefNode): Result {\n const children = attributeOf(up, \"children\");\n if (children !== undefined && !children.ok) return children;\n const list: readonly unknown[] = children !== undefined && Array.isArray(children.value) ? children.value : [];\n const index = list.indexOf(child.thing);\n return ok({ child: child.thing, index: index < 0 ? null : index, prev: index > 0 ? list[index - 1] : null });\n}\n\n/** TREE.FOLD: the unit, then `combine` with the attribute of each node of this tree in the list `children`. */\nfunction foldOf(node: RefNode, name: string, fold: NonNullable<AttributeDeclaration[\"fold\"]>): Result {\n let acc = equationOf(node, fold.unit, {});\n if (!acc.ok) return acc;\n const children = attributeOf(node, \"children\");\n if (children === undefined) return acc;\n if (!children.ok) return children;\n if (!Array.isArray(children.value)) return fail(\"#VALUE!\", `The fold of ${name} needs a list in children.`);\n for (const item of children.value) {\n const child = refNodeOf(item);\n if (child === undefined || child.tree !== node.tree) continue;\n const value = attributeOf(child, name);\n if (value === undefined) return fail(\"#N/A\", `No rung gives ${nameOfAttribute(child, name)}.`);\n if (!value.ok) return value;\n acc = equationOf(node, fold.combine, { acc: acc.value, item: value.value });\n if (!acc.ok) return acc;\n }\n return acc;\n}\n\n/**\n * TREE.LADDER: the rungs of the ladder of an attribute, in their order. A rung gives `undefined` when it does not\n * answer, and the next rung then tries.\n */\nconst REF_RUNGS: readonly (readonly [AttributeRung, (node: RefNode, name: string) => Result | undefined])[] = [\n [\"own\", (node, name) => node.parts.find((item) => item.key === name)?.evaluate({ ...node.ctx, self: node.thing })],\n [\n \"kind\",\n (node, name) => {\n const term = termIn(node.contract?.equations, name);\n return term === undefined ? undefined : equationOf(node, term, {});\n },\n ],\n [\n \"parent\",\n (node, name) => {\n const up = node.up;\n const term = up === undefined ? undefined : termIn(up.contract?.down, name);\n if (up === undefined || term === undefined) return undefined;\n const names = namesOfChild(up, node);\n return names.ok ? equationOf(up, term, names.value as Readonly<Record<string, unknown>>) : names;\n },\n ],\n [\"copy\", (node, name) => (node.up !== undefined && termIn(node.contract?.attributes, name)?.copy === true ? attributeOf(node.up, name) : undefined)],\n [\n \"default\",\n (node, name) => {\n const declared = termIn(node.contract?.attributes, name);\n if (declared?.fold !== undefined) return foldOf(node, name, declared.fold);\n return declared?.default === undefined ? undefined : equationOf(node, declared.default, {});\n },\n ],\n];\n\n/** TREE.ONCE, TREE.MEMO and TREE.CYCLE: the result of one attribute, or `undefined` when no rung of its ladder answers. */\nfunction attributeOf(node: RefNode, 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 node.pending.add(name);\n inEvaluation.push({ node, name });\n try {\n for (const [, rung] of REF_RUNGS) {\n const result = rung(node, name);\n if (result === undefined) continue;\n node.values.set(name, result);\n return result;\n }\n return undefined;\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, 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. The node\n * reads `self` only through `resolve` (C4, TREE.SELF).\n */\nconst treeDefinition: EvalFn = ({ parts, context, kind, place, machine, typePath, resolve: walk }) => {\n const reached = walk([\"self\"]);\n const parent: Thing | undefined = reached.ok ? reached.thing : undefined;\n const outer = refNodeOf(parent);\n const nested = outer !== undefined && outer.tree.open;\n const found = machine === undefined || typePath.length === 0 ? undefined : lookupKind(machine.world, typePath);\n const contract = found?.ok === true ? found.kind.tree : undefined;\n const of = contract === undefined || found?.ok !== true ? undefined : equationType(found.kind);\n const node: RefNode = {\n tree: nested ? outer.tree : { open: true },\n kind,\n place,\n parts,\n ctx: context,\n contract,\n of,\n up: nested ? outer : undefined,\n env: activeEnvs[activeEnvs.length - 1],\n thing: null as unknown as HostThing,\n values: new Map(),\n pending: new Set(),\n };\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 parent;\n if (key === \"type\") return kind;\n const result = attributeOf(node, String(key));\n if (result === undefined || result.ok) return result?.ok === true ? result.value : undefined;\n throw new Failure(result.error);\n },\n has: (key) => key === \"parent\" || key === \"type\" || parts.some((part) => part.key === String(key)) || node.values.has(String(key)),\n toJson: () => {\n const result = jsonOfNode(node, self, []);\n if (result.ok) return result.value;\n throw new Failure(result.error);\n },\n };\n node.thing = self;\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 = /* @__PURE__ */ 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, machine }) => {\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, machine?.domains);\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 = /* @__PURE__ */ 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, equalWith } from \"./doc.ts\";\nimport type { Context } from \"./deref.ts\";\nimport { type EvalError, type Result, isStackOverflow, thrown } from \"./errors.ts\";\nimport { type Effect, type Machine, type Perform, 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 * - `folds`: a second plan with the other choice of folds (PLAN.FOLD). It has no folds when the plan has them, and\n * it has folds when the option `observe` stops the folds of the plan.\n * - `other`: the second tier of a language, from the option `other`.\n */\nexport type Tier = \"reference\" | \"traced\" | \"again\" | \"folds\" | \"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/** What `agree` gives the second tier of a language beside the document and the context. */\nexport interface TierInput {\n /** The mock of the host, when `agree` has one (AGREE.MOCK). The tier answers each effect with it. */\n readonly perform?: Perform;\n /** The verb of `agree`, when its options name one (VERB.AGREE). A tier that does not serve the verb fails. */\n readonly verb?: string;\n}\n\n/** The options of `agree`. */\nexport interface AgreeOptions {\n /** The type of a bare root value. */\n readonly declaredType?: string;\n /**\n * The verb of each tier, as in `prepare`. The default is `eval`. The plan, the reference, the traced evaluation and a\n * second evaluation each ask the ladder for this verb (VERB.AGREE). The second tier of a language gets it in its\n * input.\n */\n readonly verb?: string;\n /** The definitional code of the compiled evaluators of the machine, for the reference. */\n readonly definitions?: Definitions;\n /**\n * The tiers to compare with the plan. The default is the reference, the traced evaluation, a second evaluation and\n * the plan with the other choice of folds.\n */\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 * @param input - The mock of the host and the verb, when `agree` has them.\n * @returns The result, or the result with the effects.\n */\n readonly other?: (doc: unknown, context: Context, input: TierInput) => Result | TierResult;\n /**\n * The mock of the host (RUN.MOCK, AGREE.MOCK). Each tier gets it, thus the tiers agree on documents with effects. A\n * mock must give the same answer to the same effect, because each tier asks it again.\n */\n readonly perform?: Perform;\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. A fold moves the calls of a part to the compilation, thus with this option the plan has\n * no folds. The tier `folds` then has folds, and `agree` does not compare its calls.\n *\n * @returns What the host saw.\n */\n readonly observe?: () => unknown;\n}\n\n/** The tiers that `agree` compares when its options name none. */\nconst DEFAULT_TIERS: readonly Exclude<Tier, \"other\">[] = /* @__PURE__ */ Object.freeze([\"reference\", \"traced\", \"again\", \"folds\"]);\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` and `sameResult` use the same walk (D20). `docEquals` has no rules for closures, for `Held` values and\n * for a rule of the caller. `sameResult` is for an early cutoff, thus a closure is the same there only as itself, and\n * two errors also need the same reason.\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 return equalWith(a, b, equal === undefined ? sameInTiers : (x, y) => equal(x, y) ?? sameInTiers(x, y));\n}\n\n/** The rules of `sameValue` for the values that two tiers make again: closures and held errors. */\nfunction sameInTiers(x: unknown, y: unknown): boolean | undefined {\n if (isClosure(x) || isClosure(y)) return isClosure(x) && isClosure(y) && docEquals(closureParams(x), closureParams(y));\n if (x instanceof Held || y instanceof Held) return x instanceof Held && y instanceof Held && errorDiffers(x.error, y.error, false) === undefined;\n return undefined;\n}\n\nconst CLOSURE = /* @__PURE__ */ 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/**\n * This function gives the difference of two lists of effects, or `undefined` when they agree (EFFECT.ORDER). When both\n * tiers record the address or the outcome of an effect, these must agree too (AGREE.MOCK).\n */\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 if (x.address !== undefined && y.address !== undefined && x.address !== y.address) {\n return `The effect ${index} has the address ${x.address} in the plan, and ${y.address} in the tier.`;\n }\n const why = x.outcome !== undefined && y.outcome !== undefined ? resultDiffers(x.outcome, y.outcome, options) : undefined;\n if (why !== undefined) return `The outcome of the effect ${index} differs. ${why}`;\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`. Each tier gets the mock of the option `perform` (AGREE.MOCK).\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, the second tier and the mock.\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 = {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n };\n const mock = options.perform === undefined ? {} : { perform: options.perform };\n const tierInput: TierInput = { ...mock, ...(options.verb === undefined ? {} : { verb: options.verb }) };\n const observe = options.observe;\n observe?.();\n // A fold moves host calls to the compilation, thus a plan whose calls the host compares has no folds (PLAN.FOLD).\n const folds = observe === undefined;\n const plan = prepare(machine, doc, { ...declared, fold: folds });\n const effects: Effect[] = [];\n const result = plan.evaluate(context, { effects, ...mock });\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 ?? DEFAULT_TIERS) {\n let other: Result;\n let otherEffects: Effect[] = [];\n if (tier === \"reference\") {\n other = reference(machine, doc, context, { ...declared, ...mock, effects: otherEffects, ...(options.definitions === undefined ? {} : { definitions: options.definitions }) });\n } else if (tier === \"traced\") {\n const traced = evaluate(machine, doc, context, { ...declared, ...mock });\n other = traced.result;\n otherEffects = [...traced.effects];\n } else if (tier === \"folds\") {\n other = prepare(machine, doc, { ...declared, fold: !folds }).evaluate(context, { effects: otherEffects, ...mock });\n if (observe !== undefined) {\n // The folds of this tier call the host when it compiles. Thus only the result and the effects compare.\n observe();\n if (overflowed(result) || overflowed(other)) continue;\n const why = resultDiffers(result, other, options) ?? effectsDiffer(effects, otherEffects, options);\n if (why !== undefined) return { ok: false, tier, plan: result, other, reason: why };\n continue;\n }\n } else {\n other = plan.evaluate(context, { effects: otherEffects, ...mock });\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, tierInput);\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 // A kind with the verb step walks a step document. With a default of step, each other kind walks one too (GEN.STEPS).\n const defaultStep = Object.hasOwn(world.defaults, \"step\");\n const stepTypes = types.filter((type) => {\n const found = lookupKind(world, type);\n return found.ok && (defaultStep || 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 /**\n * A path from a root (D10). It uses the names in scope, and sometimes a step document. The kind of a step document\n * has the verb `step`, or the default of the world for `step` serves it.\n */\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","import { type Envelope, type Json, type Key, type TypeRef, docEquals, isEnvelope, isKey, typeName } from \"./doc.ts\";\nimport { type Cap, type Context, type Resolution, type ResolveOptions, resolve } from \"./deref.ts\";\nimport { type Result, describe, fail, ok, placed, thrown } from \"./errors.ts\";\nimport {\n type AllOptions,\n type Code,\n type CompileInput,\n type CompiledEvaluator,\n type CompiledPart,\n type CompiledRunner,\n type Effect,\n type EvalFn,\n type EvalInput,\n type Evaluator,\n type Machine,\n type Part,\n type Perform,\n type RunCode,\n type RunFn,\n type RunInput,\n type RunPart,\n type Runner,\n type Runtime,\n type Steps,\n capKeys,\n makeContext,\n permits,\n rootContext,\n} from \"./evaluate.ts\";\nimport { type PartSlot, type Split, pathMatches, scopesOf, splitParts } from \"./parts.ts\";\nimport { type Definitions, STD_DEFINITIONS } from \"./reference.ts\";\nimport { STD_EVALUATORS } from \"./stdlib.ts\";\nimport { sameValue } from \"./agree.ts\";\nimport { type Random, random } from \"./generate.ts\";\nimport { type Kind, type LazyRule, type Shape, type World, type WorldEntry, effectsOfVerb, isKind, isNamespace, lookupKind } from \"./world.ts\";\n\n/*\n * The conformance tests of one evaluator (K92, R7 P3, D36). `conforms` calls the code of one evaluator or runner\n * directly, without the kernel. It gives the code probe parts and a probe runtime. A probe part records each call, its\n * context and its order, and it gives a chosen result. The probe runtime records each resolution and each effect. The\n * checks compare these records with the contract of the kind and with the obligations C1 to C8 of SEMANTICS.md.\n */\n\n/**\n * An obligation that `conforms` checks. `C1` to `C8` are the obligations of host code in `docs/SEMANTICS.md`. `local`\n * and `agree` are two premises of the simulation of the plan (SIM-PLAN).\n *\n * - `C1`: each context that the code gives a part, or an effect, has only the capabilities of its document.\n * - `C2`: the code causes only the effects that the contract of the kind declares.\n * - `C3`: each eager part evaluates when the result is a value, and a lazy part evaluates only when its result counts.\n * - `C4`: the code of a pure kind causes no effect, and it reads the context only through `resolve`.\n * - `C5`: the code reads its parts only through their handles, not through the JSON of the document.\n * - `C6`: only a runner waits, and a runner passes each wait of its parts and its effects through.\n * - `C7`: the code binds for a part each name that the scope rules give the part, and no other name.\n * - `C8`: compiled code gives the result of code that compiles again at the time of the evaluation.\n * - `local`: the code keeps no state from one call to the next.\n * - `agree`: compiled code gives the result of its definition for the reference interpreter.\n */\nexport type Obligation = \"C1\" | \"C2\" | \"C3\" | \"C4\" | \"C5\" | \"C6\" | \"C7\" | \"C8\" | \"local\" | \"agree\";\n\n/** The probe of a finding: the document, the result of each probe part, the capabilities and the handler. */\nexport interface ConformProbe {\n /** The text of the type of the document. */\n readonly type: string;\n /** The document. A probe document takes the place of each part. */\n readonly doc: Envelope;\n /** The result of each probe part, by the key of the part. */\n readonly results: Readonly<Record<string, Result>>;\n /** The keys of the probe parts that wait for the host before they give their result. Only a run has them. */\n readonly waits: readonly string[];\n /** The capabilities of the context of the document. */\n readonly caps: readonly Cap[];\n /** `true` in a run, in which the host does each effect and a part can wait. */\n readonly running: boolean;\n}\n\n/** One obligation that the code breaks, with the reason and the first probe that shows it. */\nexport interface Finding {\n readonly obligation: Obligation;\n /** One or two sentences that tell what the code did. */\n readonly reason: string;\n readonly probe: ConformProbe;\n}\n\n/** The options of `conforms`. */\nexport interface ConformOptions {\n /**\n * The verb that the evaluator serves. The default is `eval`. The facts `pure` and `lazy` of a contract describe only\n * `eval`, thus `conforms` checks C3 and C4 only for `eval` (D23). `conforms` checks C2 for each verb that the\n * contract declares effects for: `eval`, and each verb with an entry in `verbEffects` (D49).\n */\n readonly verb?: string;\n /**\n * The types of the probe documents. The default is each kind of the world whose verb names the evaluator. A fallback\n * kind gives the key `probe`, for example `[\"ops\", \"probe\"]`. The contract of the kind of each type applies.\n */\n readonly types?: readonly TypeRef[];\n /**\n * More values of probe documents, by the text of their type. A probe document takes the place of each part of such a\n * value. Use them for data that the code needs, for example the key of `write`.\n */\n readonly values?: Readonly<Record<string, readonly Json[]>>;\n /**\n * The results that a probe part can give. The default holds numbers, truth values, a text, `null`, a list, a\n * record, a function and two errors.\n */\n readonly results?: readonly Result[];\n /**\n * The definitional code of the compiled evaluators and runners, as for `reference`. A standard evaluator gets its\n * definition from `STD_DEFINITIONS`.\n */\n readonly definitions?: Definitions;\n /** The capabilities of half of the probes. The other half has none. The default is the declared effects and `probe`. */\n readonly caps?: readonly Cap[];\n /** The names of the context of each probe. */\n readonly names?: Readonly<Record<string, unknown>>;\n /** The seed of the random results. The same seed gives the same probes. The default is 1. */\n readonly seed?: number;\n /** The count of probes with random results for each probe document. The default is 12. */\n readonly runs?: number;\n /** The mock of the host (RUN.MOCK). It answers each effect at once. Without it, an effect gives its payload. */\n readonly perform?: Perform;\n /**\n * This function compares two values that the rules of `sameValue` do not know, as in `agree`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @returns `true` or `false`, or `undefined` for the rules of `sameValue`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n}\n\n/** The order of the obligations in the list of findings. */\nconst ORDER: readonly Obligation[] = [\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"local\", \"agree\"];\n\n/** A function in the results of the probe parts. It gives the count of its arguments. */\nconst PROBE_FN = (...args: readonly unknown[]): number => args.length;\n\n/** The arguments of a call of a function that a result gives. */\nconst PROBE_ARGS: readonly unknown[] = [1, 2];\n\n/** The default results of the probe parts. */\nconst RESULTS: readonly Result[] = [\n { ok: true, value: 1 },\n { ok: true, value: 2 },\n { ok: true, value: true },\n { ok: true, value: false },\n { ok: true, value: \"a\" },\n { ok: true, value: null },\n { ok: true, value: [1, 2] },\n { ok: true, value: { a: 1 } },\n { ok: true, value: PROBE_FN },\n { ok: false, error: { code: \"#VALUE!\", reason: \"The probe part fails.\" } },\n { ok: false, error: { code: \"#N/A\", reason: \"The probe part has no value.\" } },\n];\n\n/** The result of a probe part without a chosen result. */\nconst NO_RESULT: Result = { ok: true, value: null };\n\n/** The result of a runner that the probe driver stops. */\nconst STOPPED: Result = { ok: false, error: { code: \"#CALC!\", reason: \"The probe driver stopped the runner.\" } };\n\n/** The result of an item of `all` after a failure with `failFast`. */\nconst ABORTED: Result = { ok: false, error: { code: \"#ABORT\", reason: \"The part stopped: a part before it failed, and the parts run with failFast.\" } };\n\n/** The default names of the context of each probe. The generated names of a value (`a`, `b` and `c`) are other names. */\nconst NAMES: Readonly<Record<string, unknown>> = { x: \"outer x\", y: 2.5, z: [\"outer\"] };\n\n/** The values of a document whose kind has no parts. */\nconst DATA: readonly Json[] = [1, \"a\", true, null, [\"names\", \"x\"], { a: 1 }, [\"names\", \"y\", \"c\"]];\n\n/** The count of generated values of each type. */\nconst VARIANTS = 8;\n\n/** The lengths of a generated list. */\nconst LENGTHS: readonly number[] = [2, 0, 1, 3];\n\n/** The texts of generated data. */\nconst TEXTS: readonly string[] = [\"a\", \"b\", \"c\"];\n\n/** The place of each probe document. */\nconst PLACE: readonly Key[] = [];\n\n/** No capabilities: the context of half of the probes. */\nconst NO_CAPS: readonly Cap[] = [];\n\n/** The code under test, in one of its four forms. */\ntype Under =\n | { readonly form: \"eval\"; readonly fn: EvalFn }\n | { readonly form: \"compile\"; readonly compile: (input: CompileInput) => Code }\n | { readonly form: \"run\"; readonly fn: RunFn }\n | { readonly form: \"compileRun\"; readonly compile: (input: CompileInput) => RunCode };\n\n/** The split of a value that has the shape of its kind. */\ntype SplitOk = Extract<Split, { readonly ok: true }>;\n\n/** One probe document, with what its contract tells about each part. */\ninterface Sample {\n readonly type: string;\n readonly typePath: readonly Key[];\n readonly kind: Kind;\n /** The document, with a probe document at the place of each part. */\n readonly doc: Envelope;\n readonly split: SplitOk;\n /** The same document with other JSON in each probe document (C5). */\n readonly other: Envelope;\n readonly otherSplit: SplitOk;\n /** `true` for each part that a lazy rule covers. */\n readonly lazy: readonly boolean[];\n /** The names that the scope rules give each part. */\n readonly names: readonly (readonly string[])[];\n}\n\n/** The results, the waits and the capabilities of one evaluation of a probe document. */\ninterface Scenario {\n readonly results: readonly Result[];\n readonly waits: readonly boolean[];\n readonly caps: readonly Cap[];\n readonly running: boolean;\n}\n\n/** One call of a probe part. */\ninterface Call {\n readonly part: number;\n /** The function that the code called: `evaluate` of a handle, or `code` or `run` of a compiled part. */\n readonly via: \"evaluate\" | \"code\" | \"run\";\n /** The context that the code gave the part. */\n readonly context: Context;\n /** `true` for a call in a function that the result gives, after the evaluation. */\n readonly later: boolean;\n}\n\n/** One effect that the code caused. */\ninterface Caused {\n readonly kind: string;\n readonly payload: unknown;\n readonly context: Context;\n}\n\n/** One resolution that the code asked for. */\ninterface Asked {\n readonly path: readonly unknown[];\n readonly found: Resolution;\n}\n\n/** One wait of a probe part or of an effect in a run. */\ninterface Wait {\n readonly what: string;\n readonly answer: unknown;\n /** `true` after the runner gave the promise to the driver. */\n seen: boolean;\n /** `true` after the probe got its answer. */\n done: boolean;\n}\n\n/** The state of `conforms` for one evaluator. */\ninterface Env {\n readonly machine: Machine;\n readonly name: string;\n readonly verb: string;\n readonly under: Under;\n readonly definition: Under | undefined;\n readonly runner: boolean;\n readonly results: readonly Result[];\n readonly names: Readonly<Record<string, unknown>>;\n readonly runs: number;\n readonly random: Random;\n readonly perform: Perform | undefined;\n readonly equal: ((a: unknown, b: unknown) => boolean | undefined) | undefined;\n readonly found: Map<Obligation, Finding>;\n}\n\n/** The facts of the kind of one type, as the contract and the hook `facts` of the machine give them. */\ninterface Contract {\n readonly declared: readonly Cap[];\n readonly pure: boolean;\n readonly lazy: readonly LazyRule[] | undefined;\n /** `true` when the facts describe the verb: they describe only `eval`. */\n readonly describes: boolean;\n /** `true` when the contract declares the effects of the verb: for `eval`, and for a verb in `verbEffects`. */\n readonly declares: boolean;\n readonly caps: readonly Cap[];\n}\n\n/**\n * The probe runtime of one evaluation, and its record. It records each call of a part, each effect and each\n * resolution. In a run, a probe part and an effect wait with a promise that the probe driver answers at once.\n */\nclass Shot implements Runtime {\n readonly calls: Call[] = [];\n readonly caused: Caused[] = [];\n readonly asked: Asked[] = [];\n /** The problems of the waits (C6). */\n readonly problems: string[] = [];\n readonly waits = new Map<Promise<unknown>, Wait>();\n /** The results of the calls of a function that the result gives. */\n readonly later: Result[] = [];\n result: Result = NO_RESULT;\n private afterwards = false;\n readonly running: boolean;\n\n constructor(\n readonly machine: Machine,\n /** `true` when the code under test is a runner. */\n readonly runner: boolean,\n readonly scenario: Scenario,\n /** The context of the document. */\n readonly context: Context,\n /** The key of each part, for the reasons. */\n readonly keys: readonly string[],\n private readonly perform: Perform | undefined,\n /** The resolutions of an earlier evaluation. Each resolution with the same path gets the same answer (C4). */\n private readonly replay: readonly Asked[] | undefined,\n ) {\n this.running = scenario.running;\n }\n\n resolve(ctx: Context, path: readonly unknown[], options?: ResolveOptions): Resolution {\n const old = this.replay?.[this.asked.length];\n const found = old !== undefined && docEquals(old.path, path) ? old.found : resolve(this.machine, ctx, path, options);\n this.asked.push({ path, found });\n return found;\n }\n\n /** This function records a call of a part, and gives the result that the probe part gives. */\n call(part: number, via: Call[\"via\"], ctx: Context): Result {\n this.calls.push({ part, via, context: ctx, later: this.afterwards });\n const key = this.keys[part] ?? String(part);\n if (via === \"run\" && !this.runner) this.problems.push(`The code of an evaluator starts the steps of the part ${key}. Only a runner waits.`);\n if (via === \"code\" && this.runner && this.running) {\n this.problems.push(`The runner evaluates the part ${key} with its code, and that code cannot wait. A runner evaluates a part with its steps (K65).`);\n }\n return this.scenario.results[part] ?? NO_RESULT;\n }\n\n /** This function records a call of a part, and gives the steps of the probe part. In a run, the part can wait. */\n *steps(part: number, via: Call[\"via\"], ctx: Context): Steps {\n const result = this.call(part, via, ctx);\n if (this.running && this.scenario.waits[part] === true) yield* this.wait(`the part ${this.keys[part] ?? String(part)}`);\n return result;\n }\n\n /** This function gives the steps of one wait. The probe driver answers the promise with a new object. */\n private *wait(what: string): Generator<Promise<unknown>, void, unknown> {\n const answer = { answer: what };\n const promise = new Promise<unknown>(() => undefined);\n const wait: Wait = { what, answer, seen: false, done: false };\n this.waits.set(promise, wait);\n const got = yield promise;\n wait.done = true;\n if (got !== answer) this.problems.push(`The runner gives ${what} another answer than the answer of the host.`);\n }\n\n effect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const text = capKeys(kind).join(\".\");\n this.caused.push({ kind: text, payload, context: ctx });\n if (this.running) return fail(\"#CALC!\", `The effect ${text} needs a runner: in a run, the host does each effect.`, { place });\n return this.answer(ctx, kind, payload, place);\n }\n\n *runEffect(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Steps {\n const text = capKeys(kind).join(\".\");\n this.caused.push({ kind: text, payload, context: ctx });\n if (!this.runner) this.problems.push(`The code of an evaluator starts the steps of the effect ${text}. Only a runner waits.`);\n const answered = this.answer(ctx, kind, payload, place);\n if (!answered.ok || !this.running) return answered;\n yield* this.wait(`the effect ${text}`);\n return answered;\n }\n\n /** This function answers an effect as the kernel does: it checks the capability, and it asks the mock. */\n private answer(ctx: Context, kind: Cap, payload: unknown, place: readonly Key[]): Result {\n const keys = capKeys(kind);\n // The kernel keeps only the capabilities that the document permits (H-GRANT).\n const caps = ctx.caps.filter((cap) => permits(this.context.caps, cap));\n const allowed = this.machine.permits === undefined ? permits(caps, keys) : this.machine.permits(caps, keys, { ...ctx, caps });\n if (!allowed) return fail(\"#CAP!\", `The context has no capability for the effect ${keys.join(\".\")}.`, { place });\n if (this.perform === undefined) return ok(payload);\n const effect: Effect = { index: this.caused.length - 1, kind: keys.join(\".\"), path: keys, payload, node: -1, at: 0, place, context: { ...ctx, caps } };\n let answer: unknown;\n try {\n answer = this.perform(effect);\n } catch (error) {\n return placed(thrown(error, `the mock of the effect ${effect.kind}`), place);\n }\n if (!(answer instanceof Promise)) return ok(answer);\n void answer.catch(() => undefined);\n return fail(\"#CALC!\", `The mock gave a promise for the effect ${effect.kind}, and an evaluation does not wait.`, { place });\n }\n\n *all(list: readonly (() => Steps)[], options: AllOptions = {}): Generator<Promise<unknown>, readonly Result[], unknown> {\n if (!this.runner) this.problems.push(\"The code of an evaluator starts the steps of all. Only a runner waits.\");\n // The probe runtime starts the items one after the other. Each wait of an item passes through, as in the kernel.\n const results: Result[] = [];\n let failed = false;\n for (const begin of list) {\n if (failed) {\n results.push(ABORTED);\n continue;\n }\n let result: Result;\n try {\n result = yield* begin();\n } catch (error) {\n result = thrown(error, \"a part\");\n }\n results.push(result);\n if (options.failFast === true && !result.ok) failed = true;\n }\n return results;\n }\n\n keepsContext(): void {\n // The probe runtime records no reads, thus a closure needs no read of the roots.\n }\n\n /** This function starts a function that the result gives, with probe arguments. The calls of the parts are later calls. */\n callLater(): void {\n const result = this.result;\n if (!result.ok || typeof result.value !== \"function\") return;\n this.afterwards = true;\n try {\n this.later.push(ok((result.value as (...args: readonly unknown[]) => unknown)(...PROBE_ARGS)));\n } catch (error) {\n this.later.push(thrown(error, \"the function of the result\"));\n } finally {\n this.afterwards = false;\n }\n }\n}\n\n/** The code of one probe document, made one time. It evaluates the document in each shot. */\ntype Instance = (shot: Shot) => Result;\n\n/** This function sets an own field, also the field `__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 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/** This function gives the form of an evaluator or of a runner. */\nfunction underOf(code: Evaluator | Runner, runner: boolean): Under {\n if (runner) {\n if (typeof code === \"function\") return { form: \"run\", fn: code as RunFn };\n return { form: \"compileRun\", compile: (input) => (code as CompiledRunner).compileRun(input) };\n }\n if (typeof code === \"function\") return { form: \"eval\", fn: code as EvalFn };\n return { form: \"compile\", compile: (input) => (code as CompiledEvaluator).compile(input) };\n}\n\nfunction compiledForm(under: Under): boolean {\n return under.form === \"compile\" || under.form === \"compileRun\";\n}\n\n/** This function gives the definition of the code for the reference, when it has one that is other code. */\nfunction definitionOf(machine: Machine, name: string, runner: boolean, definitions: Definitions | undefined): Under | undefined {\n if (runner) {\n const defined = own(definitions?.runners, name);\n return defined === undefined || defined === own(machine.runners, name) ? undefined : { form: \"run\", fn: defined };\n }\n const evaluator = own(machine.evaluators, name);\n const standard = evaluator !== undefined && evaluator === own(STD_EVALUATORS, name) ? own(STD_DEFINITIONS.evaluators, name) : undefined;\n const defined = own(definitions?.evaluators, name) ?? standard;\n return defined === undefined || defined === evaluator ? undefined : { form: \"eval\", fn: defined };\n}\n\n/** This function gives the type of each kind of the world whose verb names the evaluator. */\nfunction typesNaming(world: World, name: string, verb: string): readonly TypeRef[] {\n const out: (readonly Key[])[] = [];\n const names = (kind: Kind | undefined): boolean => kind !== undefined && own(kind.verbs, verb) === name;\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)) {\n if (names(entry)) out.push([...prefix, key]);\n } else if (isNamespace(entry)) {\n visit(entry.kinds, [...prefix, key]);\n if (names(entry.fallback)) out.push([...prefix, key, \"probe\"]);\n }\n }\n };\n visit(world.kinds, []);\n if (names(world.fallback)) out.push([\"probe\"]);\n return out;\n}\n\n/** This function gives the facts of the kind of a type. The hook `facts` of the machine wins over the contract. */\nfunction contractOf(env: Env, kind: Kind, typePath: readonly Key[], caps: readonly Cap[] | undefined): Contract {\n const facts = env.machine.facts?.(typePath, env.name);\n // A verb without a declaration keeps the effects of eval for the capabilities of the probes, as before D49.\n const own = effectsOfVerb(kind, env.verb);\n const effects = own ?? kind.effects;\n const declared: readonly Cap[] = effects === undefined ? [] : effects === \"type\" ? [typePath] : effects;\n return {\n declared,\n pure: (facts?.pure ?? kind.pure) === true,\n lazy: facts?.lazy ?? kind.lazy,\n describes: env.verb === \"eval\",\n declares: own !== undefined,\n caps: caps ?? [...declared, \"probe\"],\n };\n}\n\n/** This function tells if a lazy rule covers the part with an index, as `factsOf` reads the rule. */\nfunction covers(rule: LazyRule, slots: readonly PartSlot[], index: number): boolean {\n const matches = (slot: PartSlot): boolean => rule.in === undefined || rule.in.some((pattern) => pathMatches(slot.path, pattern));\n const slot = slots[index] as PartSlot;\n if (!matches(slot)) return false;\n const after = rule.after ?? 0;\n if (after <= 0) return true;\n let position = 0;\n for (let at = 0; at < index; at += 1) if (matches(slots[at] as PartSlot)) position += 1;\n return position >= after;\n}\n\n/** The counter of the probe documents of one value. */\ninterface Counter {\n next: number;\n}\n\n/** This function gives the JSON of a probe document. A position that permits only some kinds gets the first of them. */\nfunction probeJson(counter: Counter, kinds: readonly (readonly Key[])[] | undefined, named: boolean): Json {\n const id = counter.next;\n counter.next += 1;\n const first = kinds?.[0];\n return { type: first === undefined ? \"probe\" : (first as readonly Json[]), value: { probe: id }, ...(named ? { name: `p${id}` } : {}) };\n}\n\n/** This function gives a number that a number shape permits. */\nfunction numberIn(shape: Extract<Shape, { readonly shape: \"number\" }>, variant: number): number {\n const start = shape.min ?? (shape.max === undefined ? 1 : shape.max - 2);\n const base = shape.whole === true ? Math.ceil(start) : start;\n const value = base + (variant % 3);\n return shape.max !== undefined && value > shape.max ? shape.max : value;\n}\n\n/**\n * This function generates a value of a shape, with a probe document at the place of each part. The variant selects the\n * length of each list, the fields of a record that are absent, and the binding names of the probe documents.\n */\nfunction valueOf(shape: Shape | undefined, variant: number, counter: Counter, named: boolean): Json {\n if (shape === undefined || shape.shape === \"none\") return DATA[variant % DATA.length] as Json;\n switch (shape.shape) {\n case \"text\":\n return TEXTS[variant % TEXTS.length] as string;\n case \"number\":\n return numberIn(shape, variant);\n case \"one\":\n return shape.values[variant % Math.max(1, shape.values.length)] ?? null;\n case \"term\":\n return probeJson(counter, shape.kinds, named);\n case \"deep\": {\n const pick = variant % 4;\n if (pick === 0) return [probeJson(counter, undefined, named)];\n if (pick === 1) return { a: probeJson(counter, undefined, named), b: [probeJson(counter, undefined, named)] };\n if (pick === 2) return [\"names\", probeJson(counter, undefined, named)];\n return [\"names\", \"a\"];\n }\n case \"list\": {\n const item: Shape = shape.item ?? { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) };\n const length = LENGTHS[variant % LENGTHS.length] as number;\n // The index selects the data of each item, thus the items of a list of data are different.\n return Array.from({ length }, (_unused, index) => valueOf(item, item.shape === \"term\" ? variant : index, counter, named));\n }\n case \"map\": {\n const item: Shape = shape.item ?? { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) };\n const out: Record<string, Json> = {};\n for (const key of TEXTS.slice(0, [2, 0, 1][variant % 3])) setField(out, key, valueOf(item, variant, counter, named));\n return out;\n }\n case \"record\": {\n const fields: Readonly<Record<string, Shape>> = Array.isArray(shape.fields)\n ? Object.fromEntries((shape.fields as readonly string[]).map((key) => [key, { shape: \"term\", ...(shape.of === undefined ? {} : { of: shape.of }) } as Shape]))\n : (shape.fields as Readonly<Record<string, Shape>>);\n const keys = Object.keys(fields);\n const required = new Set(shape.required ?? []);\n const optional = keys.filter((key) => !required.has(key));\n // The variant 0 has each field. Each other variant leaves out one optional field.\n const absent = variant === 0 || optional.length === 0 ? undefined : optional[(variant - 1) % optional.length];\n const out: Record<string, Json> = {};\n for (const key of keys) if (key !== absent) setField(out, key, valueOf(fields[key], variant, counter, named));\n return out;\n }\n }\n}\n\n/** This function gives the JSON of a probe document with other JSON: another value, and another type where it can. */\nfunction otherJson(item: Json): Json {\n if (!isEnvelope(item)) return item;\n return { ...item, type: item.type === \"probe\" ? [\"probe\", \"other\"] : item.type, value: { other: [true, \"json\"], was: item.value } };\n}\n\n/** This function gives a probe document for a part of a value of the options. It keeps the type and the name of an envelope. */\nfunction probeFor(counter: Counter, item: Json): Json {\n if (!isEnvelope(item)) return probeJson(counter, undefined, false);\n const id = counter.next;\n counter.next += 1;\n return { ...item, value: { probe: id } };\n}\n\n/** This function gives the probe documents of a type: generated values and the values of the options. */\nfunction samplesOf(type: TypeRef, typePath: readonly Key[], kind: Kind, contract: Contract, extra: readonly Json[]): readonly Sample[] {\n const values: Json[] = [];\n for (let variant = 0; variant < VARIANTS; variant += 1) values.push(valueOf(kind.parts, variant, { next: 0 }, variant % 2 === 1));\n for (const value of extra) {\n const split = splitParts(kind.parts, value);\n if (!split.ok) continue;\n const counter: Counter = { next: 0 };\n values.push(split.fill(split.parts.map((slot) => probeFor(counter, slot.item))) as Json);\n }\n const out: Sample[] = [];\n const seen: Json[] = [];\n for (const value of values) {\n if (seen.some((other) => docEquals(other, value))) continue;\n seen.push(value);\n const split = splitParts(kind.parts, value);\n if (!split.ok) continue;\n const otherValue = split.parts.length === 0 ? value : (split.fill(split.parts.map((slot) => otherJson(slot.item))) as Json);\n const otherSplit = splitParts(kind.parts, otherValue);\n if (!otherSplit.ok || otherSplit.parts.length !== split.parts.length) continue;\n out.push({\n type: typeName(type),\n typePath,\n kind,\n doc: { type, value },\n split,\n other: { type, value: otherValue },\n otherSplit,\n lazy: split.parts.map((_slot, index) => contract.lazy?.some((rule) => covers(rule, split.parts, index)) === true),\n names: scopesOf(kind.scope, value, split.parts).sees,\n });\n }\n return out;\n}\n\n/** This function gives the handle fields of a part: its key, its path and its binding name. */\nfunction handleOf(slot: PartSlot): { readonly key: string; readonly path: readonly Key[]; readonly name?: string } {\n const item = slot.item;\n const name = isEnvelope(item) && typeof (item as { readonly name?: unknown }).name === \"string\" ? (item as { readonly name: string }).name : undefined;\n return name === undefined ? { key: slot.key, path: slot.path } : { key: slot.key, path: slot.path, name };\n}\n\n/**\n * This function drives the steps of a runner. It answers each wait of a probe part or of an effect at once. A promise\n * that no probe gave, or a wait that the runner gives two times, stops the steps (C6).\n */\nfunction drive(shot: Shot, steps: Steps): Result {\n let input: unknown;\n for (;;) {\n let step: IteratorResult<Promise<unknown>, Result>;\n try {\n step = steps.next(input);\n } catch (error) {\n return thrown(error, \"the runner\");\n }\n if (step.done === true) return step.value;\n const wait = shot.waits.get(step.value);\n if (wait === undefined || wait.seen) {\n shot.problems.push(\n wait === undefined\n ? \"The runner yields a promise that no part and no effect gave. A runner passes on only the waits of its parts and its effects.\"\n : `The runner yields the wait of ${wait.what} two times.`,\n );\n if (step.value instanceof Promise) void step.value.catch(() => undefined);\n try {\n steps.return(STOPPED);\n } catch {\n // The finally code of the runner threw. The probe stops the runner.\n }\n return STOPPED;\n }\n wait.seen = true;\n input = wait.answer;\n }\n}\n\n/** This function ends one evaluation: it keeps the result, calls a function that the result gives, and finds the waits that the runner dropped. */\nfunction finish(shot: Shot, start: () => Result, who: string): Result {\n let result: Result;\n try {\n result = placed(start(), PLACE);\n } catch (error) {\n result = placed(thrown(error, who), PLACE);\n }\n for (const wait of shot.waits.values()) if (!wait.done) shot.problems.push(`The runner drops the wait of ${wait.what}.`);\n shot.result = result;\n shot.callLater();\n return result;\n}\n\n/**\n * This function makes the code of one probe document. A compiler compiles the document one time, with compiled probe\n * parts. Each call of the code then evaluates the document in one shot.\n */\nfunction instanceOf(env: Env, under: Under, doc: Envelope, split: SplitOk, sample: Sample): Instance {\n const fill = (items: readonly unknown[]): unknown => (split.parts.length === 0 ? doc.value : split.fill(items));\n const base = { kind: sample.type, typePath: sample.typePath, doc, data: split.data, place: PLACE, machine: env.machine, fill };\n const who = `the ${env.runner ? \"runner\" : \"evaluator\"} ${env.name}`;\n if (under.form === \"eval\" || under.form === \"run\") {\n if (under.form === \"eval\") {\n const fn = under.fn;\n return (shot) => {\n const ctx = shot.context;\n const parts: Part[] = split.parts.map((slot, index) => ({ ...handleOf(slot), evaluate: (given?: Context) => shot.call(index, \"evaluate\", given ?? ctx) }));\n const input: EvalInput = {\n ...base,\n value: fill(parts),\n parts,\n context: ctx,\n resolve: (path, options) => shot.resolve(ctx, path, options),\n effect: (kind, payload) => shot.effect(ctx, kind, payload, PLACE),\n };\n return finish(shot, () => fn(input), who);\n };\n }\n const fn = under.fn;\n return (shot) => {\n const ctx = shot.context;\n const parts: RunPart[] = split.parts.map((slot, index) => ({ ...handleOf(slot), evaluate: (given?: Context) => shot.steps(index, \"evaluate\", given ?? ctx) }));\n const input: RunInput = {\n ...base,\n value: fill(parts),\n parts,\n context: ctx,\n resolve: (path, options) => shot.resolve(ctx, path, options),\n effect: (kind, payload) => shot.runEffect(ctx, kind, payload, PLACE),\n all: (list, options) => shot.all(list.map((part) => () => part.evaluate()), options),\n };\n return finish(shot, () => drive(shot, fn(input)), who);\n };\n }\n // A compiled part finds the shot of the evaluation through this holder, because the parts exist before each shot.\n const holder: { shot: Shot | undefined } = { shot: undefined };\n const early = fail(\"#CALC!\", \"The compiler evaluated a part before an evaluation.\");\n const parts: CompiledPart[] = split.parts.map((slot, index) => ({\n ...handleOf(slot),\n code: (ctx) => holder.shot?.call(index, \"code\", ctx) ?? early,\n *run(ctx) {\n const shot = holder.shot;\n return shot === undefined ? early : yield* shot.steps(index, \"run\", ctx);\n },\n }));\n const input: CompileInput = { ...base, value: fill(parts), parts, machine: env.machine };\n let made: Code | RunCode | Result;\n try {\n made = under.compile(input);\n } catch (error) {\n made = placed(thrown(error, who), PLACE);\n }\n const compiled = made;\n return (shot) => {\n holder.shot = shot;\n if (typeof compiled !== \"function\") return finish(shot, () => compiled, who);\n if (under.form === \"compile\") return finish(shot, () => (compiled as Code)(shot.context, shot), who);\n return finish(shot, () => drive(shot, (compiled as RunCode)(shot.context, shot)), who);\n };\n}\n\n/** This function evaluates a probe document one time in a new shot. */\nfunction shoot(env: Env, instance: Instance, sample: Sample, scenario: Scenario, more: { readonly context?: Context; readonly replay?: readonly Asked[] } = {}): Shot {\n const context = more.context ?? rootContext(env.machine, makeContext(env.names, scenario.caps));\n const shot = new Shot(env.machine, env.runner, scenario, context, sample.split.parts.map((slot) => slot.key), env.perform, more.replay);\n instance(shot);\n return shot;\n}\n\n/** This function gives the scenarios of a probe document: each result of the palette in each part, then random results. */\nfunction scenariosOf(env: Env, sample: Sample, contract: Contract, running: boolean): readonly Scenario[] {\n const count = sample.split.parts.length;\n const palette = env.results;\n const capsAt = (index: number): readonly Cap[] => (index % 2 === 0 ? contract.caps : NO_CAPS);\n const out: Scenario[] = [];\n const add = (results: readonly Result[], waits: readonly boolean[]): void => {\n out.push({ results, waits, caps: capsAt(out.length), running });\n };\n if (count === 0) {\n add([], []);\n add([], []);\n return out;\n }\n const all = Array.from({ length: count }, () => true);\n for (const result of palette) add(Array.from({ length: count }, () => result), all);\n for (let run = 0; run < env.runs; run += 1) {\n add(\n Array.from({ length: count }, () => env.random.pick(palette)),\n Array.from({ length: count }, () => env.random.chance(0.5)),\n );\n }\n return out;\n}\n\n/** This function gives a short text of a value for a reason. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"function\") return \"a function\";\n let text: string;\n try {\n text = JSON.stringify(value) ?? describe(value);\n } catch {\n text = describe(value);\n }\n return text.length > 40 ? `${text.slice(0, 37)}...` : text;\n}\n\nfunction resultText(result: Result): string {\n return result.ok ? `the value ${valueText(result.value)}` : `the error ${result.error.code}`;\n}\n\nfunction capsText(caps: readonly Cap[]): string {\n return caps.length === 0 ? \"no capabilities\" : `the capabilities ${caps.map((cap) => capKeys(cap).join(\".\")).join(\", \")}`;\n}\n\n/** This function tells if two results agree, as in `agree`: the same value, or errors with the same code and place. */\nfunction sameOutcome(a: Result, b: Result, equal: Env[\"equal\"]): boolean {\n if (a.ok && b.ok) return sameValue(a.value, b.value, equal);\n if (a.ok || b.ok) return false;\n if (a.error.code !== b.error.code) return false;\n return a.error.place === undefined || b.error.place === undefined || docEquals(a.error.place as readonly Key[], b.error.place as readonly Key[]);\n}\n\n/** This function tells if two shots give the same result and the same results of a later call. */\nfunction sameResults(a: Shot, b: Shot, equal: Env[\"equal\"]): boolean {\n return sameOutcome(a.result, b.result, equal) && a.later.length === b.later.length && a.later.every((result, index) => sameOutcome(result, b.later[index] as Result, equal));\n}\n\n/**\n * This function gives the difference of two shots of the same probe, or `undefined` when they agree. Two shots agree\n * when they give the same results, use the parts in the same order and cause the same effects. Without `paths`, the\n * resolutions do not count, as in the simulation of the plan.\n */\nfunction differs(a: Shot, b: Shot, equal: Env[\"equal\"], paths = true): string | undefined {\n if (!sameOutcome(a.result, b.result, equal)) return `The first evaluation gives ${resultText(a.result)}, and the second gives ${resultText(b.result)}.`;\n if (!sameResults(a, b, equal)) return \"The function that the result gives returns another result.\";\n const order = (shot: Shot): string => shot.calls.map((call) => `${call.later ? \"later \" : \"\"}${shot.keys[call.part] ?? String(call.part)}`).join(\", \");\n if (order(a) !== order(b)) return `The parts evaluate in another order: [${order(a)}] and [${order(b)}].`;\n const effects = (shot: Shot): string => shot.caused.map((effect) => effect.kind).join(\", \");\n if (a.caused.length !== b.caused.length || a.caused.some((effect, index) => effect.kind !== b.caused[index]?.kind || !sameValue(effect.payload, b.caused[index]?.payload, equal))) {\n return `The effects differ: [${effects(a)}] and [${effects(b)}].`;\n }\n if (!paths) return undefined;\n const asked = (shot: Shot): string => shot.asked.map((each) => valueText(each.path)).join(\", \");\n if (a.asked.length !== b.asked.length || a.asked.some((each, index) => !docEquals(each.path, b.asked[index]?.path))) return `The resolutions differ: [${asked(a)}] and [${asked(b)}].`;\n return undefined;\n}\n\n/** This function gives the probe of a finding. */\nfunction probeOf(sample: Sample, scenario: Scenario, doc: Envelope = sample.doc): ConformProbe {\n const results: Record<string, Result> = {};\n sample.split.parts.forEach((slot, index) => setField(results, slot.key, scenario.results[index] ?? NO_RESULT));\n const waits = scenario.running ? sample.split.parts.filter((_slot, index) => scenario.waits[index] === true).map((slot) => slot.key) : [];\n return { type: sample.type, doc, results, waits, caps: scenario.caps, running: scenario.running };\n}\n\n/** This function keeps the first finding of each obligation. */\nfunction report(env: Env, obligation: Obligation, reason: string, probe: () => ConformProbe): void {\n if (!env.found.has(obligation)) env.found.set(obligation, { obligation, reason, probe: probe() });\n}\n\nfunction thenable(value: unknown): boolean {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null && typeof (value as { readonly then?: unknown }).then === \"function\";\n}\n\n/** This function checks the record of one shot: the capabilities, the effects, the eager parts, the waits and the names. */\nfunction checkShot(env: Env, sample: Sample, contract: Contract, scenario: Scenario, shot: Shot): void {\n const probe = (): ConformProbe => probeOf(sample, scenario);\n const docCaps = shot.context.caps;\n const keyOf = (part: number): string => shot.keys[part] ?? String(part);\n // C1: each context that the code gives a part or an effect has only the capabilities of its document.\n for (const call of shot.calls) {\n if (!call.context.caps.every((cap) => permits(docCaps, cap))) {\n report(env, \"C1\", `The code gives the part ${keyOf(call.part)} ${capsText(call.context.caps)}, and its document has ${capsText(docCaps)}.`, probe);\n }\n }\n for (const effect of shot.caused) {\n if (!effect.context.caps.every((cap) => permits(docCaps, cap))) {\n report(env, \"C1\", `The code gives its effect ${effect.kind} ${capsText(effect.context.caps)}, and its document has ${capsText(docCaps)}.`, probe);\n }\n }\n if (contract.declares) {\n // C2: only the declared effects of the verb (VERB.EFFECTS).\n for (const effect of shot.caused) {\n if (!permits(contract.declared, effect.kind)) {\n report(env, \"C2\", `The code causes the effect ${effect.kind}, and the contract of ${sample.type} declares ${contract.declared.length === 0 ? \"no effects\" : capsText(contract.declared)}${env.verb === \"eval\" ? \"\" : ` for the verb ${env.verb}`}.`, probe);\n }\n }\n }\n if (contract.describes) {\n // C4: a pure kind causes no effect.\n const first = shot.caused[0];\n if (contract.pure && first !== undefined) report(env, \"C4\", `The kind ${sample.type} is pure, and the code causes the effect ${first.kind}.`, probe);\n // C3: each eager part evaluates when the result is a value.\n if (shot.result.ok) {\n sample.split.parts.forEach((_slot, index) => {\n if (sample.lazy[index] === true || shot.calls.some((call) => call.part === index && !call.later)) return;\n report(env, \"C3\", `The result is a value, and the code does not evaluate the part ${keyOf(index)}. No lazy rule of ${sample.type} covers the part.`, probe);\n });\n }\n }\n // C6: only a runner waits, and it passes each wait through.\n for (const problem of shot.problems) report(env, \"C6\", problem, probe);\n if (!env.runner && shot.result.ok && thenable(shot.result.value)) {\n report(env, \"C6\", \"The code of an evaluator gives a promise. Only a runner waits, with the steps of its parts and its effects.\", probe);\n }\n // C7: the names of each part are the names of the scope rules.\n const outer = shot.context.names;\n for (const call of shot.calls) {\n const given = call.context.names;\n const allowed = new Set(sample.names[call.part] ?? []);\n const bound = Object.keys(given).filter((key) => !Object.hasOwn(outer, key) || !Object.is(given[key], outer[key]));\n const extra = bound.filter((key) => !allowed.has(key));\n const lost = Object.keys(outer).filter((key) => !Object.hasOwn(given, key));\n const missing = [...allowed].filter((key) => !Object.hasOwn(given, key));\n const part = keyOf(call.part);\n if (extra.length > 0) {\n report(env, \"C7\", `The code binds ${extra.join(\", \")} for the part ${part}, and the scope rules of ${sample.type} give it ${allowed.size === 0 ? \"no names\" : [...allowed].join(\", \")}.`, probe);\n } else if (missing.length > 0) {\n report(env, \"C7\", `The scope rules of ${sample.type} give the part ${part} the names ${missing.join(\", \")}, and the code does not bind them.`, probe);\n } else if (lost.length > 0) {\n report(env, \"C7\", `The part ${part} does not see the names ${lost.join(\", \")} of its document.`, probe);\n }\n }\n}\n\n/**\n * This function gives a context with other values in each name and root that no resolution read (C4). The world and the\n * capabilities stay. A value that the code resolves keeps its value, because the list of reads holds that read.\n */\nfunction variedContext(ctx: Context, asked: readonly Asked[]): Context {\n const read = new Set<string>();\n for (const { path } of asked) {\n const root = path[0];\n read.add(root === \"names\" && isKey(path[1]) ? `names.${String(path[1])}` : String(root));\n }\n const names: Record<string, unknown> = {};\n for (const key of Object.keys(ctx.names)) setField(names, key, read.has(\"names\") || read.has(`names.${key}`) ? ctx.names[key] : { other: key });\n return { ...ctx, names, self: read.has(\"self\") ? ctx.self : { other: \"self\" }, event: read.has(\"event\") ? ctx.event : { other: \"event\" } };\n}\n\n/** This function examines one probe document with each check. */\nfunction examine(env: Env, sample: Sample, contract: Contract): void {\n const { under } = env;\n const fresh = (): Instance => instanceOf(env, under, sample.doc, sample.split, sample);\n const scenarios = scenariosOf(env, sample, contract, false);\n const code = fresh();\n const first = scenarios.map((scenario) => shoot(env, code, sample, scenario));\n scenarios.forEach((scenario, index) => checkShot(env, sample, contract, scenario, first[index] as Shot));\n\n // local: the same code gives the same record in the other order of the probes.\n const second: Shot[] = new Array<Shot>(scenarios.length);\n for (let index = scenarios.length - 1; index >= 0; index -= 1) second[index] = shoot(env, code, sample, scenarios[index] as Scenario);\n let clean = true;\n scenarios.forEach((scenario, index) => {\n const why = differs(first[index] as Shot, second[index] as Shot, env.equal);\n if (why === undefined) return;\n clean = false;\n report(env, \"local\", `The code keeps state from one call to the next. The same probe gives another record in a later call. ${why}`, () => probeOf(sample, scenario));\n });\n // C8: code that compiles again at the time of the evaluation gives the same record.\n if (clean && compiledForm(under)) {\n scenarios.forEach((scenario, index) => {\n const why = differs(second[index] as Shot, shoot(env, fresh(), sample, scenario), env.equal);\n if (why === undefined) return;\n clean = false;\n report(env, \"C8\", `The code reads a table of the machine or of the profile when it compiles, and the answer changes later. The code of an earlier compilation and new code differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n // The other comparisons need code without state, because each of them evaluates the probes again.\n if (!clean) return;\n\n // C5: other JSON in each part, and the same results of the parts, give the same record.\n if (sample.split.parts.length > 0) {\n const other = instanceOf(env, under, sample.other, sample.otherSplit, sample);\n const again = compiledForm(under) ? fresh() : code;\n scenarios.forEach((scenario) => {\n const why = differs(shoot(env, again, sample, scenario), shoot(env, other, sample, scenario), env.equal);\n if (why !== undefined) report(env, \"C5\", `The code reads the JSON of its parts. Two documents whose parts have other JSON and the same results differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n\n if (contract.describes) {\n // C4: a pure kind gives the same record in a context with other values, when each resolution gives the same answer.\n if (contract.pure) {\n scenarios.forEach((scenario, index) => {\n const before = first[index] as Shot;\n const varied = shoot(env, code, sample, scenario, { context: variedContext(before.context, before.asked), replay: before.asked });\n const why = differs(before, varied, env.equal);\n if (why !== undefined) {\n report(env, \"C4\", `The kind ${sample.type} is pure, and the code reads the context outside resolve. Other values in the roots, with the same answers of resolve, change the record. ${why}`, () => probeOf(sample, scenario));\n }\n });\n }\n // C3: a lazy part evaluates only when its result counts.\n scenarios.forEach((scenario, index) => {\n const before = first[index] as Shot;\n const evaluated = new Set(before.calls.filter((call) => !call.later && sample.lazy[call.part] === true).map((call) => call.part));\n for (const part of evaluated) {\n const counts = env.results.some((result) => {\n if (result === scenario.results[part]) return false;\n const results = scenario.results.map((each, at) => (at === part ? result : each));\n return !sameResults(before, shoot(env, code, sample, { ...scenario, results }), env.equal);\n });\n if (!counts) {\n report(env, \"C3\", `The code evaluates the lazy part ${before.keys[part] ?? String(part)}, and no result of that part changes the result. A lazy part evaluates only when its result counts.`, () => probeOf(sample, scenario));\n }\n }\n });\n }\n\n // agree: the compiled code and its definition give the same record (the local lemma of SIM-PLAN).\n const definition = env.definition;\n if (definition !== undefined) {\n const defined = instanceOf(env, definition, sample.doc, sample.split, sample);\n scenarios.forEach((scenario, index) => {\n const why = differs(first[index] as Shot, shoot(env, defined, sample, scenario), env.equal, false);\n if (why !== undefined) report(env, \"agree\", `The code and its definition for the reference differ. ${why}`, () => probeOf(sample, scenario));\n });\n }\n\n // C6 and the other checks of one shot in a run: each probe part can wait.\n if (env.runner) {\n for (const scenario of scenariosOf(env, sample, contract, true)) checkShot(env, sample, contract, scenario, shoot(env, code, sample, scenario));\n }\n}\n\n/**\n * This function examines one evaluator or runner of a machine against the obligations of host code (K92, D36). It\n * starts the code directly, without the kernel, with probe parts and a probe runtime. It generates probe documents from\n * the contract of each kind that names the code, and it gives the probe parts chosen and random results.\n *\n * The checks follow the obligations C1 to C8 of `docs/SEMANTICS.md`. Two more checks follow the premises of the\n * simulation of the plan. The check `local` finds state that stays from one call to the next. The check `agree` compares\n * compiled code with its definition. The\n * finding of an obligation names the first probe that breaks it. An empty list means that each probe conforms.\n *\n * @param machine - The machine with the code and the world of the kinds.\n * @param name - The name of the evaluator or of the runner. A runner wins over an evaluator of the same name.\n * @param options - The verb, the types and the values of the probe documents, and the results of the probe parts. Also\n * the definitions, the capabilities, the names, the seed, the mock and the rule of equality.\n * @returns The first finding of each obligation that the code breaks, in the order of the obligations.\n * @throws {Error} The machine has no code with the name, or no kind names it and the options give no types.\n */\nexport function conforms(machine: Machine, name: string, options: ConformOptions = {}): readonly Finding[] {\n const verb = options.verb ?? \"eval\";\n const runnerCode = own(machine.runners, name);\n const code = runnerCode ?? own(machine.evaluators, name);\n if (code === undefined) throw new Error(`The machine has no evaluator and no runner with the name ${name}.`);\n const runner = runnerCode !== undefined;\n const env: Env = {\n machine,\n name,\n verb,\n under: underOf(code, runner),\n definition: definitionOf(machine, name, runner, options.definitions),\n runner,\n results: options.results ?? RESULTS,\n names: options.names ?? NAMES,\n runs: options.runs ?? 12,\n random: random(options.seed ?? 1),\n perform: options.perform,\n equal: options.equal,\n found: new Map(),\n };\n const types = options.types ?? typesNaming(machine.world, name, verb);\n if (types.length === 0) throw new Error(`No kind of the world names ${name} for the verb ${verb}. Give the types of the probe documents in the option types.`);\n for (const type of types) {\n const found = lookupKind(machine.world, type);\n if (!found.ok) throw new Error(`The world has no kind for the type ${typeName(type)}.`);\n const contract = contractOf(env, found.kind, found.path, options.caps);\n const extra = own(options.values, typeName(type)) ?? own(options.values, found.path.join(\".\")) ?? [];\n for (const sample of samplesOf(type, found.path, found.kind, contract, extra)) examine(env, sample, contract);\n }\n return ORDER.filter((obligation) => env.found.has(obligation)).map((obligation) => env.found.get(obligation) as Finding);\n}\n","import { type Key, docEquals, equalWith } from \"./doc.ts\";\nimport type { EvalError, Result } from \"./errors.ts\";\nimport { Held } from \"./formula.ts\";\n\n/**\n * This function tells if two results are the same for an early cutoff (RESULT.SAME). A schedule uses it to stop the\n * work when a part that evaluates again gives the same result. A wrong `true` keeps a stale value, but a wrong `false`\n * only costs work. Thus each rule gives `false` when it is not sure.\n *\n * - Two values compare by the rules of `docEquals`. Lists and plain records compare by their items and fields. Each\n * other value compares with `Object.is`.\n * - Thus `-0` is not `0`, and `NaN` is `NaN`. A date, a map and a closure of `fn` are the same only as themselves.\n * - Two errors are the same when they have the same code, reason and place (RESULT.SAME-ERROR). The cause is not\n * compared. A `Held` value compares its error by the same rule.\n * - A value and an error are not the same.\n *\n * `sameValue` of `agree` uses the same walk, with rules for two tiers (D20). It compares two closures by their\n * parameters, and two errors by their code and place.\n *\n * @param a - The earlier result.\n * @param b - The new result.\n * @param equal - The rule of the host for two values, for example two dates. It answers first, and `undefined` gives the rules above.\n * @returns `true` when the results are the same.\n */\nexport function sameResult(a: Result<unknown>, b: Result<unknown>, equal?: (a: unknown, b: unknown) => boolean | undefined): boolean {\n if (a.ok && b.ok) return equalWith(a.value, b.value, equal === undefined ? sameHeld : (x, y) => equal(x, y) ?? sameHeld(x, y));\n if (!a.ok && !b.ok) return sameError(a.error, b.error);\n return false;\n}\n\n/** The rule of `sameResult` for held errors. Two `Held` values are the same when their errors are the same. */\nfunction sameHeld(x: unknown, y: unknown): boolean | undefined {\n if (x instanceof Held || y instanceof Held) return x instanceof Held && y instanceof Held && sameError(x.error, y.error);\n return undefined;\n}\n\n/** Two errors are the same when they have the same code, reason and place. An error without a place has no place in both. */\nfunction sameError(a: EvalError, b: EvalError): boolean {\n if (a.code !== b.code || a.reason !== b.reason) return false;\n if (a.place === undefined || b.place === undefined) return a.place === b.place;\n return docEquals(a.place as readonly Key[], b.place as readonly Key[]);\n}\n","import { docEquals } from \"./doc.ts\";\nimport { type Result, ok } from \"./errors.ts\";\nimport type { Context, Hop } from \"./deref.ts\";\nimport { type Machine, type Plan, type Read, readAgain, rootContext } from \"./evaluate.ts\";\nimport { Held } from \"./formula.ts\";\nimport { sameResult } from \"./same.ts\";\n\n/*\n * The verifying trace of a schedule (R4 P3, D26). An evaluation with the option `reads` records each path that it\n * resolves, and what the path reached. A pure document is a function of its reads. Thus when each free read reaches\n * the same thing in a new context, the old result stays valid, and the schedule keeps it without an evaluation.\n */\n\n/** The answer of `verifyReads`: the old result stays valid, or the first read that reaches another thing. */\nexport type ReadsCheck =\n | { readonly same: true }\n | {\n readonly same: false;\n /** The index of the first changed read in the list. */\n readonly index: number;\n /** The first changed read, as the evaluation recorded it. */\n readonly read: Read;\n /** What the path of that read reaches in the new context. */\n readonly now: Result;\n };\n\n/** The options of `verifyReads`. */\nexport interface VerifyOptions {\n /**\n * The rule of the host for two things, as in `sameResult`. It answers first, and `undefined` gives the rules of\n * `sameResult`. An example is a rule for a host thing that keeps a version.\n *\n * @param a - The thing of the recorded read.\n * @param b - The thing in the new context.\n * @returns `true` when the two things are the same, or `undefined` for the rules of `sameResult`.\n */\n readonly equal?: (a: unknown, b: unknown) => boolean | undefined;\n}\n\n/** One answer serves each list whose reads are all the same. */\nconst SAME: ReadsCheck = /* @__PURE__ */ Object.freeze({ same: true });\n\n/** This function tells if two lists of hops are the same: the same steps, rungs and things, in order. */\nfunction sameHops(a: readonly Hop[], b: readonly Hop[] | undefined, equal: VerifyOptions[\"equal\"]): boolean {\n if (b === undefined || a.length !== b.length) return false;\n for (let index = 0; index < a.length; index += 1) {\n const x = a[index] as Hop;\n const y = b[index] as Hop;\n if (x.by !== y.by || !docEquals(x.step, y.step) || !sameResult(ok(x.thing), ok(y.thing), equal)) return false;\n }\n return true;\n}\n\n/**\n * This function gives the error of a name that holds a held error and stops a longer path, or `undefined`. A\n * reference of the formula kit tests the binding of its first name before it resolves the rest of the path\n * (FORMULA.LET). The resolution of the whole path does not show that test.\n */\nfunction heldStop(root: Context, path: readonly unknown[]): Result | undefined {\n const name = path[1];\n if (path.length <= 2 || path[0] !== \"names\" || typeof name !== \"string\" || !Object.hasOwn(root.names, name)) return undefined;\n const bound = root.names[name];\n return bound instanceof Held ? { ok: false, error: bound.error } : undefined;\n}\n\n/**\n * This function tells if an old result stays valid in a new context (READS.VERIFY, D26). It resolves the path of\n * each free read again, in the order of the list, and it compares what the path reaches with `sameResult`. It stops at\n * the first read that reaches another thing, and it gives that read (READS.CHANGED).\n *\n * - A read that is not free reads a binding that a kind made from earlier reads, for example a name of `let`. The\n * function does not resolve it again.\n * - A thing compares as in `sameResult`. Thus a host thing or a date is the same only as itself. A host gives a new\n * object for a new state, or the option `equal`.\n * - A longer path through a name that holds a `Held` in the new context is a changed read. A reference of the formula\n * kit gives the error of that binding, and the resolution of the path does not show it.\n * - The answer is sound only for a pure document (FACTS.PURE). A document with an effect, a volatile operation or an\n * extension of a profile can read outside `resolve`. The schedule asks `factsOf` first.\n *\n * The values of the context must not change in place, as PLAN.CACHE says for the documents. A value that changed in\n * place is the same object, thus the function cannot see the change.\n *\n * @param target - The machine of the evaluation, or its plan.\n * @param reads - The reads of the evaluation, from the option `reads`.\n * @param context - The new context.\n * @param options - The rule of the host for two things.\n * @returns `{ same: true }` when each free read reaches the same thing, or else the first changed read.\n */\nexport function verifyReads(target: Machine | Plan, reads: readonly Read[], context: Context, options: VerifyOptions = {}): ReadsCheck {\n const machine = \"evaluators\" in target ? target : target.machine;\n const root = rootContext(machine, context);\n const equal = options.equal;\n for (let index = 0; index < reads.length; index += 1) {\n const read = reads[index] as Read;\n if (!read.free) continue;\n const stop = heldStop(root, read.path);\n if (stop !== undefined) return { same: false, index, read, now: stop };\n const asked = read.hops !== undefined;\n const now = readAgain(machine, root, read.path, asked);\n if (!sameResult(read.reached, now.reached, equal) || (read.hops !== undefined && !sameHops(read.hops, now.hops, equal))) {\n return { same: false, index, read, now: now.reached };\n }\n }\n return SAME;\n}\n","import type { Context } from \"./deref.ts\";\nimport type { Result } from \"./errors.ts\";\nimport { type Machine, type Plan, type PrepareOptions, type Read, prepare } from \"./evaluate.ts\";\nimport { type DocFacts, type FactsOptions, factsOf } from \"./facts.ts\";\nimport { type VerifyOptions, verifyReads } from \"./reads.ts\";\n\n/*\n * Two levels of durability (R4 P7, D30). The plan and the facts of a document depend only on the structure: the\n * machine and the documents. A result also depends on the data: the values that a context gives. A host keeps one\n * epoch for each level. Thus a change of data keeps each plan and each fact, and it only verifies or evaluates.\n */\n\n/** The two epochs of a host (DURABLE.EPOCHS). Each epoch counts the changes of its level. */\nexport interface Epochs {\n /** The count of the changes of the structure: a new machine, or an edit of a document. */\n readonly structure: number;\n /** The count of the changes of the data. A change of the structure is also a change of the data. */\n readonly data: number;\n}\n\n/** The work of a durable cache since its start. A schedule reads it as a measure, not as a rule (R4). */\nexport interface DurableCounts {\n /** The compilations: the calls of `prepare`. */\n readonly compiles: number;\n /** The calls of `factsOf`. */\n readonly facts: number;\n /** The evaluations of a plan. */\n readonly evaluations: number;\n /** The calls of `verifyReads`. */\n readonly verifications: number;\n /** The results that stayed without an evaluation. */\n readonly reuses: number;\n}\n\n/** The options of `durable`. */\nexport interface DurableOptions {\n /** The type of a bare root value, for each plan and each fact. */\n readonly declaredType?: string;\n /** The verb of each plan and each fact. The default is `eval` (VERB.PREPARE). */\n readonly verb?: string;\n /** The volatile reads of the host, as in `factsOf`. A document with such a read is not pure, thus it evaluates again after each change of data. */\n readonly volatile?: FactsOptions[\"volatile\"];\n /** The rule of the host for two things, as in `verifyReads`. */\n readonly equal?: VerifyOptions[\"equal\"];\n}\n\n/**\n * A cache of plans, facts and results with two levels of durability (D30). A host or a schedule tells the cache each\n * change of the structure and each change of the data.\n */\nexport interface Durable {\n /** The machine of the current structure epoch. */\n readonly machine: Machine;\n /** The current epochs. A schedule builds again what depends on the whole structure when `structure` changes, for example a graph of the nodes. */\n readonly epochs: Epochs;\n /** The work since the start. */\n readonly counts: DurableCounts;\n /**\n * This function gives the plan of a document. A document object compiles one time for a machine (DURABLE.STRUCTURE).\n * A change of data compiles nothing (DURABLE.DATA).\n *\n * @param doc - The document, as JSON.\n * @returns The plan.\n */\n plan(doc: unknown): Plan;\n /**\n * This function gives the static facts of a document. A document object computes its facts one time for a machine.\n *\n * @param doc - The document, as JSON.\n * @returns The facts.\n */\n facts(doc: unknown): DocFacts;\n /**\n * This function gives the result of the document of a node (DURABLE.REUSE). The key names the node, and in one data\n * epoch the context of a key gives the same data.\n *\n * - In the data epoch of its result, a key with the same plan gives that result again.\n * - After a change of data, a pure document verifies its reads, and it keeps its result when each read is the same.\n * - Each other document evaluates again.\n *\n * @param key - The name of the node in the host, for example the name of a cell.\n * @param doc - The document of the node.\n * @param context - The context of the node.\n * @returns The result.\n */\n evaluate(key: unknown, doc: unknown, context: Context): Result;\n /** This function tells the cache that the data changed: a context gives a new value (DURABLE.EPOCHS). */\n changeData(): void;\n /**\n * This function tells the cache that the structure changed (DURABLE.EPOCHS). An edit of a document gives a new\n * document object, and only that object compiles. A new machine drops each plan, each fact and each result.\n *\n * @param machine - The new machine, or `undefined` for an edit of a document.\n */\n changeStructure(machine?: Machine): void;\n /**\n * This function drops the result of a node, for example a node that the host removed.\n *\n * @param key - The name of the node.\n */\n forget(key: unknown): void;\n}\n\n/** The result of one node, with what it depends on. */\ninterface Entry {\n /** The plan of the evaluation. A new document or a new machine gives another plan. */\n readonly plan: Plan;\n readonly result: Result;\n /** The reads of the evaluation, only for a pure document. */\n readonly reads: readonly Read[] | undefined;\n /** The data epoch in which the result was last valid. */\n data: number;\n}\n\n/** The most values that a cache of value documents keeps, as in `planner`. */\nconst MAX_VALUES = 1000;\n\n/** No reads. One frozen list serves each result of a pure document without reads. */\nconst NO_READS: readonly Read[] = /* @__PURE__ */ Object.freeze([]);\n\n/** The key of the document `-0` in a cache of value documents. A `Map` finds the entry of `0` for `-0`. */\nconst NEGATIVE_ZERO = /* @__PURE__ */ Symbol(\"coeval.negative-zero\");\n\n/** This function makes a cache by document. A document object gives its value one time, as PLAN.CACHE says. */\nfunction byDocument<T>(make: (doc: unknown) => T): (doc: unknown) => T {\n const objects = new WeakMap<object, T>();\n const values = new Map<unknown, T>();\n return (doc) => {\n if (typeof doc === \"object\" && doc !== null) {\n if (objects.has(doc)) return objects.get(doc) as T;\n const made = make(doc);\n objects.set(doc, made);\n return made;\n }\n const key = Object.is(doc, -0) ? NEGATIVE_ZERO : doc;\n if (values.has(key)) return values.get(key) as T;\n const made = make(doc);\n if (values.size >= MAX_VALUES) values.clear();\n values.set(key, made);\n return made;\n };\n}\n\n/**\n * This function makes a cache with two levels of durability for a host or a schedule (R4 P7, D30). The structure is\n * the machine and the documents. The data is each value that a context gives: the names, `self`, `event`, the\n * capabilities and the world of the host.\n *\n * - A plan and the facts depend only on the structure. A document object compiles one time for a machine, thus a\n * change of data compiles nothing (DURABLE.DATA).\n * - A result depends on the data too. It stays in its data epoch. After a change of data, a pure document verifies\n * its reads with `verifyReads`, and each other document evaluates again.\n * - An edit gives a new document object, thus only that document compiles. A new machine drops each plan, each fact\n * and each result (DURABLE.STRUCTURE).\n *\n * The host keeps two promises. In one data epoch, the context of a key gives the same data. The values of a\n * context and the documents do not change in place, as PLAN.CACHE and `verifyReads` say.\n *\n * @param machine - The machine of the first structure epoch.\n * @param options - The type of a bare root value, the verb, the volatile reads and the rule of the host for two things.\n * @returns The cache.\n */\nexport function durable(machine: Machine, options: DurableOptions = {}): Durable {\n const prepareOptions: PrepareOptions = {\n ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }),\n ...(options.verb === undefined ? {} : { verb: options.verb }),\n };\n const factsOptions: FactsOptions = { ...prepareOptions, ...(options.volatile === undefined ? {} : { volatile: options.volatile }) };\n const verifyOptions: VerifyOptions = options.equal === undefined ? {} : { equal: options.equal };\n const counts = { compiles: 0, facts: 0, evaluations: 0, verifications: 0, reuses: 0 };\n const results = new Map<unknown, Entry>();\n let current = machine;\n let epochs: Epochs = { structure: 0, data: 0 };\n const plansOf = (m: Machine): ((doc: unknown) => Plan) =>\n byDocument((doc) => {\n counts.compiles += 1;\n return prepare(m, doc, prepareOptions);\n });\n const factsFor = (m: Machine): ((doc: unknown) => DocFacts) =>\n byDocument((doc) => {\n counts.facts += 1;\n return factsOf(m, doc, factsOptions);\n });\n let plans = plansOf(machine);\n let facts = factsFor(machine);\n return {\n get machine() {\n return current;\n },\n get epochs() {\n return epochs;\n },\n get counts() {\n return { ...counts };\n },\n plan: (doc) => plans(doc),\n facts: (doc) => facts(doc),\n evaluate(key, doc, context) {\n const plan = plans(doc);\n const entry = results.get(key);\n if (entry !== undefined && entry.plan === plan) {\n if (entry.data === epochs.data) {\n counts.reuses += 1;\n return entry.result;\n }\n if (entry.reads !== undefined) {\n counts.verifications += 1;\n if (verifyReads(plan, entry.reads, context, verifyOptions).same) {\n entry.data = epochs.data;\n counts.reuses += 1;\n return entry.result;\n }\n }\n }\n // Only a pure document is a function of its reads (FACTS.PURE), thus only its reads can keep its result.\n const reads: Read[] | undefined = facts(doc).pure ? [] : undefined;\n counts.evaluations += 1;\n const result = plan.evaluate(context, reads === undefined ? undefined : { reads });\n // A list that grows by push keeps room for more reads. A copy of a short list is smaller (PLAN.LEAN).\n results.set(key, { plan, result, reads: reads === undefined ? undefined : reads.length === 0 ? NO_READS : reads.slice(), data: epochs.data });\n return result;\n },\n changeData() {\n epochs = { structure: epochs.structure, data: epochs.data + 1 };\n },\n changeStructure(next) {\n epochs = { structure: epochs.structure + 1, data: epochs.data + 1 };\n if (next === undefined || next === current) return;\n current = next;\n plans = plansOf(next);\n facts = factsFor(next);\n results.clear();\n },\n forget(key) {\n results.delete(key);\n },\n };\n}\n","import type { Side } from \"./world.ts\";\n\n/*\n * The analysis of a graph of nodes (S2, R4 P5, D33). A host gives each node with its edges: the nodes that it reads.\n * The analysis gives the strongly connected components, the heights of a push schedule, the layers of independent\n * nodes, the nodes that an observer needs and the static cycles. Each function walks the graph with its own stack,\n * not with the stack of the host. Thus a chain of 100000 nodes does not overflow (GRAPH.SCC).\n */\n\n/** One edge of a graph of nodes: a read of a node by another node. `NodeEdge` of a schedule is such an edge. */\nexport interface GraphEdge<Id> {\n /** The node that the read reaches. It is `undefined` when the read can reach each node (GRAPH.UNKNOWN). */\n readonly to: Id | undefined;\n /** `true` when only a lazy part reaches the read. An evaluation can then give a value without it (FACTS.LAZY). */\n readonly lazy: boolean;\n}\n\n/** One node of a graph, with its edges. `NodeInfo` of a schedule is such a node. */\nexport interface GraphNode<Id> {\n /** The edges to the nodes that the node reads. */\n readonly edges: readonly GraphEdge<Id>[];\n /** The side of the node. A node on the run side is a sink: no edge reaches it (SCHED.SIDE). The default is `derive`. */\n readonly side?: Side;\n}\n\n/**\n * A graph of nodes, by name. The order of the map is the order of the nodes in each answer. The function `graph` of\n * a schedule gives such a graph. An edge to a name that is not in the map, or to a sink, is not an edge of the\n * analysis.\n */\nexport type NodeGraph<Id> = ReadonlyMap<Id, GraphNode<Id>>;\n\n/** The options of an analysis. */\nexport interface GraphOptions {\n /**\n * `true`: the analysis keeps only the eager edges with a target node. Such a read occurs in each evaluation in\n * which each document around it gives a value (FACTS.LAZY). The default keeps each edge.\n */\n readonly eager?: boolean;\n}\n\n/** One static cycle of a graph (GRAPH.CYCLE). */\nexport interface GraphCycle<Id> {\n /** The nodes of the cycle, in the order of the graph. */\n readonly nodes: readonly Id[];\n /**\n * `true` when the eager edges with a target close the cycle. `false` when the cycle needs a lazy edge or an edge\n * without a target. The value of each node still comes from the demand (D31).\n */\n readonly certain: boolean;\n}\n\n/**\n * A graph with a number for each node, and its edges in arrays. The edges of the node `v` are the items of `targets`\n * from `start[v]` up to `start[v + 1]`. An edge without a target goes to the extra node `all`, and `all` reaches each\n * node that is not a sink. Thus such an edge costs one edge, not one edge for each node.\n */\ninterface Indexed<Id> {\n readonly ids: readonly Id[];\n /** The count of the nodes, with the node `all` when the graph has it. */\n readonly size: number;\n readonly start: Int32Array;\n readonly targets: Int32Array;\n /** The number of the node `all`, or `-1` when no edge goes to it. */\n readonly all: number;\n}\n\n/** This function gives the indexed form of a graph, with the edges that the options keep. */\nfunction indexed<Id>(graph: NodeGraph<Id>, options: GraphOptions): Indexed<Id> {\n const eager = options.eager === true;\n const ids = [...graph.keys()];\n const count = ids.length;\n const numbers = new Map<Id, number>();\n const sink = new Uint8Array(count);\n ids.forEach((id, index) => {\n numbers.set(id, index);\n if (graph.get(id)?.side === \"run\") sink[index] = 1;\n });\n const start = new Int32Array(count + 2);\n const targets: number[] = [];\n let unknown = false;\n let from = 0;\n for (const node of graph.values()) {\n start[from] = targets.length;\n for (const edge of node.edges) {\n if (eager && edge.lazy) continue;\n if (edge.to === undefined) {\n if (eager) continue;\n unknown = true;\n targets.push(count);\n continue;\n }\n const to = numbers.get(edge.to);\n if (to !== undefined && sink[to] === 0) targets.push(to);\n }\n from += 1;\n }\n start[count] = targets.length;\n if (unknown) for (let to = 0; to < count; to += 1) if (sink[to] === 0) targets.push(to);\n start[count + 1] = targets.length;\n return { ids, size: unknown ? count + 1 : count, start, targets: Int32Array.from(targets), all: unknown ? count : -1 };\n}\n\n/** The strongly connected components of an indexed graph. */\ninterface Strong {\n /** The number of the component of each node. */\n readonly of: Int32Array;\n /** The nodes of each component. Each component comes after each component that it reaches. */\n readonly list: readonly (readonly number[])[];\n}\n\n/**\n * This function finds the strongly connected components with the algorithm of Tarjan. It keeps its own stack of\n * calls in two arrays, thus a long chain does not overflow the stack of the host. Each component comes after each\n * component that its nodes reach: the deepest component comes first.\n */\nfunction strong(graph: Indexed<unknown>): Strong {\n const { size, start, targets } = graph;\n const order = new Int32Array(size).fill(-1);\n const low = new Int32Array(size);\n const of = new Int32Array(size).fill(-1);\n // The nodes of the components that are still open.\n const open = new Int32Array(size);\n const onOpen = new Uint8Array(size);\n // The stack of calls: a node, and the position of its next edge.\n const calls = new Int32Array(size);\n const next = new Int32Array(size);\n const list: number[][] = [];\n let top = 0;\n let count = 0;\n const enter = (node: number, depth: number): void => {\n order[node] = count;\n low[node] = count;\n count += 1;\n open[top] = node;\n top += 1;\n onOpen[node] = 1;\n calls[depth] = node;\n next[depth] = start[node] as number;\n };\n for (let root = 0; root < size; root += 1) {\n if (order[root] !== -1) continue;\n enter(root, 0);\n let depth = 1;\n while (depth > 0) {\n const node = calls[depth - 1] as number;\n const edge = next[depth - 1] as number;\n if (edge < (start[node + 1] as number)) {\n next[depth - 1] = edge + 1;\n const to = targets[edge] as number;\n if (order[to] === -1) {\n enter(to, depth);\n depth += 1;\n } else if (onOpen[to] === 1 && (order[to] as number) < (low[node] as number)) {\n low[node] = order[to] as number;\n }\n continue;\n }\n depth -= 1;\n if (low[node] === order[node]) {\n const members: number[] = [];\n let member: number;\n do {\n top -= 1;\n member = open[top] as number;\n onOpen[member] = 0;\n of[member] = list.length;\n members.push(member);\n } while (member !== node);\n list.push(members.sort((a, b) => a - b));\n }\n if (depth > 0) {\n const reader = calls[depth - 1] as number;\n if ((low[node] as number) < (low[reader] as number)) low[reader] = low[node] as number;\n }\n }\n }\n return { of, list };\n}\n\n/** This function tells if a component has a cycle: two or more nodes, or one node with an edge to itself. */\nfunction cyclic(graph: Indexed<unknown>, members: readonly number[]): boolean {\n if (members.length > 1) return true;\n const node = members[0] as number;\n for (let edge = graph.start[node] as number; edge < (graph.start[node + 1] as number); edge += 1) if (graph.targets[edge] === node) return true;\n return false;\n}\n\n/** This function gives the names of the nodes of a component, without the node `all`. */\nfunction named<Id>(graph: Indexed<Id>, members: readonly number[]): Id[] {\n const out: Id[] = [];\n for (const member of members) if (member !== graph.all) out.push(graph.ids[member] as Id);\n return out;\n}\n\n/** This function gives the height of each component, in the order of `strong`. The node `all` adds no height. */\nfunction heightsOf(graph: Indexed<unknown>, found: Strong): Int32Array {\n const { start, targets } = graph;\n const heights = new Int32Array(found.list.length);\n found.list.forEach((members, component) => {\n let highest = -1;\n let real = false;\n for (const node of members) {\n if (node !== graph.all) real = true;\n for (let edge = start[node] as number; edge < (start[node + 1] as number); edge += 1) {\n const other = found.of[targets[edge] as number] as number;\n if (other !== component && (heights[other] as number) > highest) highest = heights[other] as number;\n }\n }\n heights[component] = real ? highest + 1 : highest;\n });\n return heights;\n}\n\n/**\n * This function gives the strongly connected components of a graph of nodes (GRAPH.SCC), with the algorithm of\n * Tarjan. It keeps its own stack, thus a chain of 100000 nodes does not overflow the stack of the host.\n *\n * - Each component comes after each component that it reads: the deepest component comes first.\n * - A node that is on no cycle is a component of one node.\n * - The nodes of a component are in the order of the graph.\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The components, deepest first.\n */\nexport function components<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): readonly (readonly Id[])[] {\n const index = indexed(graph, options);\n const out: (readonly Id[])[] = [];\n for (const members of strong(index).list) {\n const names = named(index, members);\n if (names.length > 0) out.push(names);\n }\n return out;\n}\n\n/**\n * This function gives the height of each node: the order of a push schedule (GRAPH.ORDER). A schedule that evaluates\n * the nodes from the lowest height up evaluates each node after each node that it reads, except on a cycle.\n *\n * - A node that reads no node outside its component has the height 0.\n * - Each other node is one higher than the highest node that it reads outside its component.\n * - The nodes of one component have one height.\n * - An edge without a target reads each node that is not a sink (GRAPH.UNKNOWN).\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The height of each node, in the order of the graph.\n */\nexport function heights<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): ReadonlyMap<Id, number> {\n const index = indexed(graph, options);\n const found = strong(index);\n const levels = heightsOf(index, found);\n const out = new Map<Id, number>();\n index.ids.forEach((id, node) => out.set(id, levels[found.of[node] as number] as number));\n return out;\n}\n\n/**\n * This function puts the nodes in layers by their heights, in linear time (GRAPH.LAYERS). The first layer has the\n * height 0. Two nodes of one layer read each other only inside one component. Thus a push schedule can evaluate the\n * components of one layer at the same time.\n *\n * @param graph - The nodes, each with its edges.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The layers, from the height 0 up. Each layer keeps the order of the graph.\n */\nexport function nodeLayers<Id>(graph: NodeGraph<Id>, options: GraphOptions = {}): readonly (readonly Id[])[] {\n const out: Id[][] = [];\n for (const [id, height] of heights(graph, options)) {\n while (out.length <= height) out.push([]);\n out[height]?.push(id);\n }\n return out;\n}\n\n/**\n * This function gives the nodes that a set of observed nodes needs (GRAPH.NECESSARY). These are the observed nodes,\n * and each node with a path of edges from them. A push schedule evaluates only these nodes. An observed name that is\n * not a node of the graph adds nothing.\n *\n * @param graph - The nodes, each with its edges.\n * @param observed - The nodes that the host shows or reads.\n * @param options - The option `eager` keeps only the eager edges with a target node.\n * @returns The necessary nodes, in the order of the graph.\n */\nexport function necessary<Id>(graph: NodeGraph<Id>, observed: Iterable<Id>, options: GraphOptions = {}): ReadonlySet<Id> {\n const index = indexed(graph, options);\n const numbers = new Map<Id, number>();\n index.ids.forEach((id, node) => numbers.set(id, node));\n const seen = new Uint8Array(index.size);\n const work: number[] = [];\n for (const id of observed) {\n const node = numbers.get(id);\n if (node === undefined || seen[node] === 1) continue;\n seen[node] = 1;\n work.push(node);\n }\n while (work.length > 0) {\n const node = work.pop() as number;\n for (let edge = index.start[node] as number; edge < (index.start[node + 1] as number); edge += 1) {\n const to = index.targets[edge] as number;\n if (seen[to] === 1) continue;\n seen[to] = 1;\n work.push(to);\n }\n }\n const out = new Set<Id>();\n index.ids.forEach((id, node) => {\n if (seen[node] === 1) out.add(id);\n });\n return out;\n}\n\n/**\n * This function gives the static cycles of a graph (GRAPH.CYCLE): each component with two or more nodes, and each\n * node with an edge to itself. A cycle of the eager edges with a target is certain, and `check` or a host can report\n * it before a run. Another cycle is possible: an evaluation can skip a lazy read.\n *\n * - A component of all the edges that is also a component of the eager edges is one certain cycle.\n * - Each other component of all the edges is one possible cycle, and each certain cycle in it comes after it.\n * - A read can still fail before it occurs. Thus the demand of D31, not a static cycle, gives the value of each node.\n *\n * @param graph - The nodes, each with its edges.\n * @returns The cycles, deepest first.\n */\nexport function cycles<Id>(graph: NodeGraph<Id>): readonly GraphCycle<Id>[] {\n const every = indexed(graph, {});\n const found = strong(every);\n const eager = indexed(graph, { eager: true });\n // The certain cycles, by the component of all the edges that holds them.\n const inside = new Map<number, (readonly number[])[]>();\n for (const members of strong(eager).list) {\n if (!cyclic(eager, members)) continue;\n const component = found.of[members[0] as number] as number;\n const list = inside.get(component);\n if (list === undefined) inside.set(component, [members]);\n else list.push(members);\n }\n const out: GraphCycle<Id>[] = [];\n found.list.forEach((members, component) => {\n if (!cyclic(every, members)) return;\n const nodes = named(every, members);\n const certain = inside.get(component) ?? [];\n if (certain.length === 1 && certain[0]?.length === nodes.length) {\n out.push({ nodes, certain: true });\n return;\n }\n out.push({ nodes, certain: false });\n for (const part of certain) out.push({ nodes: named(eager, part), certain: true });\n });\n return out;\n}\n\n/**\n * This function gives the nodes that a demand of a node needs first, deepest first (SCHED.LONG-CHAIN). It follows the\n * eager edges with a target from the node, with its own stack. Each node comes after each node that it reads, except\n * on a cycle, as in an order by heights. The walk costs only the nodes that it enters.\n *\n * @param from - The node of the demand. It is not in the answer.\n * @param edgesOf - This function gives the edges of a node, or `undefined` for a node that the walk does not enter.\n * @returns The nodes, deepest first.\n */\nexport function deepestFirst<Id>(from: Id, edgesOf: (id: Id) => readonly GraphEdge<Id>[] | undefined): readonly Id[] {\n const out: Id[] = [];\n const first = edgesOf(from);\n if (first === undefined) return out;\n const seen = new Set<Id>([from]);\n const nodes: Id[] = [from];\n const lists: (readonly GraphEdge<Id>[])[] = [first];\n const positions: number[] = [0];\n while (nodes.length > 0) {\n const top = nodes.length - 1;\n const edges = lists[top] as readonly GraphEdge<Id>[];\n let position = positions[top] as number;\n let entered = false;\n while (position < edges.length) {\n const edge = edges[position] as GraphEdge<Id>;\n position += 1;\n const to = edge.to;\n if (edge.lazy || to === undefined || seen.has(to)) continue;\n seen.add(to);\n const more = edgesOf(to);\n if (more === undefined) continue;\n positions[top] = position;\n nodes.push(to);\n lists.push(more);\n positions.push(0);\n entered = true;\n break;\n }\n if (entered) continue;\n const done = nodes.pop() as Id;\n lists.pop();\n positions.pop();\n if (nodes.length > 0) out.push(done);\n }\n return out;\n}\n","import type { Key } from \"./doc.ts\";\nimport { type Context, type HostThing, type Thing, THING, context as contextOf } from \"./deref.ts\";\nimport { type Failed, type Result, Failure, fail } from \"./errors.ts\";\nimport { type Machine, type Perform, type StopSignal, rootContext } from \"./evaluate.ts\";\nimport { type DurableCounts, type DurableOptions, type Epochs, durable } from \"./durable.ts\";\nimport type { DocFacts, StaticRead } from \"./facts.ts\";\nimport { deepestFirst } from \"./graph.ts\";\nimport type { Side } from \"./world.ts\";\n\n/*\n * The interface of a schedule (S1, D31). A host gives named documents. Each document is a node, and the root `world`\n * of each node reaches the other nodes. The static reads give the edges of the graph, and the contracts give the side\n * of each node. A demand evaluates a node and each node that it reads, through `durable`. Thus after a change, a node\n * evaluates again only when one of its reads changed. A demand of the host first demands the nodes that the eager\n * edges reach, deepest first (S2a, D33). Thus a long chain does not use the stack of the host for each node.\n */\n\n/** One edge of a graph of nodes: a static read of a node from the document of another node (SCHED.EDGES). */\nexport interface NodeEdge {\n /**\n * The node that the read reaches: the first key after the root `world`. It is `undefined` when the read can reach\n * each node, for example the path `[\"world\"]`, or a step document right after the root.\n */\n readonly to: string | undefined;\n /** The keys after the node, up to the first step document: the field of the node that the read reaches (SCHED.GRAIN). */\n readonly field: readonly Key[];\n /** `true` when only a lazy part reaches the read. An evaluation can then give a value without it (FACTS.LAZY). */\n readonly lazy: boolean;\n /** The static read of `factsOf`, with its path, its place and its mark `exact`. */\n readonly read: StaticRead;\n}\n\n/** One node of a schedule, with what the static facts tell about it (SCHED.GRAPH). */\nexport interface NodeInfo {\n /** The name of the node: its key under the root `world`. */\n readonly id: string;\n /** The document of the node. */\n readonly doc: unknown;\n /** The static facts of the document. */\n readonly facts: DocFacts;\n /** The side of the node, from the facts. A node on the run side is a sink: no node reads it (SCHED.SIDE). */\n readonly side: Side;\n /** The edges to the nodes that the document can read, in the order of its reads. */\n readonly edges: readonly NodeEdge[];\n}\n\n/** The options of `schedule`: the options of `durable`, and the context of the host. */\nexport interface ScheduleOptions extends DurableOptions {\n /** The context of the host: the names, `self`, `event` and the capabilities. The schedule sets the root `world` to the nodes. */\n readonly context?: Context;\n}\n\n/** The work of a schedule since its start: the work of its `durable` cache, and the demands ahead of a node. */\nexport interface ScheduleCounts extends DurableCounts {\n /**\n * The demands that a demand of the host made before its own node (SCHED.LONG-CHAIN). Each node that the eager edges\n * reach, and that has no value in the data epoch, adds one.\n */\n readonly ahead: number;\n}\n\n/** The options of a run of a node. */\nexport interface NodeRunOptions {\n /** The event that starts the run, at the root `event`. The default is the event of the context of the host. */\n readonly event?: Thing;\n /** The host code that does each effect, as in `run`. */\n readonly perform?: Perform;\n /** A signal that stops the run. */\n readonly signal?: StopSignal;\n}\n\n/**\n * The demand schedule of a graph of named nodes (D31). The host tells it each change of a node, of the machine and of\n * its data. The schedule evaluates a node only when a host or another node reads it.\n */\nexport interface Schedule {\n /** The epochs of the schedule (DURABLE.EPOCHS). A schedule builds again what depends on the structure when `structure` changes. */\n readonly epochs: Epochs;\n /** The work of the schedule since its start: the compilations, the evaluations, the verifications, the reuses and the demands ahead. */\n readonly counts: ScheduleCounts;\n /** The context of each node in the current data epoch: the context of the host, with the nodes at the root `world`. */\n readonly context: Context;\n /**\n * This function gives each node with its facts, its side and its edges (SCHED.GRAPH). The map stays the same object\n * in one structure epoch, thus a schedule can keep what it computes from it, for example an order.\n *\n * @returns The nodes, by name.\n */\n graph(): ReadonlyMap<string, NodeInfo>;\n /**\n * This function gives the value of a node on demand (SCHED.DEMAND). A read of `world` in the document demands that\n * node first. Each node evaluates at most one time in a data epoch.\n *\n * - First, the schedule demands each node that the eager edges reach, deepest first (SCHED.LONG-CHAIN).\n * - After a change, a pure node verifies its reads, and it keeps its result when each read is the same (SCHED.STALE).\n * - Each node of a cycle gives `#CYCLE!`, in each order of demands (SCHED.CYCLE).\n * - A node on the run side gives `#REF!`, because the schedule does not evaluate it (SCHED.SIDE).\n *\n * @param id - The name of the node.\n * @returns The result, or `#N/A` for a node that the schedule does not have.\n */\n read(id: string): Result;\n /**\n * This function adds a node, or gives a node a new document. It is a change of the structure. Only a new document\n * object compiles (DURABLE.STRUCTURE).\n *\n * @param id - The name of the node.\n * @param doc - The document of the node. It must not change in place after this call.\n */\n set(id: string, doc: unknown): void;\n /**\n * This function removes a node. It is a change of the structure, and a read of the node then gives `#N/A`.\n *\n * @param id - The name of the node.\n * @returns `true` when the schedule had the node.\n */\n remove(id: string): boolean;\n /**\n * This function tells the schedule that the data of the host changed (DURABLE.EPOCHS). The values of a context do\n * not change in place, thus new data comes in a new context, or through a host thing.\n *\n * @param context - The new context of the host, or `undefined` to keep the context.\n */\n changeData(context?: Context): void;\n /**\n * This function gives the schedule a new machine. It drops each plan, each fact and each result.\n *\n * @param machine - The new machine.\n */\n changeMachine(machine: Machine): void;\n /**\n * This function starts a run of the document of a node, and the host does each effect (SCHED.RUN). Only the host\n * starts a run, for example at an event. A change of data does not start or repeat a run (L3).\n *\n * @param id - The name of the node.\n * @param options - The event, 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(id: string, options?: NodeRunOptions): Promise<Result>;\n}\n\n/**\n * This function gives the edges of a node from the static facts of its document (SCHED.EDGES). Each read of the root\n * `world` is an edge to the node of its first key. The keys after that key are the field of the edge (SCHED.GRAIN).\n * A read of another root reads the data of the host, thus it is not an edge.\n *\n * A reference in the value of a node can lead a read to a third node (DEREF.COLLAPSE). The edges do not show such a\n * read, but the reads of an evaluation do (S1d).\n *\n * @param facts - The static facts of the document of the node.\n * @returns The edges, in the order of the reads.\n */\nexport function edgesOf(facts: DocFacts): readonly NodeEdge[] {\n const edges: NodeEdge[] = [];\n for (const read of facts.reads) {\n if (read.root !== \"world\") continue;\n const first = read.keys[0];\n edges.push({ to: first === undefined ? undefined : String(first), field: read.keys.length > 1 ? read.keys.slice(1) : NO_KEYS, lazy: read.lazy, read });\n }\n // A list that grows by push keeps room for more edges. A copy of a short list is smaller (PLAN.LEAN).\n return edges.length === 0 ? NO_EDGES : edges.slice();\n}\n\n/** No keys, and no edges. One frozen list of each serves each node, thus a schedule of many nodes keeps less. */\nconst NO_KEYS: readonly Key[] = /* @__PURE__ */ Object.freeze([]);\nconst NO_EDGES: readonly NodeEdge[] = /* @__PURE__ */ Object.freeze([]);\n\n/** This function gives the error of a node on a cycle. It names only the node, thus each order of demands gives the same error. */\nfunction cycleOf(id: string): Failed {\n return fail(\"#CYCLE!\", `The node ${id} is on a cycle of reads.`);\n}\n\n/** This function gives the error of a read of a node on the run side. */\nfunction runSide(id: string): Failed {\n return fail(\"#REF!\", `The node ${id} is on the run side, thus it has no value for a reader.`);\n}\n\n/** This function gives the error of a node that the schedule does not have. */\nfunction missing(id: string): Failed {\n return fail(\"#N/A\", `The schedule has no node ${id}.`);\n}\n\n/** The state of one data epoch: the context of the nodes, and the value of each node that a demand reached. */\ninterface Epoch {\n readonly context: Context;\n readonly values: Map<string, Result>;\n}\n\n/**\n * This function makes the demand schedule of a graph of named nodes (S1, R4, D31). A host gives each node a name and\n * a document. The root `world` of each node reaches the other nodes by name. The context of the host gives the other\n * roots.\n *\n * - `graph()` gives the facts, the side and the edges of each node, from `factsOf` and `edgesOf`.\n * - `read(id)` evaluates a node on demand, through `durable`. A pure node verifies its reads after a change, and a\n * read of a node demands that node again. Thus only a node with a changed read evaluates again: the red-green\n * algorithm of rustc.\n * - A node is on a cycle when its demand reaches itself through the reads of the evaluations. Each node of such a\n * strongly connected component gives `#CYCLE!`, whatever its document does with the error. The schedule finds the\n * components with the algorithm of Tarjan over the demands. Thus each order of demands gives the same values.\n * - A demand of the host, or of a run, first demands each node that the eager edges reach, deepest first. Thus each\n * read of such a node finds a value, and a chain of 100000 nodes does not overflow the stack (SCHED.LONG-CHAIN).\n * Each such demand starts with no node in evaluation, thus the order of demands keeps the values of D31.\n * - A node on the run side is a sink. Only `run` evaluates it, and only the host uses `run`.\n *\n * The host keeps the promises of `durable`. The documents and the values of a context do not change in place.\n *\n * @param machine - The machine of the first structure epoch.\n * @param options - The options of `durable`, and the context of the host.\n * @returns The schedule.\n */\nexport function schedule(machine: Machine, options: ScheduleOptions = {}): Schedule {\n const { context: given, ...cacheOptions } = options;\n const cache = durable(machine, cacheOptions);\n const docs = new Map<string, unknown>();\n const edges = new WeakMap<DocFacts, readonly NodeEdge[]>();\n let base: Context = given ?? contextOf();\n let now: Epoch | undefined;\n let nodes: { readonly structure: number; readonly map: ReadonlyMap<string, NodeInfo> } | undefined;\n\n // The nodes in evaluation, in the order of their demands. The top of the stack is the node whose read demands.\n const stack: string[] = [];\n const busy = new Set<string>();\n // The algorithm of Tarjan over the demands: the order of each demand, the lowest order that the node reaches, and\n // the nodes of the components that are still open.\n const order = new Map<string, number>();\n const low = new Map<string, number>();\n const open: string[] = [];\n const onOpen = new Set<string>();\n // The nodes in evaluation that read themselves.\n const looped = new Set<string>();\n let count = 0;\n let ahead = 0;\n\n const lower = (id: string, to: number): void => {\n if (to < (low.get(id) as number)) low.set(id, to);\n };\n\n /** This function closes the open components down to an index of the list `open`. */\n const close = (from: number): number => {\n let size = 0;\n while (open.length > from) {\n const id = open.pop() as string;\n onOpen.delete(id);\n order.delete(id);\n low.delete(id);\n size += 1;\n }\n return size;\n };\n\n /** This function gives the edges of the facts of a document. They stay for each facts object, as the facts stay for each document. */\n const edgesFrom = (facts: DocFacts): readonly NodeEdge[] => {\n let found = edges.get(facts);\n if (found === undefined) {\n found = edgesOf(facts);\n edges.set(facts, found);\n }\n return found;\n };\n\n /** This function gives the edges of a node, for the walk of a demand. A known node, a missing node and a node on the run side need no walk. */\n const edgesFor = (id: string): readonly NodeEdge[] | undefined => {\n if (current().values.has(id) || !docs.has(id)) return undefined;\n const facts = cache.facts(docs.get(id));\n return facts.side === \"run\" ? undefined : edgesFrom(facts);\n };\n\n /**\n * This function gives the value of a node. A demand of the host or of a run has no node in evaluation. It first\n * demands each node that the eager edges reach, deepest first. Each of these demands also starts with no node in\n * evaluation, thus it is a demand of the host too. D31 gives each order of such demands the same values.\n */\n const demand = (id: string): Result => {\n if (stack.length === 0) {\n for (const first of deepestFirst(id, edgesFor)) {\n ahead += 1;\n visit(first);\n }\n }\n return visit(id);\n };\n\n /** This function demands one node, with the algorithm of Tarjan over the demands for the cycles of D31. */\n const visit = (id: string): Result => {\n const epoch = current();\n const reader = stack[stack.length - 1];\n const known = epoch.values.get(id);\n if (known !== undefined) {\n // A finished node of an open component is on a cycle with its reader too.\n if (reader !== undefined && onOpen.has(id)) lower(reader, order.get(id) as number);\n return known;\n }\n if (busy.has(id)) {\n // A read of a node in evaluation closes a cycle. It gives the same error as the final result of that node.\n if (reader !== undefined) lower(reader, order.get(id) as number);\n if (reader === id) looped.add(id);\n return cycleOf(id);\n }\n const doc = docs.get(id);\n if (cache.facts(doc).side === \"run\") {\n const refused = runSide(id);\n epoch.values.set(id, refused);\n return refused;\n }\n const mine = count++;\n order.set(id, mine);\n low.set(id, mine);\n const from = open.length;\n open.push(id);\n onOpen.add(id);\n busy.add(id);\n stack.push(id);\n let result: Result | undefined;\n try {\n result = cache.evaluate(id, doc, epoch.context);\n } finally {\n stack.pop();\n busy.delete(id);\n // An exception of the host leaves the node without a result. A later demand evaluates it again.\n if (result === undefined) {\n looped.delete(id);\n close(from);\n }\n }\n const reached = low.get(id) as number;\n const self = looped.delete(id);\n let value = result;\n if (reached < mine) {\n // The node reaches an earlier node that is still open, thus it is in that component.\n value = cycleOf(id);\n } else if (close(from) > 1 || self) {\n value = cycleOf(id);\n } else if (!result.ok && result.error.code === \"#DEPTH!\") {\n // An overflow of the stack depends on the depth of the demand, not on the node (D15).\n cache.forget(id);\n }\n epoch.values.set(id, value);\n if (reader !== undefined) lower(reader, reached);\n return value;\n };\n\n /** This function gives the record of the derive nodes, for a path that ends at the root `world`. */\n const record = (): unknown => {\n const out: Record<string, unknown> = {};\n for (const id of [...docs.keys()].sort()) {\n if (cache.facts(docs.get(id)).side === \"run\") continue;\n const result = demand(id);\n if (!result.ok) throw new Failure(result.error);\n Object.defineProperty(out, id, { value: result.value, enumerable: true, writable: true, configurable: true });\n }\n return out;\n };\n\n /**\n * This function gives the state of the current data epoch. Each data epoch has a new host thing at the root\n * `world`. Thus a read that reaches the whole root changes at each change of data (READS.KEPT).\n */\n const current = (): Epoch => {\n if (now !== undefined) return now;\n const nodesThing: HostThing = {\n [THING]: true,\n label: \"nodes\",\n deref(key) {\n const id = String(key);\n if (!docs.has(id)) return undefined;\n const result = demand(id);\n // A failed node gives its own error to each reader, as a failed attribute of a tree does (D16).\n if (!result.ok) throw new Failure(result.error);\n return result.value;\n },\n has: (key) => docs.has(String(key)),\n toJson: record,\n };\n // The context has a world, thus `rootContext` only gives it its grant (CAP.NARROW-CODE). Each evaluation of the\n // epoch then uses this object with no copy.\n now = { context: rootContext(machine, { ...base, world: nodesThing }), values: new Map() };\n return now;\n };\n\n const changed = (structure: boolean): void => {\n if (structure) cache.changeStructure();\n else cache.changeData();\n now = undefined;\n };\n\n return {\n get epochs() {\n return cache.epochs;\n },\n get counts() {\n return { ...cache.counts, ahead };\n },\n get context() {\n return current().context;\n },\n graph() {\n const structure = cache.epochs.structure;\n if (nodes?.structure === structure) return nodes.map;\n const map = new Map<string, NodeInfo>();\n for (const [id, doc] of docs) {\n const facts = cache.facts(doc);\n map.set(id, { id, doc, facts, side: facts.side, edges: edgesFrom(facts) });\n }\n nodes = { structure, map };\n return map;\n },\n read: (id) => (docs.has(id) ? demand(id) : missing(id)),\n set(id, doc) {\n docs.set(id, doc);\n changed(true);\n },\n remove(id) {\n if (!docs.delete(id)) return false;\n cache.forget(id);\n changed(true);\n return true;\n },\n changeData(next) {\n if (next !== undefined) base = next;\n changed(false);\n },\n changeMachine(next) {\n cache.changeStructure(next);\n now = undefined;\n },\n run(id, runOptions = {}) {\n if (!docs.has(id)) return Promise.resolve(missing(id));\n const ctx = current().context;\n return cache.plan(docs.get(id)).run(runOptions.event === undefined ? ctx : { ...ctx, event: runOptions.event }, {\n ...(runOptions.perform === undefined ? {} : { perform: runOptions.perform }),\n ...(runOptions.signal === undefined ? {} : { signal: runOptions.signal }),\n });\n },\n };\n}\n","import { docEquals } from \"./doc.ts\";\nimport { type Result, Failure, fail } from \"./errors.ts\";\nimport { type Effect, type Journal, type Perform, JOURNAL } from \"./evaluate.ts\";\n\n/*\n * Record and replay (R2 P2, D19). A recorder wraps the function `perform` of a host and keeps a log. The log has each\n * effect with its address, its request and its outcome, and the order in which the waits of each `all` settled. A\n * replayer answers each effect from the log by its address, thus a replay does no host effect. The kernel gives the\n * address and the outcome of each effect. The journal on the function `perform` carries the order of the waits.\n */\n\n/** One effect of a log: its address, its request and its outcome. */\nexport interface ReplayEntry {\n /** The address of the effect (RUN.ADDRESS), for example `1#0` or `all0.1/1#0`. */\n readonly address: string;\n /** The kind of the effect, as a text with dots. */\n readonly kind: string;\n readonly payload: unknown;\n /** The outcome of the effect (RUN.OUTCOME). It is absent when the recorded run stopped before the answer came. */\n readonly outcome?: Result;\n /** `true` when the host made the run wait for the outcome. */\n readonly waited: boolean;\n}\n\n/** An item of an `all` whose wait settled in the recorded run. */\nexport interface ReplaySettle {\n /** The address of the `all`, for example `all0` or `all0.1/all0`. */\n readonly all: string;\n /** The index of the item. */\n readonly item: number;\n}\n\n/** The log of a run: each effect in the order of the requests, and the order in which the waits of each `all` settled. */\nexport interface ReplayLog {\n readonly effects: readonly ReplayEntry[];\n readonly settles: readonly ReplaySettle[];\n}\n\n/** A recorder: the function `perform` for a run, and the log of that run (RUN.RECORD). */\nexport interface Recorder {\n /** The function to give the run. It gives each effect to the function `perform` of the host, and it records the effect. */\n readonly perform: Perform;\n /**\n * This function gives the log of the run until this time. An effect gets its outcome when the answer comes.\n *\n * @returns The log.\n */\n log(): ReplayLog;\n}\n\n/** The options of a replayer. */\nexport interface ReplayOptions {\n /**\n * `false`: each answer comes at once, also for an effect that waited in the recorded run. An evaluation needs this\n * value, because it does not wait. The default is `true`: an effect waits when it waited in the recorded run.\n */\n readonly wait?: boolean;\n}\n\n/**\n * This function makes a recorder (RUN.RECORD). The recorder gives each effect to the function `perform` of the host.\n * Its log keeps each effect with its address, its kind, its payload and the outcome that the kernel gives it. The log\n * also keeps the order in which the waits of each `all` settle.\n *\n * @param perform - The function of the host. Without it, each effect gives its payload, as in a run without a host.\n * @returns The function `perform` for the run, and the log.\n */\nexport function recorder(perform?: Perform): Recorder {\n const seen: { readonly effect: Effect; waited: boolean }[] = [];\n const settles: ReplaySettle[] = [];\n const journal: Journal = {\n settled: (all, item) => {\n settles.push({ all, item });\n },\n };\n const host = (effect: Effect): unknown => {\n const entry = { effect, waited: false };\n seen.push(entry);\n const answer = perform === undefined ? effect.payload : perform(effect);\n if (answer instanceof Promise) entry.waited = true;\n return answer;\n };\n return {\n perform: Object.assign(host, { [JOURNAL]: journal }),\n log: () => ({\n effects: seen.map(({ effect, waited }) => ({\n address: effect.address ?? \"\",\n kind: effect.kind,\n payload: effect.payload,\n waited,\n ...(effect.outcome === undefined ? {} : { outcome: effect.outcome }),\n })),\n settles: [...settles],\n }),\n };\n}\n\n/**\n * This function makes a replayer: a function `perform` that answers each effect from a log, by its address (RUN.REPLAY). A\n * recorded error comes again with its code, its reason, its place and its cause. The waits of each `all` settle in the\n * recorded order. An effect that the log does not have at its address gives `#REPLAY!` (RUN.REPLAY-MISMATCH).\n *\n * A replayer keeps its place in the order of the waits, thus each run needs a new replayer.\n *\n * @param log - The log of a recorder.\n * @param options - `wait: false` for an evaluation.\n * @returns The function `perform` for the replay.\n */\nexport function replayer(log: ReplayLog, options: ReplayOptions = {}): Perform {\n const wait = options.wait !== false;\n const entries = new Map<string, ReplayEntry>();\n for (const entry of log.effects) entries.set(entry.address, entry);\n const order = new Map<string, number[]>();\n for (const settle of log.settles) {\n const items = order.get(settle.all);\n if (items === undefined) order.set(settle.all, [settle.item]);\n else items.push(settle.item);\n }\n const journal: Journal = {\n next: (all, waiting) => {\n const items = order.get(all);\n const item = items?.[0];\n if (items === undefined || item === undefined || !waiting.includes(item)) return undefined;\n items.shift();\n return item;\n },\n };\n const perform = (effect: Effect): unknown => {\n const entry = effect.address === undefined ? undefined : entries.get(effect.address);\n const wrong = mismatch(effect, entry);\n if (wrong !== undefined || entry === undefined) throw wrong;\n const outcome = entry.outcome;\n const failure =\n outcome === undefined\n ? replayError(effect, `The log has no outcome for the effect ${effect.kind} at ${effect.address ?? \"\"}: the recorded run stopped before the answer.`)\n : outcome.ok\n ? undefined\n : new Failure(outcome.error);\n const value = outcome?.ok === true ? outcome.value : undefined;\n if (wait && entry.waited) return failure === undefined ? Promise.resolve(value) : Promise.reject(failure);\n if (failure !== undefined) throw failure;\n return value;\n };\n return Object.assign(perform, { [JOURNAL]: journal });\n}\n\n/** This function gives the error of an effect that the log does not have at its address, or `undefined`. */\nfunction mismatch(effect: Effect, entry: ReplayEntry | undefined): Failure | undefined {\n const at = effect.address ?? \"\";\n if (entry === undefined) return replayError(effect, `The log has no effect at the address ${at}, and the run asks for the effect ${effect.kind}.`);\n if (entry.kind !== effect.kind) return replayError(effect, `The log has the effect ${entry.kind} at the address ${at}, and the run asks for the effect ${effect.kind}.`);\n if (!docEquals(entry.payload, effect.payload)) return replayError(effect, `The effect ${effect.kind} at the address ${at} has another payload than the log.`);\n return undefined;\n}\n\n/** This function gives the exception that carries `#REPLAY!` to the kernel, with the place of the effect. */\nfunction replayError(effect: Effect, reason: string): Failure {\n return new Failure(fail(\"#REPLAY!\", reason, { place: effect.place }).error);\n}\n","import { type Json, type Key, docEquals, isRecord } from \"./doc.ts\";\nimport { type TypeIssue, type ValueType, isUnknown, join, member } from \"./types.ts\";\n\n/*\n * Type providers (R5 P4, D28). A provider makes a value type from data that a host already has: a JSON Schema or\n * sample values. A host gives such a type to a root of a check, for example the schema of a store for `world`.\n */\n\n/** The type that a provider reads, and the problems of the reading. Each problem tells what the type does not test. */\nexport interface TypeReading {\n readonly type: ValueType;\n readonly issues: readonly TypeIssue[];\n}\n\n/** The deepest schema that `typeFromSchema` reads. A deeper schema reads as `unknown`. */\nconst MAX_SCHEMA_DEPTH = 256;\n\n/** The keywords that describe a schema and do not test a value. The reading ignores them without an issue. */\nconst NOTES: ReadonlySet<string> = /* @__PURE__ */ new Set([\n \"$schema\",\n \"$id\",\n \"$anchor\",\n \"$comment\",\n \"$defs\",\n \"definitions\",\n \"title\",\n \"description\",\n \"default\",\n \"examples\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n]);\n\n/** The keywords that the reading reads. Each other keyword gives an issue and tests nothing. */\nconst READ: ReadonlySet<string> = /* @__PURE__ */ new Set([\"type\", \"properties\", \"required\", \"additionalProperties\", \"items\", \"enum\", \"const\", \"anyOf\", \"oneOf\"]);\n\n/**\n * The keywords that can permit more values than the other keywords permit. Older drafts ignore each keyword beside\n * `$ref`, and `nullable` of OpenAPI 3.0 permits `null`. Thus a schema with one of them reads as `unknown`.\n */\nconst WIDENING: ReadonlySet<string> = /* @__PURE__ */ new Set([\"$ref\", \"$dynamicRef\", \"$recursiveRef\", \"nullable\"]);\n\n/** The base type of each name of the keyword `type`. */\nconst BASES: Readonly<Record<string, ValueType>> = { null: \"null\", boolean: \"bool\", number: \"number\", integer: \"number\", string: \"text\" };\n\n/** This function sets an own field of a new record. 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\n/** The union of types: the join of each type, or `never` for no type. */\nfunction unionOf(types: readonly ValueType[]): ValueType {\n return types.reduce<ValueType>((all, type) => join(all, type), \"never\");\n}\n\n/** The state of one reading of a schema: the issues that it found. */\nclass SchemaReader {\n readonly issues: TypeIssue[] = [];\n\n issue(at: readonly Key[], reason: string): void {\n this.issues.push({ at, reason });\n }\n\n /** This method reads one schema. */\n read(schema: unknown, at: readonly Key[], depth: number): ValueType {\n if (depth > MAX_SCHEMA_DEPTH) {\n this.issue(at, `The schema is deeper than ${MAX_SCHEMA_DEPTH} levels. The type reads it as unknown.`);\n return \"unknown\";\n }\n if (schema === true) return \"unknown\";\n if (schema === false) return \"never\";\n if (!isRecord(schema)) {\n this.issue(at, \"A schema is a record or a truth value. The type reads this value as unknown.\");\n return \"unknown\";\n }\n let widens = false;\n for (const key of Object.keys(schema)) {\n if (READ.has(key) || NOTES.has(key)) continue;\n if (WIDENING.has(key)) {\n this.issue([...at, key], `The type does not read the keyword ${key}. Thus it reads the schema as unknown.`);\n widens = true;\n } else {\n this.issue([...at, key], `The type does not read the keyword ${key}. It does not test what the keyword tests.`);\n }\n }\n if (widens) return \"unknown\";\n // A schema is the conjunction of its keywords. The reading keeps one of them, and each one alone holds each value.\n const sides: { readonly key: string; readonly type: ValueType }[] = [];\n if (Object.hasOwn(schema, \"type\")) sides.push({ key: \"type\", type: this.byType(schema, at, depth) });\n else if ([\"properties\", \"required\", \"additionalProperties\", \"items\"].some((key) => Object.hasOwn(schema, key)) && ![\"enum\", \"const\", \"anyOf\", \"oneOf\"].some((key) => Object.hasOwn(schema, key))) {\n this.issue(at, \"The schema has no keyword type. Thus a value of each JSON type fits it, and the type reads it as unknown.\");\n }\n for (const key of [\"anyOf\", \"oneOf\"]) {\n if (!Object.hasOwn(schema, key)) continue;\n const items = schema[key];\n if (!Array.isArray(items)) {\n this.issue([...at, key], `The value of ${key} is a list of schemas.`);\n continue;\n }\n // A union holds each value of oneOf too. It does not test that only one schema fits.\n sides.push({ key, type: unionOf(items.map((item, index) => this.read(item, [...at, key, index], depth + 1))) });\n }\n // A finite set of values meets each other keyword exactly: the type keeps each value that each side holds.\n const values = this.values(schema, at);\n if (values !== undefined) return { one: values.filter((value) => sides.every((side) => member(value, side.type))) };\n const known = sides.filter((side) => !isUnknown(side.type, undefined));\n const kept = known[0];\n if (kept === undefined) return \"unknown\";\n for (const side of known.slice(1)) this.issue([...at, side.key], `The type reads the keyword ${kept.key}, and not the keyword ${side.key}.`);\n return kept.type;\n }\n\n /** This method reads `enum` and `const`: the values that the schema permits, or `undefined` without them. */\n values(schema: Readonly<Record<string, unknown>>, at: readonly Key[]): Json[] | undefined {\n let values: Json[] | undefined;\n if (Object.hasOwn(schema, \"enum\")) {\n if (Array.isArray(schema[\"enum\"])) values = [...(schema[\"enum\"] as Json[])];\n else this.issue([...at, \"enum\"], \"The value of enum is a list of JSON values.\");\n }\n if (Object.hasOwn(schema, \"const\")) {\n const one = schema[\"const\"] as Json;\n values = values === undefined ? [one] : values.filter((value) => docEquals(value, one));\n }\n return values;\n }\n\n /** This method reads the keyword `type` with the keywords of an object and of an array. */\n byType(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const raw = schema[\"type\"];\n const names = typeof raw === \"string\" ? [raw] : Array.isArray(raw) ? raw : undefined;\n if (names === undefined) {\n this.issue([...at, \"type\"], \"The value of type is a text or a list of texts.\");\n return \"unknown\";\n }\n const types: ValueType[] = [];\n for (const [index, name] of names.entries()) {\n const where = typeof raw === \"string\" ? [...at, \"type\"] : [...at, \"type\", index];\n if (name === \"object\") types.push(this.object(schema, at, depth));\n else if (name === \"array\") types.push(this.array(schema, at, depth));\n else if (typeof name === \"string\" && Object.hasOwn(BASES, name)) {\n if (name === \"integer\") this.issue(where, \"The type reads integer as number. It does not test that the number is whole.\");\n types.push(BASES[name] as ValueType);\n } else {\n this.issue(where, `The type ${String(name)} is not a type of JSON Schema. The type reads it as unknown.`);\n return \"unknown\";\n }\n }\n return unionOf(types);\n }\n\n /** This method reads an object: its properties, the properties that it needs and the other properties. */\n object(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const fields: Record<string, ValueType> = {};\n const properties = schema[\"properties\"] ?? {};\n if (isRecord(properties)) {\n for (const key of Object.keys(properties)) setOwn(fields, key, this.read(properties[key], [...at, \"properties\", key], depth + 1));\n } else {\n this.issue([...at, \"properties\"], \"The value of properties is a record of schemas.\");\n }\n const required = schema[\"required\"] ?? [];\n const needed = Array.isArray(required) ? required.filter((key): key is string => typeof key === \"string\") : [];\n if (!Array.isArray(required) || needed.length !== required.length) this.issue([...at, \"required\"], \"The value of required is a list of texts.\");\n // A property that `required` names without a schema can hold each value.\n for (const key of needed) if (!Object.hasOwn(fields, key)) setOwn(fields, key, \"unknown\");\n const optional = Object.keys(fields).filter((key) => !needed.includes(key));\n const other = schema[\"additionalProperties\"];\n // Each property that a pattern names is permitted too, thus the record is closed only without patterns.\n let closed = other === false && !Object.hasOwn(schema, \"patternProperties\");\n if (other !== undefined && other !== true && other !== false) {\n this.issue([...at, \"additionalProperties\"], \"The type reads additionalProperties with a schema as an open record. The other fields can hold each value.\");\n closed = false;\n }\n return { record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) };\n }\n\n /** This method reads an array: the schema of its items. */\n array(schema: Readonly<Record<string, unknown>>, at: readonly Key[], depth: number): ValueType {\n const items = schema[\"items\"];\n if (items === undefined) return { list: \"unknown\" };\n // With prefixItems, the keyword items covers only the items after the prefix.\n if (Object.hasOwn(schema, \"prefixItems\") || Array.isArray(items)) {\n this.issue([...at, \"items\"], \"The type does not read the items of a tuple. It reads a list of unknown items.\");\n return { list: \"unknown\" };\n }\n return { list: this.read(items, [...at, \"items\"], depth + 1) };\n }\n}\n\n/**\n * This function makes a value type from a JSON Schema (TYPE.SCHEMA). A host uses it for the type of a root, for\n * example the schema of a store for `world`. It reads this subset:\n *\n * - `type`: `null`, `boolean`, `number`, `integer` (as `number`), `string`, `object` and `array`, or a list of them.\n * - `properties`, `required` and `additionalProperties` give a record. `false` closes it, and a property that is not\n * in `required` is optional.\n * - `items` gives a list. `enum` and `const` give `one`. `anyOf` and `oneOf` give a union.\n *\n * The type holds each value that the schema accepts. Each keyword that the function does not read tests nothing, as\n * `unknown`, and the issues name it. Examples are `minimum`, `pattern` and `allOf`. A schema with `$ref` or `nullable`\n * reads as `unknown`, because these keywords can permit more values. A schema with more than one of `type`, `anyOf`\n * and `oneOf` gives the type of the first, and an issue for each other. The function does not throw.\n *\n * @param schema - The schema, as JSON.\n * @returns The type, and the problems of the reading with their keys in the schema.\n */\nexport function typeFromSchema(schema: unknown): TypeReading {\n const reader = new SchemaReader();\n try {\n return { type: reader.read(schema, [], 0), issues: reader.issues };\n } catch (error) {\n // A getter of a host value can throw. The reading then gives the top.\n reader.issue([], `The schema cannot be read: ${error instanceof Error ? error.message : String(error)}`);\n return { type: \"unknown\", issues: reader.issues };\n }\n}\n\n/** The options of `typeFromSamples`. */\nexport interface SampleOptions {\n /** `true`: the samples show each field, thus each record type is closed. The default is `false`. */\n readonly closed?: boolean;\n}\n\n/** The deepest sample that `typeFromSamples` reads. A deeper value gives `unknown`. */\nconst MAX_SAMPLE_DEPTH = 256;\n\n/** This function gives the type of a group of sample values at one depth. */\nfunction samplesAt(values: readonly unknown[], closed: boolean, depth: number): ValueType {\n if (depth > MAX_SAMPLE_DEPTH) return values.length === 0 ? \"never\" : \"unknown\";\n const types: ValueType[] = [];\n const bases = new Set<string>();\n const items: unknown[] = [];\n const records: Readonly<Record<string, unknown>>[] = [];\n let lists = false;\n for (const value of values) {\n if (value === null) bases.add(\"null\");\n else if (value === undefined) bases.add(\"undefined\");\n else if (typeof value === \"boolean\") bases.add(\"bool\");\n else if (typeof value === \"number\") bases.add(\"number\");\n else if (typeof value === \"string\") bases.add(\"text\");\n else if (Array.isArray(value)) {\n lists = true;\n // A hole of a list holds undefined, thus a loop by index reads it too.\n for (let index = 0; index < value.length; index += 1) items.push(value[index]);\n } else if (isRecord(value)) records.push(value);\n // A value without a type of the kernel, for example a function, has each type.\n else return \"unknown\";\n }\n for (const base of [\"null\", \"undefined\", \"bool\", \"number\", \"text\"]) if (bases.has(base)) types.push(base);\n if (lists) types.push({ list: samplesAt(items, closed, depth + 1) });\n if (records.length > 0) {\n // All records join into one record. A field that a record does not have is optional.\n const keys: string[] = [];\n for (const record of records) for (const key of Object.keys(record)) if (!keys.includes(key)) keys.push(key);\n const fields: Record<string, ValueType> = {};\n const optional: string[] = [];\n for (const key of keys) {\n const found = records.filter((record) => Object.hasOwn(record, key));\n if (found.length < records.length) optional.push(key);\n setOwn(fields, key, samplesAt(found.map((record) => record[key]), closed, depth + 1));\n }\n types.push({ record: fields, ...(optional.length === 0 ? {} : { optional }), ...(closed ? { closed: true } : {}) });\n }\n return types.length === 1 ? (types[0] as ValueType) : unionOf(types);\n}\n\n/**\n * This function infers a value type from sample values (TYPE.SAMPLES), as a type provider of F# does. A host uses it\n * for the type of a root, for example from some events.\n *\n * - `null`, `undefined`, a truth value, a number and a text give their base types, not their values.\n * - The items of each list join into one type of items.\n * - All records join into one record with each key of the samples. A key that a record does not have is optional.\n * - Values of different forms give a union, as `join` gives. No samples give `never`.\n * - A value without a type of the kernel, for example a function, gives `unknown`.\n *\n * Each sample is a member of the type. A record is open, because samples do not show that a field cannot exist. With\n * `closed: true`, each record is closed, and a reference to a field that no sample has gives `#TYPE!`.\n *\n * @param values - The sample values.\n * @param options - `closed: true` closes each record type.\n * @returns The type.\n */\nexport function typeFromSamples(values: readonly unknown[], options: SampleOptions = {}): ValueType {\n return samplesAt(values, options.closed === true, 0);\n}\n"],"mappings":";;AAqCA,MAAa,gBAAgB;CAAC;CAAQ;CAAS;CAAQ;AAAK;;;;;;;;AAS5D,SAAgB,SAAS,OAAqC;CAC5D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,K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