{"version":3,"sources":["../src/testing/index.ts"],"names":["ExpectationError","_ExpectationError","init","createTestEngine","packages","options","locale","includeBuiltins","engine","ExpressionEngine","BUILTIN_PACKAGES","pkg","evaluate","expression","value","error","EngineError","message","Value","numbersEqual","a","b","epsilon","describeValue","describeOutcome","outcome","ExpressionAssertion","timeoutMs","DEFAULT_KIT_TIMEOUT_MS","deadline","remaining","settleWithin","expected","unit","describeExpected","matches","valueToComparableString","code","base","expectExpression","ms","linePending","line","solve","lineOutcome","DocumentAssertion","lines","lineNumber","expectDocument","text","evaluateDocument","COMMON_PROSE_WORDS","SEVERITY_ORDER","claimedWords","claimed","vocab","word","tokenType","phrase","PackageAssertion","words","prose","w","shadowed","c","list","s","others","strictness","report","checkPackageCompatibility","threshold","failing","engineVersion","ENGINE_VERSION","result","checkEngineVersionCompatibility","detail","problems","named","position","parselets","type","isFastPathToken","produced","op","name","builtinTypes","TokenTypes","ownTypes","builtinTokenCategory","registered","e","normalizeUnknownError","prefix","infix","read","p","unread","orphans","how","o","missing","sample","vocabularySamples","fn","samples","expectPackage"],"mappings":"+4JAyEO,IAAMA,EAAN,MAAMC,CAAAA,SAAyB,KAAM,CAQ3C,WAAA,CAAYC,EAA6E,CACxF,KAAA,CAAMA,CAAAA,CAAK,OAAO,EAClB,IAAA,CAAK,IAAA,CAAO,mBACZ,IAAA,CAAK,IAAA,CAAOA,EAAK,IAAA,CACjB,IAAA,CAAK,QAAA,CAAWA,CAAAA,CAAK,SACrB,IAAA,CAAK,MAAA,CAASA,EAAK,MAAA,CAGnB,MAAA,CAAO,eAAe,IAAA,CAAMD,CAAAA,CAAiB,SAAS,EACvD,CACD,EAyCO,SAASE,EAAAA,CACfC,EAA6B,EAAC,CAC9BC,EAA6B,EAAC,CACX,CACnB,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAS,KAAM,eAAA,CAAAC,CAAAA,CAAkB,IAAK,CAAA,CAAIF,CAAAA,CAK5CG,EAAS,IAAIC,mBAAAA,CAAiB,CAA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,CAAK,CAAA,EAAGpB,CAAI,CAAA,GAAA,CAAA,CAAO,CAAA,EAAGA,CAAI,CAAA,MAAA,CAAQ,CAAA,CACjG,OAAOoB,CACR,CAaO,SAASC,EAAAA,CAAchG,CAAAA,CAAuC,CACpE,OAAO,IAAIgD,CAAAA,CAAiBhD,CAAG,CAChC","file":"testing.cjs","sourcesContent":["/**\n * A test kit for package authors, the supported way to test a package by the\n * expressions it enables rather than by the opcodes it emits.\n *\n * Before this entry point a package author had two options, both bad: reach\n * into engine internals, or assert on whatever bytecode a parselet happened to\n * emit. The first is unstable across engine versions, the second pins the\n * implementation instead of the behaviour, so a refactor that keeps every\n * answer correct still breaks the tests. This module is a thin, dependency-free\n * layer over the same public surface a host uses: it constructs an\n * {@link ExpressionEngine} with the given packages and evaluates strings.\n *\n * It speaks in expressions. {@link expectExpression} evaluates a string and\n * asserts on the result or the failure code; {@link expectPackage} asserts on\n * the three mistakes a package actually makes (shadowing prose, colliding with\n * another package's vocabulary, and declaring an `engineVersion` range that the\n * running engine does not satisfy). {@link expectDocument} evaluates a whole\n * document and reads each line with the same matchers, and\n * {@link ExpressionAssertion.toResolveTo} waits for a live value to settle\n * before comparing it.\n *\n * Framework-agnostic on purpose. Nothing here imports jest, vitest or any\n * runner: an assertion that fails throws an {@link ExpectationError}, and one\n * that passes returns, so the kit drops into whatever runner the author already\n * has (or into a plain script, or `node:assert`). Runtime dependency-free and\n * side-effect free, so `solve-engine/testing` stays honest under the package's\n * `\"sideEffects\": false` contract.\n *\n * @example\n * ```ts\n * import { createTestEngine, expectExpression } from \"solve-engine/testing\";\n *\n * const engine = createTestEngine([myPackage]);\n * expectExpression(engine, \"2 gp + 3 gp\").toEqual(5, \"gp\");\n * expectExpression(engine, \"gp\").toFailWith(\"UNDEFINED_VARIABLE\");\n * await expectExpression(engine, \"tide at Dover\").toResolveTo(4.2, \"m\");\n * (await expectDocument(engine, \":x = 4\\nx * 2\")).line(2).toEqual(8);\n * ```\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { Value, ValueType } from \"@solve-js/vm/Value\";\nimport { EngineError } from \"@solve-js/errors/EngineError\";\nimport {\n\tcheckPackageCompatibility,\n\ttype CompatibilityReport,\n\ttype CompatibilityConflict,\n\ttype CompatibilitySeverity,\n} from \"@solve-js/api/PackageCompatibility\";\nimport { checkEngineVersionCompatibility } from \"@solve-js/api/EngineVersionCompatibility\";\nimport { ENGINE_VERSION } from \"@solve-js/constants/version\";\nimport { isFastPathToken } from \"@solve-js/parser/BindingPower\";\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { builtinTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport { normalizeUnknownError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { evaluateDocument } from \"@solve-js/engine/evaluateDocument\";\nimport type { ParsedLine } from \"@solve-js/types/ParsingResult\";\n\n//#region Errors\n\n/**\n * The failure a matcher throws when an expectation is not met.\n *\n * A dedicated `Error` subclass rather than a bare `throw new Error`, so a\n * caller (or a reporter) can tell a kit assertion failure apart from an\n * unrelated exception with `instanceof`, and so the structured `expected` and\n * `actual` fields survive alongside the human-readable message. This is NOT an\n * {@link EngineError}: that type classifies pipeline-stage failures inside the\n * engine, whereas this classifies a test-assertion mismatch, a different\n * concern that would be miscategorised under any of `EngineError`'s categories.\n */\nexport class ExpectationError extends Error {\n\t/** A short, machine-readable label for which expectation failed. */\n\treadonly code: string;\n\t/** What the matcher was told to expect, in plain words. */\n\treadonly expected?: string;\n\t/** What it found instead. */\n\treadonly actual?: string;\n\n\tconstructor(init: { code: string; message: string; expected?: string; actual?: string }) {\n\t\tsuper(init.message);\n\t\tthis.name = \"ExpectationError\";\n\t\tthis.code = init.code;\n\t\tthis.expected = init.expected;\n\t\tthis.actual = init.actual;\n\t\t// Restore the prototype chain across the ES5 `Error` transpile target,\n\t\t// so `instanceof ExpectationError` holds for callers.\n\t\tObject.setPrototypeOf(this, ExpectationError.prototype);\n\t}\n}\n\n//#endregion\n\n//#region createTestEngine\n\n/** Options for {@link createTestEngine}. */\nexport interface TestEngineOptions {\n\t/** Locale passed to the engine. Defaults to `\"en\"`. */\n\tlocale?: string;\n\t/**\n\t * Whether to load the engine's built-in packages (arithmetic, units, dates,\n\t * and the rest) before the packages under test. Defaults to `true`, because\n\t * almost every package builds on arithmetic and most authors want a\n\t * realistic engine. Set `false` to test a package in isolation.\n\t */\n\tincludeBuiltins?: boolean;\n}\n\n/**\n * Build an {@link ExpressionEngine} loaded with the packages under test.\n *\n * The built-in packages load first (unless {@link TestEngineOptions.includeBuiltins}\n * is `false`), then each package in `packages` is registered in order, exactly\n * as a host would. Registration is honest: a package whose declared\n * `engineVersion` the running engine does not satisfy, or whose lexer keyword\n * collides with a built-in, throws here rather than being swallowed. That is\n * deliberately different from passing packages straight to the\n * `ExpressionEngine` constructor, which contains a bad package by logging and\n * continuing, useful in production, wrong for a test that needs to know the\n * package it is testing actually loaded.\n *\n * Call {@link ExpressionEngine.clear} when a test is finished with the engine\n * if the test creates many, see the engine's own lifecycle note.\n *\n * @example\n * ```ts\n * const engine = createTestEngine([myPackage]);\n * const engineOnly = createTestEngine([myPackage], { includeBuiltins: false });\n * ```\n */\nexport function createTestEngine(\n\tpackages: IEnginePackage[] = [],\n\toptions: TestEngineOptions = {},\n): ExpressionEngine {\n\tconst { locale = \"en\", includeBuiltins = true } = options;\n\n\t// Built-ins go through the constructor (their own containment applies);\n\t// the packages under test go through registerPackage() afterwards so their\n\t// failures surface as thrown errors instead of being logged and skipped.\n\tconst engine = new ExpressionEngine({ locale, packages: includeBuiltins ? BUILTIN_PACKAGES : [] });\n\tfor (const pkg of packages) {\n\t\tengine.registerPackage(pkg);\n\t}\n\treturn engine;\n}\n\n//#endregion\n\n//#region expectExpression\n\n/**\n * The normalised outcome of evaluating one expression, computed once when\n * {@link expectExpression} runs and read by every matcher on the result.\n *\n * The engine surfaces a failure two different ways, and a package author should\n * not have to know which: a parse/eval error is THROWN as an\n * {@link EngineError} (with a `.code`), while a plugin-raised error is RETURNED\n * as a {@link Value} of {@link ValueType.Error} (its `value` is the code, its\n * `unit` is the message). Both collapse to the `\"error\"` status here. A value\n * still resolving asynchronously is its own `\"pending\"` status, since the kit\n * evaluates synchronously and cannot report a final number for it.\n */\ntype Outcome =\n\t| { status: \"value\"; value: Value }\n\t| { status: \"pending\"; value: Value }\n\t| { status: \"error\"; code: string; message: string; source: EngineError | Value };\n\n/** Evaluate `expression` on `engine` and collapse both failure shapes to one outcome. */\nfunction evaluate(engine: ExpressionEngine, expression: string): Outcome {\n\ttry {\n\t\tconst value = engine.evaluateExpression(expression);\n\t\tif (value.isError()) {\n\t\t\treturn {\n\t\t\t\tstatus: \"error\",\n\t\t\t\tcode: value.errorCode ?? \"\",\n\t\t\t\tmessage: value.errorMessage ?? \"\",\n\t\t\t\tsource: value,\n\t\t\t};\n\t\t}\n\t\tif (value.isPending()) {\n\t\t\treturn { status: \"pending\", value };\n\t\t}\n\t\treturn { status: \"value\", value };\n\t} catch (error) {\n\t\tif (error instanceof EngineError) {\n\t\t\treturn { status: \"error\", code: error.code, message: error.message, source: error };\n\t\t}\n\t\t// Anything else thrown (a bug in a plugin handler, say) is still a\n\t\t// failure, wrapped so the matcher has a code and message to report.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tstatus: \"error\",\n\t\t\tcode: \"UNKNOWN_ERROR\",\n\t\t\tmessage,\n\t\t\tsource: new Value(ValueType.Error, \"UNKNOWN_ERROR\", message),\n\t\t};\n\t}\n}\n\n/** Whether two numbers are equal within a small tolerance scaled to their magnitude. */\nfunction numbersEqual(a: number, b: number): boolean {\n\tif (Object.is(a, b)) return true;\n\tif (!Number.isFinite(a) || !Number.isFinite(b)) return false;\n\tconst epsilon = 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));\n\treturn Math.abs(a - b) <= epsilon;\n}\n\n/** A short, readable rendering of a value for an assertion message, e.g. `5 gp` or `\"abc\"`. */\nfunction describeValue(value: Value): string {\n\tif (value.type === ValueType.String) return JSON.stringify(value.value);\n\tif (value.type === ValueType.Uom && typeof value.unit === \"string\") {\n\t\treturn `${String(value.value)} ${value.unit}`;\n\t}\n\treturn String(value.value);\n}\n\n/** A short, readable rendering of an outcome for an assertion message. */\nfunction describeOutcome(outcome: Outcome): string {\n\tswitch (outcome.status) {\n\t\tcase \"value\":\n\t\t\treturn describeValue(outcome.value);\n\t\tcase \"pending\":\n\t\t\treturn \"a pending async value\";\n\t\tcase \"error\":\n\t\t\treturn `an error (${outcome.code}: ${outcome.message})`;\n\t}\n}\n\n/**\n * Assertions about the result of one evaluated expression, returned by\n * {@link expectExpression}. Every matcher returns `this`, so assertions chain,\n * and throws an {@link ExpectationError} when it fails.\n */\nexport class ExpressionAssertion {\n\t/**\n\t * @param expression - The text evaluated, named in every failure message.\n\t * @param outcome - What evaluating it gave.\n\t * @param engine - The engine it was evaluated on, which {@link settled}\n\t * re-evaluates on. Absent for a line of a document, whose outcome is final.\n\t */\n\tconstructor(\n\t\tprivate readonly expression: string,\n\t\tprivate outcome: Outcome,\n\t\tprivate readonly engine?: ExpressionEngine,\n\t) {}\n\n\t/**\n\t * Wait for a Pending result to settle, then re-evaluate, so every matcher\n\t * after it reads the settled answer: the value the live data resolved to,\n\t * or the fetch's coded failure.\n\t *\n\t * It loops within one deadline, because a line can reveal a second fetch\n\t * once its first lands: evaluate, {@link ExpressionEngine.settle}, evaluate\n\t * again, until the result is not Pending. A result that was never Pending\n\t * returns at once, without waiting.\n\t *\n\t * @param options.timeoutMs - The deadline for the whole loop, in\n\t * milliseconds. 5,000 by default.\n\t * @returns This assertion, now holding the settled outcome.\n\t * @throws ExpectationError `EXPECTED_SETTLED` (rejected) when the result is\n\t * still Pending at the deadline, or the assertion was built for a document\n\t * line rather than by {@link expectExpression}.\n\t */\n\tasync settled(options: SettleOptions = {}): Promise<this> {\n\t\tif (this.outcome.status !== \"pending\") return this;\n\t\tconst engine = this.engine;\n\t\tif (engine === undefined) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_SETTLED\",\n\t\t\t\tmessage: `\"${this.expression}\" is a document line, which expectDocument has already settled; it is still pending.`,\n\t\t\t\texpected: \"a settled value\",\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\tconst timeoutMs = options.timeoutMs ?? DEFAULT_KIT_TIMEOUT_MS;\n\t\tconst deadline = Date.now() + timeoutMs;\n\t\twhile (this.outcome.status === \"pending\") {\n\t\t\tconst remaining = deadline - Date.now();\n\t\t\tif (remaining <= 0 || !(await settleWithin(engine, remaining))) {\n\t\t\t\tthrow new ExpectationError({\n\t\t\t\t\tcode: \"EXPECTED_SETTLED\",\n\t\t\t\t\tmessage: `Expected \"${this.expression}\" to settle within ${timeoutMs} ms, but it was still a pending async value.`,\n\t\t\t\t\texpected: `a settled value within ${timeoutMs} ms`,\n\t\t\t\t\tactual: \"a pending async value\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.outcome = evaluate(engine, this.expression);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Wait for the result to settle (see {@link settled}), then assert it\n\t * equals `expected`, with `unit` when given, exactly as {@link toEqual}\n\t * does. The matcher for a package's async resolver: the first evaluation\n\t * is Pending by contract, and this is what it resolves to.\n\t *\n\t * @example\n\t * ```ts\n\t * await expectExpression(engine, \"tide at Dover\").toResolveTo(4.2, \"m\");\n\t * ```\n\t */\n\tasync toResolveTo(expected: number | string | boolean, unit?: string, options: SettleOptions = {}): Promise<this> {\n\t\tawait this.settled(options);\n\t\treturn this.toEqual(expected, unit);\n\t}\n\n\t/** The raw resolved {@link Value}, for an assertion the matchers do not cover. Throws if the expression failed. */\n\tget value(): Value {\n\t\tif (this.outcome.status === \"error\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_VALUE\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to evaluate, but it failed with ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: \"a resolved value\",\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\treturn this.outcome.value;\n\t}\n\n\t/**\n\t * Assert the expression evaluated to a value (not an error, not a pending\n\t * async result). Says nothing about what the value is.\n\t */\n\ttoEvaluate(): this {\n\t\tif (this.outcome.status !== \"value\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_EVALUATE\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to evaluate to a value, but got ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: \"a resolved value\",\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Assert the expression evaluated to `expected`, and, when `unit` is given,\n\t * that the result carries exactly that unit. A number compares against the\n\t * value's numeric magnitude within a small floating-point tolerance; a\n\t * string compares against the value's own string; a boolean against its\n\t * boolean reading. Omitting `unit` leaves the unit unchecked, so\n\t * `toEqual(5)` passes for both `5` and `5 gp`.\n\t */\n\ttoEqual(expected: number | string | boolean, unit?: string): this {\n\t\tif (this.outcome.status !== \"value\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_EQUAL\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to equal ${describeExpected(expected, unit)}, but got ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: describeExpected(expected, unit),\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\n\t\tconst value = this.outcome.value;\n\t\tlet matches: boolean;\n\t\tif (typeof expected === \"number\") {\n\t\t\tmatches = numbersEqual(value.toNumber(), expected);\n\t\t} else if (typeof expected === \"boolean\") {\n\t\t\t// A Boolean value stores the primitive directly; anything else can\n\t\t\t// never equal a boolean, so a mismatch reports the real value.\n\t\t\tmatches = value.type === ValueType.Boolean && value.value === expected;\n\t\t} else {\n\t\t\tmatches = valueToComparableString(value) === expected;\n\t\t}\n\n\t\tif (!matches) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_EQUAL\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to equal ${describeExpected(expected, unit)}, but it was ${describeValue(value)}.`,\n\t\t\t\texpected: describeExpected(expected, unit),\n\t\t\t\tactual: describeValue(value),\n\t\t\t});\n\t\t}\n\n\t\tif (unit !== undefined && value.unit !== unit) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_UNIT\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to carry the unit \"${unit}\", but it was ${value.unit === undefined ? \"unitless\" : `\"${value.unit}\"`}.`,\n\t\t\t\texpected: `unit \"${unit}\"`,\n\t\t\t\tactual: value.unit === undefined ? \"no unit\" : `unit \"${value.unit}\"`,\n\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/** Assert the expression failed (a thrown engine error or a plugin-raised error value). Says nothing about the code. */\n\ttoBeError(): this {\n\t\tif (this.outcome.status !== \"error\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_ERROR\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to fail, but it produced ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: \"an error\",\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Assert the expression failed with exactly `code`, the error catalog code\n\t * (e.g. `\"UNDEFINED_VARIABLE\"`, or a package's own code). Reports the code\n\t * it actually got when they differ, so a near-miss is obvious.\n\t */\n\ttoFailWith(code: string): this {\n\t\tif (this.outcome.status !== \"error\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_FAIL_WITH\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to fail with \"${code}\", but it produced ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: `error code \"${code}\"`,\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\tif (this.outcome.code !== code) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_FAIL_WITH\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to fail with \"${code}\", but it failed with \"${this.outcome.code}\" (${this.outcome.message}).`,\n\t\t\t\texpected: `error code \"${code}\"`,\n\t\t\t\tactual: `error code \"${this.outcome.code}\"`,\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Assert the expression returned a value still resolving asynchronously.\n\t * A package whose result comes from an async resolver reports pending on\n\t * first evaluation; this is how a test confirms the async path was taken\n\t * without waiting for it. {@link toResolveTo} waits and checks the answer.\n\t */\n\ttoBePending(): this {\n\t\tif (this.outcome.status !== \"pending\") {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_PENDING\",\n\t\t\t\tmessage: `Expected \"${this.expression}\" to be pending, but got ${describeOutcome(this.outcome)}.`,\n\t\t\t\texpected: \"a pending async value\",\n\t\t\t\tactual: describeOutcome(this.outcome),\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n}\n\n/** Render an expected value (with optional unit) for an assertion message. */\nfunction describeExpected(expected: number | string | boolean, unit?: string): string {\n\tconst base = typeof expected === \"string\" ? JSON.stringify(expected) : String(expected);\n\treturn unit === undefined ? base : `${base} ${unit}`;\n}\n\n/** The string a non-numeric value compares against in {@link ExpressionAssertion.toEqual}. */\nfunction valueToComparableString(value: Value): string {\n\t// The stored primitive stringified. For a String value this is the string\n\t// itself; for a Hex value, its `0x...` text, which is what an author writes\n\t// in a `toEqual(\"0xff\")` assertion.\n\treturn String(value.value);\n}\n\n/**\n * Evaluate `expression` on `engine` and return an assertion object.\n *\n * The expression is evaluated once, immediately, and every matcher reads that\n * one outcome, so calling several matchers on the same result does not\n * re-evaluate.\n *\n * @example\n * ```ts\n * expectExpression(engine, \"2 gp + 3 gp\").toEqual(5, \"gp\");\n * expectExpression(engine, \"gp\").toFailWith(\"UNDEFINED_VARIABLE\");\n * ```\n */\nexport function expectExpression(engine: ExpressionEngine, expression: string): ExpressionAssertion {\n\treturn new ExpressionAssertion(expression, evaluate(engine, expression), engine);\n}\n\n//#endregion\n\n//#region Settling live values\n\n/** Options for the kit's waiting matchers, {@link ExpressionAssertion.settled}, {@link ExpressionAssertion.toResolveTo} and {@link expectDocument}. */\nexport interface SettleOptions {\n\t/** The deadline for the whole wait, in milliseconds. 5,000 by default. */\n\ttimeoutMs?: number;\n}\n\n/** The kit's default deadline: long enough for a stub resolver, short enough that a test runner's own timeout is not what reports a hang. */\nconst DEFAULT_KIT_TIMEOUT_MS = 5_000;\n\n/**\n * Await {@link ExpressionEngine.settle} within `ms`, answering whether it\n * settled. A `SETTLE_TIMEOUT` is the \"no\" answer; any other failure (a\n * `timeoutMs` the engine refuses) is passed on as it is.\n */\nasync function settleWithin(engine: ExpressionEngine, ms: number): Promise<boolean> {\n\ttry {\n\t\tawait engine.settle({ timeoutMs: ms });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error instanceof EngineError && error.code === \"SETTLE_TIMEOUT\") return false;\n\t\tthrow error;\n\t}\n}\n\n/** Whether a document line, or any inline solve on it, is still Pending. */\nfunction linePending(line: ParsedLine): boolean {\n\tif (line.result?.isPending()) return true;\n\treturn line.inlineSolves.some((solve) => solve.result?.isPending() === true);\n}\n\n/** A document line's outcome in the shape the matchers read, from its result or its recorded failure. */\nfunction lineOutcome(line: ParsedLine): Outcome {\n\tif (line.error !== null) {\n\t\tconst code = line.errorCode ?? \"\";\n\t\treturn { status: \"error\", code, message: line.error, source: new Value(ValueType.Error, code, line.error) };\n\t}\n\tconst value = line.result;\n\tif (value === null) {\n\t\treturn { status: \"error\", code: \"EXPECTED_EXPRESSION\", message: \"the line holds nothing to evaluate\", source: new Value(ValueType.Error, \"EXPECTED_EXPRESSION\", \"the line holds nothing to evaluate\") };\n\t}\n\tif (value.isError()) {\n\t\treturn { status: \"error\", code: value.errorCode ?? \"\", message: value.errorMessage ?? \"\", source: value };\n\t}\n\tif (value.isPending()) return { status: \"pending\", value };\n\treturn { status: \"value\", value };\n}\n\n/**\n * Assertions about a whole evaluated document, returned by {@link expectDocument}.\n * Each line is read with the same matchers {@link expectExpression} returns.\n */\nexport class DocumentAssertion {\n\t/**\n\t * @param lines - Every line of the settled document, in order.\n\t */\n\tconstructor(readonly lines: readonly ParsedLine[]) {}\n\n\t/**\n\t * The matchers for line `lineNumber` (one-based), reading the answer the\n\t * document gave it: a line reference, a tag or a goal seek on it resolves\n\t * as it does in an editor. A line with nothing to evaluate (prose, a\n\t * heading, a blank) fails every matcher but {@link ExpressionAssertion.toBeError}.\n\t *\n\t * @throws ExpectationError `EXPECTED_LINE` for a line number the document does not have.\n\t */\n\tline(lineNumber: number): ExpressionAssertion {\n\t\tconst line = Number.isInteger(lineNumber) && lineNumber >= 1 ? this.lines[lineNumber - 1] : undefined;\n\t\tif (line === undefined) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"EXPECTED_LINE\",\n\t\t\t\tmessage: `The document has ${this.lines.length} line(s), so there is no line ${String(lineNumber)}.`,\n\t\t\t\texpected: `a line number from 1 to ${this.lines.length}`,\n\t\t\t\tactual: String(lineNumber),\n\t\t\t});\n\t\t}\n\t\treturn new ExpressionAssertion(`line ${lineNumber}: ${line.text}`, lineOutcome(line));\n\t}\n}\n\n/**\n * Evaluate `text` as a whole document on `engine`, wait for any live values\n * it starts to settle, and return per-line matchers.\n *\n * The document goes through the incremental pass a live editor uses\n * (`evaluateDocument`), so every whole-document form resolves: line\n * references, category tags, table columns and goal seek. While any line is\n * Pending, the kit awaits {@link ExpressionEngine.settle} and evaluates the\n * document again, until none is or the deadline passes. A line still Pending\n * at the deadline is left Pending, for {@link ExpressionAssertion.toBePending}\n * to confirm or another matcher to report.\n *\n * @example\n * ```ts\n * const doc = await expectDocument(engine, \":rate = 4%\\n1000 * rate\");\n * doc.line(2).toEqual(40);\n * ```\n */\nexport async function expectDocument(engine: ExpressionEngine, text: string, options: SettleOptions = {}): Promise<DocumentAssertion> {\n\tconst deadline = Date.now() + (options.timeoutMs ?? DEFAULT_KIT_TIMEOUT_MS);\n\tlet lines = evaluateDocument(engine, text).lines;\n\twhile (lines.some(linePending)) {\n\t\tconst remaining = deadline - Date.now();\n\t\tif (remaining <= 0 || !(await settleWithin(engine, remaining))) break;\n\t\tlines = evaluateDocument(engine, text).lines;\n\t}\n\treturn new DocumentAssertion(lines);\n}\n\n//#endregion\n\n//#region expectPackage\n\n/**\n * A modest set of everyday English words a package's keywords should not claim.\n *\n * A starting point for {@link PackageAssertion.notToShadow}, not an exhaustive\n * dictionary: it leans on the function words and common nouns/verbs a package\n * is most tempted to grab as a trigger (`price`, `of`, `per`, `sum`, `total`).\n * Pass your own list to check against the specific prose your package sits in.\n */\nexport const COMMON_PROSE_WORDS: readonly string[] = [\n\t\"a\", \"an\", \"and\", \"or\", \"but\", \"if\", \"then\", \"the\", \"this\", \"that\", \"these\", \"those\",\n\t\"in\", \"on\", \"at\", \"to\", \"of\", \"for\", \"from\", \"with\", \"by\", \"as\", \"per\", \"into\", \"over\",\n\t\"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"do\", \"does\", \"did\", \"have\", \"has\", \"had\",\n\t\"will\", \"would\", \"can\", \"could\", \"should\", \"may\", \"might\", \"must\",\n\t\"price\", \"cost\", \"value\", \"total\", \"sum\", \"count\", \"rate\", \"amount\", \"number\",\n\t\"time\", \"date\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\",\n\t\"add\", \"buy\", \"sell\", \"hold\", \"make\", \"take\", \"give\", \"get\", \"set\", \"run\",\n\t\"up\", \"down\", \"out\", \"off\", \"all\", \"some\", \"any\", \"no\", \"not\", \"more\", \"less\",\n\t\"one\", \"two\", \"three\", \"first\", \"last\", \"next\", \"each\", \"every\", \"here\", \"there\",\n];\n\n/** How strict {@link PackageAssertion.notToCollideWith} is about the conflicts it will accept. */\nexport type CollisionStrictness = \"error\" | \"warning\" | \"info\";\n\n/** One shadowed word found by {@link PackageAssertion.notToShadow}: the prose word and how the package claims it. */\nexport interface ShadowedWord {\n\t/** The prose word the package claims. */\n\tword: string;\n\t/** Which descriptor field claims it. */\n\tvia: \"keyword\" | \"unit\" | \"operator\" | \"phrase\";\n\t/** The token type the word becomes, when the field maps to one. */\n\ttokenType?: string;\n}\n\n/** Severities at or above the strictness threshold, ordered most to least severe. */\nconst SEVERITY_ORDER: CompatibilitySeverity[] = [\"error\", \"warning\", \"info\"];\n\n/** Gather the single words a package claims through its declared vocabulary, which is where prose shadowing comes from. */\nfunction claimedWords(pkg: IEnginePackage): ShadowedWord[] {\n\tconst claimed: ShadowedWord[] = [];\n\tconst vocab = pkg.lexerVocabulary;\n\tif (vocab?.keywords) {\n\t\tfor (const [word, tokenType] of Object.entries(vocab.keywords)) {\n\t\t\tclaimed.push({ word, via: \"keyword\", tokenType });\n\t\t}\n\t}\n\tif (vocab?.units) {\n\t\tfor (const word of vocab.units) {\n\t\t\tclaimed.push({ word, via: \"unit\" });\n\t\t}\n\t}\n\tif (vocab?.operators) {\n\t\tfor (const [word, tokenType] of Object.entries(vocab.operators)) {\n\t\t\tclaimed.push({ word, via: \"operator\", tokenType });\n\t\t}\n\t}\n\tif (pkg.phrases) {\n\t\tfor (const [phrase, tokenType] of Object.entries(pkg.phrases)) {\n\t\t\t// A multi-word phrase is the SAFE pattern the trigger-words guide\n\t\t\t// recommends (`next friday` reserves neither word), so only a\n\t\t\t// single-word phrase can shadow a prose word.\n\t\t\tif (!phrase.includes(\" \")) {\n\t\t\t\tclaimed.push({ word: phrase, via: \"phrase\", tokenType });\n\t\t\t}\n\t\t}\n\t}\n\treturn claimed;\n}\n\n/**\n * Assertions about a package's declared descriptor, returned by\n * {@link expectPackage}. These catch the three mistakes the issue calls out,\n * before the package is ever registered. Every matcher returns `this` and\n * throws an {@link ExpectationError} when it fails.\n */\nexport class PackageAssertion {\n\tconstructor(private readonly pkg: IEnginePackage) {}\n\n\t/**\n\t * Assert none of the package's claimed words shadow a prose word.\n\t *\n\t * A trigger word that is also an ordinary word turns a line of prose into\n\t * arithmetic, the single most common package mistake and the subject of the\n\t * trigger-words guide. This checks the words the package declares\n\t * (lexer keywords, units, operators, and single-word phrases) against\n\t * `words` (defaulting to {@link COMMON_PROSE_WORDS}), case-insensitively.\n\t *\n\t * @returns the shadowed words, empty when the package is clean, for a test\n\t * that wants to inspect rather than assert.\n\t */\n\tnotToShadow(words: readonly string[] = COMMON_PROSE_WORDS): ShadowedWord[] {\n\t\tconst prose = new Set(words.map((w) => w.toLowerCase()));\n\t\tconst shadowed = claimedWords(this.pkg).filter((c) => prose.has(c.word.toLowerCase()));\n\t\tif (shadowed.length > 0) {\n\t\t\tconst list = shadowed.map((s) => `\"${s.word}\" (${s.via})`).join(\", \");\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"PACKAGE_SHADOWS_PROSE\",\n\t\t\t\tmessage: `Package \"${this.pkg.name}\" claims prose word(s) as syntax: ${list}. A word that is also ordinary English turns prose into arithmetic; prefer a multi-word phrase or a form that requires a parenthesis.`,\n\t\t\t\texpected: \"no prose words claimed as syntax\",\n\t\t\t\tactual: list,\n\t\t\t});\n\t\t}\n\t\treturn shadowed;\n\t}\n\n\t/**\n\t * Assert the package does not collide with any of `others` in a way that\n\t * would silently break one of them (two packages claiming the same lexer\n\t * keyword, plugin-function index, async-resolver namespace, and so on).\n\t *\n\t * `strictness` sets which severities fail the assertion: `\"error\"` (the\n\t * default) fails only on the collisions that always break something,\n\t * `\"warning\"` also fails on the ones that silently pick a winner, `\"info\"`\n\t * fails on cosmetic overlaps too.\n\t *\n\t * @returns the full compatibility report, so a test can inspect every\n\t * conflict, including ones below the strictness threshold.\n\t */\n\tnotToCollideWith(\n\t\tothers: IEnginePackage[],\n\t\tstrictness: CollisionStrictness = \"error\",\n\t): CompatibilityReport {\n\t\tconst report = checkPackageCompatibility(this.pkg, others);\n\t\tconst threshold = SEVERITY_ORDER.indexOf(strictness);\n\t\tconst failing = report.conflicts.filter(\n\t\t\t(c: CompatibilityConflict) => SEVERITY_ORDER.indexOf(c.severity) <= threshold,\n\t\t);\n\t\tif (failing.length > 0) {\n\t\t\tconst list = failing.map((c) => `[${c.severity}] ${c.detail}`).join(\"\\n\");\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"PACKAGE_VOCABULARY_COLLISION\",\n\t\t\t\tmessage: `Package \"${this.pkg.name}\" collides with another package:\\n${list}`,\n\t\t\t\texpected: `no conflicts at or above \"${strictness}\" severity`,\n\t\t\t\tactual: `${failing.length} conflict(s)`,\n\t\t\t});\n\t\t}\n\t\treturn report;\n\t}\n\n\t/**\n\t * Assert the package's declared `engineVersion` range is satisfied by the\n\t * running engine (or by `engineVersion` when given).\n\t *\n\t * A package that declares a range and never checks it resolves is the third\n\t * mistake the issue names: it looks fine until the one engine version it\n\t * cannot run against, where the range either fails to match or turns out to\n\t * be a malformed string. A package with no declared range passes (no\n\t * constraint is always compatible).\n\t */\n\ttoDeclareCompatibleEngineVersion(engineVersion: string = ENGINE_VERSION): this {\n\t\tconst result = checkEngineVersionCompatibility(this.pkg, engineVersion);\n\t\tif (!result.compatible) {\n\t\t\tconst detail =\n\t\t\t\tresult.reason === \"invalid-range\"\n\t\t\t\t\t? `its range \"${result.declaredRange}\" is not valid semver`\n\t\t\t\t\t: `its range \"${result.declaredRange}\" is not satisfied by engine version \"${result.engineVersion}\"`;\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"PACKAGE_ENGINE_VERSION_INCOMPATIBLE\",\n\t\t\t\tmessage: `Package \"${this.pkg.name}\" declares an engineVersion that will be rejected at registration: ${detail}.`,\n\t\t\t\texpected: `an engineVersion satisfied by \"${engineVersion}\"`,\n\t\t\t\tactual: `\"${result.declaredRange}\"`,\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Assert the package is put together so every part it declares can be\n\t * reached (#719). Each of these used to be accepted without a word and then\n\t * fail, or never run, at the first line that used it:\n\t *\n\t * - it has a name (registration keys everything by name, so a second\n\t *   nameless package unregistered the first);\n\t * - it registers against the built-ins;\n\t * - a token its keywords, operators, phrases or calls produce that no\n\t *   parselet reads is not meant for a parselet the package keys under\n\t *   another name (`twice` making `DOUBLE_KW` while the parselet waits for\n\t *   `DOUBLE`). A token read inside another parselet's grammar (the `and`\n\t *   of `between X and Y`) is not a mistake, and is not reported;\n\t * - no parselet claims a token the parser reads itself (`NUMBER`, `+`,\n\t *   ...), where it would never run;\n\t * - each token type of its own has a `tokenCategories` entry, so an editor\n\t *   can colour it;\n\t * - each plugin function its parselets call by name is in `pluginFunctions`,\n\t *   found by compiling the package's own words in the shapes a line puts\n\t *   them in (`word 1`, `word(1)`, `1 op 1`). A call reached only by some\n\t *   other shape is not seen.\n\t *\n\t * Every problem is reported at once rather than the first alone.\n\t */\n\ttoBeWellFormed(): this {\n\t\tconst pkg = this.pkg;\n\t\tconst problems: string[] = [];\n\t\tconst named = typeof pkg.name === \"string\" && pkg.name.trim() !== \"\";\n\t\tif (!named) problems.push(\"it has no name, and registration keeps everything by name\");\n\n\t\tfor (const position of [\"prefix\", \"infix\"] as const) {\n\t\t\tconst parselets = position === \"prefix\" ? pkg.prefixParselets : pkg.infixParselets;\n\t\t\tfor (const type of Object.keys(parselets ?? {})) {\n\t\t\t\tif (isFastPathToken(type, position)) {\n\t\t\t\t\tproblems.push(`its ${position} parselet for \"${type}\" never runs: the parser reads that token itself, before it consults the registry`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// The tokens the package's own vocabulary makes, and what makes each.\n\t\tconst produced = new Map<string, string>();\n\t\tfor (const [word, type] of Object.entries(pkg.lexerVocabulary?.keywords ?? {})) produced.set(type, `the keyword \"${word}\"`);\n\t\tfor (const [op, type] of Object.entries(pkg.lexerVocabulary?.operators ?? {})) produced.set(type, `the operator \"${op}\"`);\n\t\tfor (const [phrase, type] of Object.entries(pkg.phrases ?? {})) produced.set(type, `the phrase \"${phrase}\"`);\n\t\tfor (const [name, type] of Object.entries(pkg.callFusions ?? {})) produced.set(type, `the call \"${name}(\"`);\n\n\t\tconst builtinTypes = new Set<string>(Object.values(TokenTypes));\n\t\tconst ownTypes = new Set<string>([\n\t\t\t...produced.keys(),\n\t\t\t...Object.keys(pkg.prefixParselets ?? {}),\n\t\t\t...Object.keys(pkg.infixParselets ?? {}),\n\t\t].filter((type) => !builtinTypes.has(type)));\n\t\tfor (const type of ownTypes) {\n\t\t\tif (pkg.tokenCategories?.[type] === undefined && builtinTokenCategory(type) === undefined) {\n\t\t\t\tproblems.push(`its token \"${type}\" has no tokenCategories entry, so an editor cannot colour it`);\n\t\t\t}\n\t\t}\n\n\t\tif (named) {\n\t\t\tconst engine = new ExpressionEngine({ packages: BUILTIN_PACKAGES });\n\t\t\tlet registered = false;\n\t\t\ttry {\n\t\t\t\tengine.registerPackage(pkg);\n\t\t\t\tregistered = true;\n\t\t\t} catch (e) {\n\t\t\t\tproblems.push(`it does not register: ${normalizeUnknownError(e).message}`);\n\t\t\t}\n\t\t\tif (registered) {\n\t\t\t\ttry {\n\t\t\t\t\tconst { prefix, infix } = engine.getParseletRegistry();\n\t\t\t\t\tconst read = new Set([...prefix.map((p) => p.tokenType), ...infix.map((p) => p.tokenType)]);\n\t\t\t\t\t// A parselet keyed by a token nothing the package declares makes,\n\t\t\t\t\t// beside a declared token nothing reads, is the one mistake this\n\t\t\t\t\t// can name without guessing: the two were meant to be one. A\n\t\t\t\t\t// package with normalizer rules may make the parselet's token in\n\t\t\t\t\t// one, so it is not asked.\n\t\t\t\t\tconst unread = [...produced].filter(([type]) => !read.has(type));\n\t\t\t\t\tconst orphans = pkg.normalizerRules !== undefined && pkg.normalizerRules.length > 0\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: [...Object.keys(pkg.prefixParselets ?? {}), ...Object.keys(pkg.infixParselets ?? {})]\n\t\t\t\t\t\t\t.filter((type) => !produced.has(type) && !builtinTypes.has(type));\n\t\t\t\t\tif (orphans.length > 0) {\n\t\t\t\t\t\tfor (const [type, how] of unread) {\n\t\t\t\t\t\t\tproblems.push(`${how} makes the token \"${type}\", which no parselet reads, while the parselet for ${orphans.map((o) => `\"${o}\"`).join(\" or \")} reads a token nothing in the package makes: were they meant to be one?`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst missing = new Set<string>();\n\t\t\t\t\tfor (const sample of vocabularySamples(pkg)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tengine.compileExpression(sample);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tconst error = normalizeUnknownError(e);\n\t\t\t\t\t\t\tconst fn = (error.context as { functionName?: string } | undefined)?.functionName;\n\t\t\t\t\t\t\tif (error.code === \"UNKNOWN_PLUGIN_FUNCTION\" && fn !== undefined && !missing.has(fn)) {\n\t\t\t\t\t\t\t\tmissing.add(fn);\n\t\t\t\t\t\t\t\tproblems.push(`\"${sample}\" calls the plugin function \"${fn}\", which pluginFunctions does not declare`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tengine.unregisterPackage(pkg.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (problems.length > 0) {\n\t\t\tthrow new ExpectationError({\n\t\t\t\tcode: \"PACKAGE_NOT_WELL_FORMED\",\n\t\t\t\tmessage: `Package \"${String(pkg.name)}\" is not well formed:\\n- ${problems.join(\"\\n- \")}`,\n\t\t\t\texpected: \"every part the package declares can be reached\",\n\t\t\t\tactual: `${problems.length} problem(s)`,\n\t\t\t});\n\t\t}\n\t\treturn this;\n\t}\n}\n\n/**\n * The lines {@link PackageAssertion.toBeWellFormed} compiles to find the\n * plugin functions a package's parselets call: each word, operator, phrase and\n * call of its own, in the shapes a line usually puts it in.\n */\nfunction vocabularySamples(pkg: IEnginePackage): string[] {\n\tconst samples: string[] = [];\n\tfor (const word of Object.keys(pkg.lexerVocabulary?.keywords ?? {})) {\n\t\tsamples.push(word, `${word} 1`, `${word}(1)`, `${word}(1, 2)`, `1 ${word} 1`, `${word} 1 and 2`);\n\t}\n\tfor (const op of Object.keys(pkg.lexerVocabulary?.operators ?? {})) samples.push(`1 ${op} 1`, `${op} 1`);\n\tfor (const phrase of Object.keys(pkg.phrases ?? {})) samples.push(phrase, `${phrase} 1`, `1 ${phrase} 1`);\n\tfor (const name of Object.keys(pkg.callFusions ?? {})) samples.push(`${name}(1)`, `${name}(1, 2)`);\n\treturn samples;\n}\n\n/**\n * Begin an assertion about a package's declared descriptor.\n *\n * @example\n * ```ts\n * expectPackage(myPackage).notToShadow([\"price\", \"in\", \"of\"]);\n * expectPackage(myPackage).notToCollideWith(BUILTIN_PACKAGES);\n * expectPackage(myPackage).toDeclareCompatibleEngineVersion();\n * expectPackage(myPackage).toBeWellFormed();\n * ```\n */\nexport function expectPackage(pkg: IEnginePackage): PackageAssertion {\n\treturn new PackageAssertion(pkg);\n}\n\n//#endregion\n"]}