validup 0.5.1 → 1.0.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.
- package/README.md +18 -0
- package/dist/index.d.mts +282 -27
- package/dist/index.mjs +519 -265
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -4
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["interpolate"],"sources":["../src/utils/has-own-property.ts","../src/utils/object.ts","../src/container/check.ts","../src/error/base.ts","../src/issue/check.ts","../src/issue/constants.ts","../src/issue/define.ts","../src/issue/flatten.ts","../src/issue/format.ts","../src/error/check.ts","../src/helpers/error-to-issues.ts","../src/helpers/one-of-failed.ts","../src/helpers/compose.ts","../src/helpers/create-error.ts","../src/helpers/defaults.ts","../src/helpers/error.ts","../src/constants.ts","../src/helpers/optional-value.ts","../src/helpers/path-filter.ts","../src/helpers/path-stringify.ts","../src/validator/check.ts","../src/validator/define.ts","../src/container/run-sync-violation.ts","../src/container/module.ts","../src/builder/module.ts","../src/cache/check.ts","../src/cache/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown> {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function isObject(input: unknown) : input is Record<string, any> {\n return !!input &&\n typeof input === 'object' &&\n !Array.isArray(input);\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isObject } from '../utils';\nimport type { IContainer } from './types';\n\nexport function isContainer(input: unknown) : input is IContainer {\n return isObject(input) &&\n typeof input.run === 'function' &&\n typeof input.safeRun === 'function';\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from '@ebec/core';\nimport { buildErrorMessageForAttributes, stringifyPath } from '../helpers';\nimport type { Issue } from '../issue';\n\nexport class ValidupError extends BaseError {\n readonly issues: Issue[];\n\n constructor(issues: Issue[] = []) {\n const paths = issues.map((issue) => stringifyPath(issue.path));\n super({ message: buildErrorMessageForAttributes(paths) });\n\n this.issues = issues;\n }\n\n override toJSON(): ReturnType<BaseError['toJSON']> & { issues: Issue[] } {\n return {\n ...super.toJSON(),\n issues: this.issues,\n };\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isObject } from '../utils';\nimport type {\n Issue, \n IssueBase, \n IssueGroup, \n IssueItem,\n} from './types';\n\nfunction isIssuePath(input: unknown) : input is PropertyKey[] {\n if (!Array.isArray(input)) {\n return false;\n }\n\n return input.every((el) => typeof el === 'string' ||\n typeof el === 'number' ||\n typeof el === 'symbol');\n}\n\nfunction isBaseIssue(input: unknown) : input is IssueBase & { [ke: string]: any } {\n if (!isObject(input)) {\n return false;\n }\n\n if (typeof input.message !== 'string') {\n return false;\n }\n\n if (!isIssuePath(input.path)) {\n return false;\n }\n\n return typeof input.meta === 'undefined' ||\n isObject(input.meta);\n}\n\nexport function isIssueItem(input: unknown) : input is IssueItem {\n if (!isBaseIssue(input)) {\n return false;\n }\n\n if (input.type !== 'item') {\n return false;\n }\n\n return typeof input.code === 'string';\n}\n\nexport function isIssueGroup(input: unknown) : input is IssueGroup {\n if (!isBaseIssue(input)) {\n return false;\n }\n\n if (input.type !== 'group') {\n return false;\n }\n\n return Array.isArray(input.issues) &&\n input.issues.every((issue) => isIssueItem(issue) || isIssueGroup(issue));\n}\n\nexport function isIssue(input: unknown) : input is Issue {\n return isIssueGroup(input) || isIssueItem(input);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Vocabulary of well-known issue codes. Adapter packages map foreign\n * validator codes onto these so consumer-side translation catalogs\n * (e.g. `@ilingo/validup`) can ship one localized message per code\n * instead of falling back to a generic \"invalid value\" fallback.\n *\n * Tracks the common ground between vuelidate, zod, joi, and yup. The\n * core lifts from vuelidate's catalog (snake_cased to match validup's\n * convention); modern format codes (`PATTERN`, `UUID`, `DATE`,\n * `JSON`, `BASE64`, `STRONG_PASSWORD`, …) cover ground vuelidate\n * predates. Every format code names the format positively (`UUID`,\n * `EMAIL`, `URL`, …) rather than the failure mode (`NOT_UUID`,\n * `INVALID_EMAIL`) so the registry reads consistently.\n *\n * Ad-hoc / project-specific codes still work — `IssueItem.code` is\n * widened to `IssueCode | (string & {})`, so `defineIssueItem({ code:\n * 'email_taken', ... })` is valid. If you want a typed const for your\n * own codes, define one alongside this one:\n *\n * ```ts\n * import { IssueCode } from 'validup';\n *\n * export const AppCode = {\n * ...IssueCode,\n * EMAIL_TAKEN: 'email_taken',\n * } as const;\n * ```\n *\n * Each entry's JSDoc documents the structured `data` adapters should\n * attach when constructing the issue — templates can rely on those\n * placeholders being present (`{{min}}`, `{{max}}`, `{{other}}`, etc.).\n */\nexport const IssueCode = {\n // ──────────────────────────── Generic / structural ────────────────────────────\n /** Generic fallback when no more-specific code applies. `data`: — */\n VALUE_INVALID: 'value_invalid',\n /** Every branch of a `oneOf` container failed. `data`: — */\n ONE_OF_FAILED: 'one_of_failed',\n\n // ──────────────────────────── Presence ────────────────────────────\n /** Value is missing, `undefined`, `null`, or empty per the validator's semantics. `data`: — */\n REQUIRED: 'required',\n\n // ──────────────────────────── Type assertions ────────────────────────────\n /** Value contains characters outside the alphabetical set. `data`: — */\n ALPHA: 'alpha',\n /** Value contains characters outside the alphanumeric set. `data`: — */\n ALPHA_NUM: 'alpha_num',\n /** Value is not a number. `data`: — */\n NUMERIC: 'numeric',\n /** Value is not an integer. `data`: — */\n INTEGER: 'integer',\n /** Value is not a decimal number. `data`: — */\n DECIMAL: 'decimal',\n\n // ──────────────────────────── Length (strings, arrays) ────────────────────────────\n /** Value is shorter than the configured minimum. `data`: `{ min: number }` */\n MIN_LENGTH: 'min_length',\n /** Value is longer than the configured maximum. `data`: `{ max: number }` */\n MAX_LENGTH: 'max_length',\n\n // ──────────────────────────── Numeric range ────────────────────────────\n /** Numeric value is below the configured minimum. `data`: `{ min: number }` */\n MIN_VALUE: 'min_value',\n /** Numeric value is above the configured maximum. `data`: `{ max: number }` */\n MAX_VALUE: 'max_value',\n /** Numeric value falls outside the configured `[min, max]` range. `data`: `{ min: number, max: number }` */\n BETWEEN: 'between',\n\n // ──────────────────────────── String format ────────────────────────────\n /** Value is not a valid email address. `data`: — */\n EMAIL: 'email',\n /** Value is not a valid URL. `data`: — */\n URL: 'url',\n /** Value is not a valid IP address. `data`: — */\n IP_ADDRESS: 'ip_address',\n /** Value is not a valid MAC address. `data`: — */\n MAC_ADDRESS: 'mac_address',\n /** Value is not a valid UUID. `data`: — */\n UUID: 'uuid',\n /** Value is not a valid date / cannot be parsed as a date. `data`: — */\n DATE: 'date',\n /**\n * Value does not match the expected regex pattern. `data`:\n * `{ pattern: string }` — source of the regex without flags so\n * catalogs can quote it in human-readable form.\n */\n PATTERN: 'pattern',\n /** Value is not valid JSON. `data`: — */\n JSON: 'json',\n /** Value is not valid base64. `data`: — */\n BASE64: 'base64',\n /**\n * Value does not meet the configured strong-password rules. `data`:\n * `{ minLength?: number, minLowercase?: number, minUppercase?: number,\n * minNumbers?: number, minSymbols?: number }` — only the keys the\n * adapter chose to surface; missing keys mean \"the default for that\n * setting wasn't configured.\"\n */\n STRONG_PASSWORD: 'strong_password',\n\n // ──────────────────────────── Comparison ────────────────────────────\n /**\n * Value must equal another named field's value (sibling-field assertion,\n * e.g. password-confirm). `data`: `{ other: string }` — the name of\n * the field being compared against.\n */\n SAME_AS: 'same_as',\n} as const;\n\nexport type IssueCode = typeof IssueCode[keyof typeof IssueCode];\n\n/**\n * Per-code `data` contract for the well-known vocabulary. Producers\n * (`defineIssueItem`, `createValidupError`, adapter `error.ts` modules)\n * thread this through their type signatures so TS rejects mismatched\n * payloads at compile time — e.g. `STRONG_PASSWORD` with `data:\n * { pointsPerUnique: 5 }` (a validator.js scoring weight, not a strength\n * requirement) fails to type-check. Codes absent from this map carry no\n * `data`; ad-hoc string codes fall back to the open\n * `Record<string, unknown>` shape on the raw `IssueItem` branch.\n *\n * Extensible via TypeScript declaration merging — third-party adapters\n * and apps that want typed data for their own codes can augment this\n * interface, and the producer-side gatekeep (`defineIssueItem`,\n * `createValidupError`) will type-check their payloads too:\n *\n * ```ts\n * // In a third-party package or app:\n * declare module 'validup' {\n * interface IssueDataByCode {\n * email_taken: { existingUserId: string };\n * }\n * }\n *\n * defineIssueItem({\n * code: 'email_taken',\n * path: ['email'],\n * message: 'Already in use',\n * data: { existingUserId: 'u_42' }, // typed and required\n * });\n * ```\n *\n * Keep entries here in lockstep with the JSDoc on the corresponding\n * `IssueCode` entry — the type-level enforcement and the documentation\n * are two views of the same contract.\n */\nexport interface IssueDataByCode {\n min_length: { min: number };\n max_length: { max: number };\n min_value: { min: number };\n max_value: { max: number };\n between: { min: number, max: number };\n pattern: { pattern: string };\n strong_password: {\n minLength?: number,\n minLowercase?: number,\n minUppercase?: number,\n minNumbers?: number,\n minSymbols?: number,\n };\n same_as: { other: string };\n}\n\n/**\n * `IssueCode` values that carry a documented `data` payload — keys of\n * {@link IssueDataByCode}. Producers using one of these codes must\n * supply the matching `data` shape.\n */\nexport type ParameterizedIssueCode = keyof IssueDataByCode;\n\n/**\n * `IssueCode` values that carry no `data` (`VALUE_INVALID`, `EMAIL`,\n * `REQUIRED`, …). Producers using one of these codes must omit `data`\n * (or pass `undefined`).\n */\nexport type BareIssueCode = Exclude<IssueCode, ParameterizedIssueCode>;\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { IssueCode } from './constants';\nimport type {\n BareIssueCode,\n IssueDataByCode,\n ParameterizedIssueCode,\n} from './constants';\nimport type {\n IssueBase,\n IssueGroup,\n IssueItem,\n IssueItemBare,\n IssueItemRaw,\n IssueItemTyped,\n ResolveIssueCode,\n} from './types';\n\ninterface DefineIssueItemCommon extends Omit<IssueBase, 'data'> {\n received?: unknown,\n expected?: unknown,\n}\n\n/**\n * Per-call `data` shape for {@link defineIssueItem}. The `data`\n * requirement is selected from the resolved `code`:\n *\n * - Parameterized code → `data` required, typed per {@link IssueDataByCode}.\n * - Bare code (incl. omitted, which resolves to `VALUE_INVALID`)\n * → `data` must be absent / `undefined`.\n * - Ad-hoc string code → `data` optional `Record`.\n */\ntype DefineIssueItemData<C> = DefineIssueItemCommon & {\n code?: C,\n} & (\n ResolveIssueCode<C> extends ParameterizedIssueCode ?\n { data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode] } :\n ResolveIssueCode<C> extends BareIssueCode ?\n { data?: undefined } :\n { data?: Record<string, unknown> }\n);\n\n/**\n * Return type for {@link defineIssueItem} — picks the concrete `IssueItem`\n * variant matching the resolved `code`.\n */\ntype DefineIssueItemReturn<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ?\n Extract<IssueItemTyped, { code: ResolveIssueCode<C> }> :\n ResolveIssueCode<C> extends BareIssueCode ?\n Extract<IssueItemBare, { code: ResolveIssueCode<C> }> :\n IssueItemRaw;\n\n/**\n * Build an `IssueItem`. TS uses the supplied `code` to pick the right\n * `data` requirement at the call site — passing `MIN_LENGTH` without\n * `data: { min }` is a compile error; passing `STRONG_PASSWORD` with\n * `data: { pointsPerUnique: 5 }` is a compile error.\n *\n * `code` may be omitted (defaults to `IssueCode.VALUE_INVALID` — bare,\n * no data).\n */\nexport function defineIssueItem<C extends string | undefined = undefined>(\n data: DefineIssueItemData<C>,\n): DefineIssueItemReturn<C> {\n return {\n type: 'item',\n ...data,\n code: (data as { code?: string }).code || IssueCode.VALUE_INVALID,\n } as unknown as DefineIssueItemReturn<C>;\n}\n\nexport function defineIssueGroup(data: Omit<IssueGroup, 'type'>): IssueGroup {\n return {\n type: 'group',\n ...data,\n };\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isIssueGroup, isIssueItem } from './check';\nimport type { Issue, IssueGroup, IssueItem } from './types';\n\nexport function flattenIssueItems(issues: Issue[]): IssueItem[] {\n const output: IssueItem[] = [];\n for (const issue of issues) {\n if (isIssueItem(issue)) {\n output.push(issue);\n } else {\n output.push(...flattenIssueItems(issue.issues));\n }\n }\n return output;\n}\n\nexport function flattenIssueGroups(issues: Issue[]): IssueGroup[] {\n const output: IssueGroup[] = [];\n for (const issue of issues) {\n if (isIssueGroup(issue)) {\n output.push(issue);\n output.push(...flattenIssueGroups(issue.issues));\n }\n }\n return output;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { interpolate } from '@ebec/core';\nimport type { IssueCode } from './constants';\nimport type { Issue } from './types';\n\n/**\n * Map of issue `code` → message template. Templates use `{name}` placeholders\n * — the same syntax `@ebec/core`'s `interpolate` understands — and are\n * resolved against `Issue.data` at format time.\n *\n * ```ts\n * const de: IssueMessageTemplates = {\n * value_invalid: 'Wert ist ungültig',\n * one_of_failed: 'Keine der Varianten war erfolgreich',\n * };\n * ```\n */\nexport type IssueMessageTemplates = Partial<Record<IssueCode, string>> & Record<string, string>;\n\n/**\n * Render an issue's user-facing message.\n *\n * Resolution order:\n * 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.\n * 2. Else return `issue.message` (the default English rendering set at\n * construction time).\n * 3. Else return `fallback`.\n */\nexport function formatIssue(\n issue: Issue,\n templates?: IssueMessageTemplates,\n fallback: string = '',\n): string {\n if (templates && issue.code) {\n const template = templates[issue.code];\n if (typeof template === 'string') {\n return interpolate(template, issue.data || {});\n }\n }\n if (typeof issue.message === 'string' && issue.message.length > 0) {\n return issue.message;\n }\n return fallback;\n}\n\n// Re-export ebec's `interpolate` so consumers writing custom formatters don't\n// need a direct dependency on `@ebec/core`. Same `{name}` placeholder syntax.\nexport { interpolate } from '@ebec/core';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isIssue } from '../issue';\nimport { hasOwnProperty, isObject } from '../utils';\nimport { ValidupError } from './base';\n\nexport function isError(input: unknown) : input is Error & { [key: string]: any } {\n // Primary check: anything that walks like an Error in this realm.\n // Keeps cross-realm fallbacks (e.g. errors from another iframe / vm\n // context where `instanceof Error` is false) duck-typed via the\n // `message` shape — which also matches `ValidupError`-shaped throws\n // from a duplicate copy of the package.\n if (input instanceof Error) {\n return true;\n }\n\n if (!isObject(input)) {\n return false;\n }\n\n return typeof input.message === 'string' && typeof input.name === 'string';\n}\n\nexport function isValidupError(error: unknown) : error is ValidupError {\n if (!isError(error)) {\n return false;\n }\n\n if (error instanceof ValidupError) {\n return true;\n }\n\n if (!hasOwnProperty(error, 'issues')) {\n return false;\n }\n\n return Array.isArray(error.issues) &&\n error.issues.every((issue) => isIssue(issue));\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isError, isValidupError } from '../error';\nimport { IssueCode, defineIssueItem } from '../issue';\nimport type { Issue } from '../issue';\n\n/**\n * Options for {@link errorToIssues}. Defaults match what the\n * orchestrating helpers (compose's collect-all catch, composeAnyOf's\n * branch-failure path) want out of the box.\n */\nexport type ErrorToIssuesOptions = {\n /**\n * Code stamped on the synthetic `IssueItem` when the thrown value\n * is an `Error` or a non-`Error` throw. Defaults to\n * `IssueCode.VALUE_INVALID`. `ValidupError` issues are spread\n * verbatim and DO NOT get this code applied; their own codes are\n * preserved.\n */\n code?: IssueCode | (string & {}),\n /**\n * Path on the synthetic `IssueItem`. Defaults to `[]`.\n * `ValidupError` issues are spread verbatim with their original\n * paths intact — callers that want to prefix or transform spread\n * paths should do so after this fold (the surrounding Container\n * run loop does this in `prefixIssuePath`, for example).\n */\n path?: PropertyKey[],\n};\n\n/**\n * The \"given an unknown throw, produce `Issue[]`\" cascade shared by\n * the validator-orchestrating helpers. The branching is identical\n * at each site — `ValidupError` fans out, `Error` becomes one item,\n * anything else gets a defensive stringify — so it lives here.\n *\n * - `ValidupError` → returns a fresh array containing each of its\n * `issues` verbatim (callers can map/prefix after).\n * - `Error` → returns one `IssueItem` carrying the message + supplied\n * code/path.\n * - Anything else (string, plain object, `null`, …) → returns one\n * defensively-stringified `IssueItem` so the aggregate is never\n * silently missing a contributing failure.\n *\n * Callers layer their own per-site concerns on top of the returned\n * issues: path prefixing, optional stamping, per-branch index\n * stamping, etc.\n */\nexport function errorToIssues(\n error: unknown,\n options: ErrorToIssuesOptions = {},\n): Issue[] {\n const code = options.code ?? IssueCode.VALUE_INVALID;\n const path = options.path ?? [];\n\n if (isValidupError(error)) {\n return [...error.issues];\n }\n\n if (isError(error)) {\n return [defineIssueItem({\n path,\n code,\n message: error.message,\n })];\n }\n\n return [defineIssueItem({\n path,\n code,\n message: typeof error === 'string' && error.length > 0 ?\n error :\n `Non-Error throw: ${String(error)}`,\n })];\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { IssueCode, defineIssueGroup } from '../issue';\nimport type { Issue, IssueGroup } from '../issue';\n\n/**\n * Options for {@link buildOneOfFailedGroup}.\n */\nexport type BuildOneOfFailedGroupOptions = {\n /**\n * Path on the wrapping group. Defaults to `[]` — most callers\n * (compose's `composeAnyOf`, the run-loop entry to a oneOf\n * container) emit the group at the boundary they own and let the\n * surrounding context attach a path.\n */\n path?: PropertyKey[],\n /**\n * Override the default English message. The wrapping group\n * carries `code: IssueCode.ONE_OF_FAILED`, so i18n catalogs key\n * off the code rather than the message; the message is only the\n * fallback rendering.\n */\n message?: string,\n};\n\n/**\n * Build the `IssueGroup` that wraps an every-branch-failed aggregate\n * — used by `composeAnyOf` (validator-level oneOf) AND\n * `Container.finalizeOutput` (container-level `oneOf` option). Sharing\n * the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so\n * consumers / i18n catalogs only need one format for both modes.\n */\nexport function buildOneOfFailedGroup(\n branchIssues: Issue[],\n options: BuildOneOfFailedGroupOptions = {},\n): IssueGroup {\n return defineIssueGroup({\n code: IssueCode.ONE_OF_FAILED,\n message: options.message ?? 'None of the branches succeeded',\n path: options.path ?? [],\n issues: branchIssues,\n });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isContainer } from '../container/check';\nimport type { IContainer } from '../container/types';\nimport { ValidupError } from '../error';\nimport type { Issue } from '../issue';\nimport { isObject } from '../utils';\nimport { errorToIssues } from './error-to-issues';\nimport { buildOneOfFailedGroup } from './one-of-failed';\nimport type { Validator, ValidatorContext } from '../validator';\n\n/**\n * A composable element — either a bare `Validator<C>` function or a\n * fully-built `IContainer<T, C>` instance. Containers participate\n * with the same contract as validators (transform-or-throw); the\n * dispatcher (`invokeComposeElement`) hides the call-shape difference.\n *\n * `IContainer<any, any>` (rather than something tighter) keeps the\n * compose array heterogeneous — a chain can mix schemas / containers\n * with different output shapes without forcing the caller to widen\n * generics at every call site. The cost is that the composed\n * `Validator`'s `Out` defaults to `unknown` (same as before).\n */\nexport type ComposeElement<C = unknown> = Validator<C> | IContainer<any, any>;\n\n/**\n * Options for {@link compose}. Discriminated on `oneOf` so the type\n * surface enforces the (`bail` × `oneOf`) combinations that actually\n * make sense:\n *\n * - `{}` / `{ bail?: boolean }` / `{ oneOf: false }` — the **all**\n * strategy: every validator must pass, stages thread their return\n * value into the next, `bail` controls fail-fast vs. collect-all.\n * - `{ oneOf: true }` — the **any-of** strategy: the first branch to\n * succeed wins and the composed validator returns its value;\n * `bail` is rejected at compile time because there's no chain to\n * bail out of.\n */\nexport type ComposeOptions = {\n /**\n * Run every validator and require all to pass (default). Stages\n * thread their return into the next; `bail` controls whether the\n * first failure stops the chain (`true`, default) or every failure\n * is collected into one aggregate `ValidupError` (`false`).\n *\n * **Threading rule.** A stage's return replaces the threaded\n * `ctx.value` only when defined — `undefined` is treated as a\n * pass-through so pure checks that don't re-emit `ctx.value`\n * compose cleanly with transformers. Stages that DO want to\n * explicitly clear the field must throw or return a sentinel.\n */\n oneOf?: false,\n bail?: boolean,\n} | {\n /**\n * Run branches as alternatives in registration order — the first\n * one to succeed wins, subsequent branches are not invoked, and\n * the composed validator returns the winning branch's value\n * (falling back to `ctx.value` if the winning branch returned\n * `undefined`). When *every* branch fails, the composed validator\n * throws a `ValidupError` whose first issue is an `IssueGroup`\n * with `code: IssueCode.ONE_OF_FAILED` carrying every branch's\n * collected failures (per-branch index surfaced via\n * `data: { branch }`). Symmetric with\n * `Container.options.oneOf`, just at the validator level.\n *\n * Each branch sees the original `ctx.value` — no threading\n * across alternatives, since branches aren't a pipeline.\n * `bail` is intentionally rejected at the type level under this\n * mode: there's no chain to fail-fast over.\n */\n oneOf: true,\n};\n\n/**\n * Compose multiple validators into a single `Validator`.\n *\n * Default (`oneOf: false`) — validators run in order; each stage's\n * return value feeds the next as `ctx.value`. A stage that returns\n * `undefined` is treated as a pass-through (upstream value continues\n * down the chain), so pure checks that don't re-emit `ctx.value`\n * compose cleanly with transformers. `bail: true` (default) stops at\n * the first failure; `bail: false` collects every failure into a\n * single `ValidupError`.\n *\n * `oneOf: true` — branches run as alternatives in registration order;\n * the first branch to succeed wins and subsequent branches are not\n * invoked. When every branch fails, the composed validator throws a\n * `ValidupError` whose first issue is an `IssueGroup` with\n * `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.\n *\n * Elements can be bare `Validator<C>` functions OR fully-built\n * `IContainer<T, C>` instances — the dispatcher detects which and\n * either calls the function with the threaded `ctx` or invokes the\n * container's `run(value, { group, context, signal, path })` with\n * the threaded value as input. Containers participate with the same\n * transform-or-throw contract; their output replaces the threaded\n * value in the all-strategy chain, and a successful container wins\n * the branch in `oneOf` mode.\n *\n * @example\n * // Fail-fast (default) — sanitize then validate\n * container.mount('email', compose([\n * trim(),\n * isEmail(),\n * isLength({ max: 254 }),\n * ]));\n *\n * // Collect-all — surface every broken rule for a richer error UI\n * container.mount('password', compose([\n * isLength({ min: 8 }),\n * isAlphanumeric(),\n * matches(/[0-9]/),\n * ], { bail: false }));\n *\n * // Any-of — accept either an email or a phone number on the same field\n * container.mount('contact', compose([\n * isEmail(),\n * isMobilePhone(),\n * ], { oneOf: true }));\n *\n * // Any-of with a container branch — accept a contact string OR a\n * // nested address object validated by its own container.\n * container.mount('contact', composeOneOf([\n * isEmail(),\n * isMobilePhone(),\n * addressContainer,\n * ]));\n *\n * Throws that aren't `ValidupError` / `Error` (raw strings, plain\n * objects, null) are synthesized into a single `IssueItem` so the\n * aggregate is never silently missing a contributing failure — mirrors\n * `Container.recordMountError`'s defensive behavior.\n */\nexport function compose<C = unknown>(\n elements: ComposeElement<C>[],\n options: ComposeOptions = {},\n): Validator<C> {\n if (options.oneOf === true) {\n return composeAnyOf(elements);\n }\n\n const bail = options.bail ?? true;\n\n return async (ctx) => {\n const issues: Issue[] = [];\n let { value } = ctx;\n\n for (const element of elements) {\n try {\n // Spread a fresh ctx per stage so the threaded value\n // doesn't leak back to the caller via the input\n // reference — callers that compose inside their own\n // validator can keep reading `ctx.value` after the\n // composed call returns without seeing the post-thread\n // mutation.\n const result = await invokeComposeElement(element, { ...ctx, value });\n if (typeof result !== 'undefined') {\n value = result;\n }\n } catch (e) {\n if (bail) {\n throw e;\n }\n\n // Failing stage doesn't get to mutate the threaded\n // value — `value` keeps whatever the last successful\n // stage produced, so the next validator runs against a\n // well-defined input. Use the shared `errorToIssues`\n // cascade so the ValidupError / Error / non-Error fold\n // stays in lockstep with composeAnyOf and other\n // call sites.\n for (const issue of errorToIssues(e)) {\n issues.push(issue);\n }\n }\n }\n\n if (issues.length > 0) {\n throw new ValidupError(issues);\n }\n\n return value;\n };\n}\n\n/**\n * Sugar for `compose(elements, { oneOf: true })`. Reads more\n * naturally at the call site when the alternative semantic is the\n * intent, mirrors `Container`'s own `oneOf` option.\n */\nexport function composeOneOf<C = unknown>(\n elements: ComposeElement<C>[],\n): Validator<C> {\n return compose(elements, { oneOf: true });\n}\n\n/**\n * The `oneOf` execution path. Carved out so `compose`'s body stays\n * focused on the all-strategy chain and so the abort / per-branch\n * issue plumbing has somewhere to live without nesting.\n *\n * Each branch sees the original `ctx.value` (no threading across\n * alternatives). The first defined return wins; an `undefined` return\n * from a successful branch falls back to `ctx.value` so the\n * pass-through rule stays symmetric with the all-strategy path.\n *\n * Aborts are re-raised verbatim from inside the try (matches Container\n * behavior): a cancelled run isn't a validation outcome to wrap.\n */\nfunction composeAnyOf<C>(elements: ComposeElement<C>[]): Validator<C> {\n return async (ctx) => {\n const branchIssues: Issue[] = [];\n\n for (const [index, element] of elements.entries()) {\n // Pre-branch abort check — short-circuits cleanly before we\n // enter the per-branch try/catch, so aborts never get\n // rewritten into branch-failure issues.\n ctx.signal?.throwIfAborted();\n\n try {\n const result = await invokeComposeElement(element, { ...ctx });\n // First branch to succeed wins — pass-through rule:\n // if the winning branch didn't bother re-emitting\n // `ctx.value`, surface the input as the output.\n return typeof result === 'undefined' ? ctx.value : result;\n } catch (e) {\n // Cancellations from a branch validator surface\n // verbatim instead of being folded into a branch\n // failure — caller can distinguish \"no branch matched\"\n // from \"operation cancelled\".\n if (ctx.signal?.aborted) {\n throw e;\n }\n\n const wrapped = wrapBranchIssues(e, index);\n for (const issue of wrapped) {\n branchIssues.push(issue);\n }\n }\n }\n\n // Every branch (including the empty-branch-list case) failed.\n // Use the shared `buildOneOfFailedGroup` so consumers /\n // i18n catalogs handle compose's any-of the same way they\n // handle `Container.options.oneOf`.\n throw new ValidupError([buildOneOfFailedGroup(branchIssues)]);\n };\n}\n\n/**\n * Dispatch one compose element against the current `ctx`. Containers\n * receive `ctx.value` as their input (normalised to `{}` for non-object\n * values, mirroring how the `Container.run` loop handles a nested\n * container mounted against a non-object value); validators receive\n * `ctx` itself.\n *\n * Forwarded to the child container's `run`:\n *\n * - `group`, `context`, `signal` — the threaded run-level options\n * surfaced on `ctx`. Letting the child see `ctx.signal` matters for\n * aborting in-flight child validation when the outer run is\n * cancelled.\n * - `path: ctx.path` — used by the child's mounts to compute their\n * own `ctx.path`, so a validator inside the child sees the\n * absolute path it sits at (`['foo', 'street']`, not just\n * `['street']`). Issue *paths* in the final thrown error don't\n * depend on this forwarding — the outer Container's\n * `prefixIssuePath` step rebuilds them from each level's own\n * `keyParts` — but validators that inspect `ctx.path` (for\n * logging, custom error formatting, etc.) would see a misleading\n * relative path without it.\n * - `cache: ctx.cache` — the outer Container surfaces its run-level\n * `IResultCache` on `ctx`, so threading it here keeps a\n * container-as-branch participating in the same per-mount cache\n * the outer container is using. Without this forward, mounts\n * inside a compose-branch container would silently bypass the\n * cache, breaking the cache contract for the\n * `composeOneOf([…, childContainer])` shape.\n *\n * Other run-level options (`pathsToInclude`, `pathsToExclude`,\n * `defaults`, `parallel`) are intentionally NOT forwarded — they're\n * normally narrowed per-mount by the parent's run loop\n * (`resolvePathFilter`, `resolveDefaults`), and compose doesn't have\n * the parent mount key it would need to compute the equivalent\n * narrowing. A `composeOneOf` branch that's a container therefore\n * runs all of its mounts regardless of the outer's include/exclude\n * filter; if you need that level of inheritance, mount the container\n * directly with `container.mount(...)` instead of routing it through\n * compose.\n */\nasync function invokeComposeElement<C>(\n element: ComposeElement<C>,\n ctx: ValidatorContext<C>,\n): Promise<unknown> {\n if (isContainer(element)) {\n return element.run(\n isObject(ctx.value) ? ctx.value : {},\n {\n path: ctx.path,\n group: ctx.group,\n context: ctx.context,\n signal: ctx.signal,\n cache: ctx.cache,\n },\n );\n }\n // `isContainer` narrows `element` to `IContainer`, but the\n // negative branch leaves it as the original union — TypeScript\n // doesn't subtract `IContainer` from a union containing\n // `Validator<C>` because their structural shapes overlap\n // (functions are objects). Cast to recover the call signature.\n return (element as Validator<C>)(ctx);\n}\n\n/**\n * Normalize one branch's failure into `Issue[]` ready to merge into\n * the outer `ONE_OF_FAILED` group. Each issue is tagged with\n * `data: { branch: index }` so a tree-walking consumer can report\n * \"branch N failed because ...\" without needing to reconstruct\n * registration order.\n *\n * Delegates the unknown-throw → `Issue[]` fold to the shared\n * `errorToIssues` cascade; only the per-branch stamping is local\n * concern. Spread issues are shallow-cloned before stamping so the\n * `ValidupError` instance's `issues` array on the caller side isn't\n * mutated when a consumer reads `.data.branch` later.\n */\nfunction wrapBranchIssues(error: unknown, index: number): Issue[] {\n const stamp = <I extends Issue>(issue: I): I => {\n issue.data = { ...(issue.data ?? {}), branch: index };\n return issue;\n };\n return errorToIssues(error).map((issue) => stamp({ ...issue }));\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ValidupError } from '../error';\nimport { defineIssueItem } from '../issue';\nimport type { \n BareIssueCode, \n IssueCode, \n IssueDataByCode, \n ParameterizedIssueCode, \n ResolveIssueCode, \n} from '../issue';\n\n/**\n * Trailing-args shape selected by the resolved `code`:\n *\n * - Parameterized code → `data` is required and typed.\n * - Bare code → no trailing arg accepted.\n * - Ad-hoc string code → `data?: Record<string, unknown>` optional.\n */\ntype CreateValidupErrorTail<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ?\n [data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode]] :\n ResolveIssueCode<C> extends BareIssueCode ?\n [] :\n [data?: Record<string, unknown>];\n\n/**\n * Build a `ValidupError` carrying a single `IssueItem` with the supplied\n * code / message / data. Sugar for the common one-issue failure\n * construction used by adapters and hand-rolled validators.\n *\n * The caller throws — keeping the `throw` keyword at the call site\n * makes the failure path obvious in the validator function body:\n *\n * ```ts\n * if (!validator.isEmail(s)) {\n * throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');\n * }\n *\n * if (!isInRange(s)) {\n * throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });\n * }\n * ```\n *\n * The `code` you pass selects the `data` requirement at compile time:\n * parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their\n * typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any\n * other string falls through to an open `Record<string, unknown>` data\n * argument.\n *\n * For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),\n * build a `ValidupError` directly with\n * `new ValidupError([defineIssueItem(...), …])`.\n */\nexport function createValidupError<C extends string = typeof IssueCode.VALUE_INVALID>(\n received: unknown,\n code: C,\n message: string,\n ...rest: CreateValidupErrorTail<C>\n): ValidupError {\n const data = rest[0] as Record<string, unknown> | undefined;\n return new ValidupError([\n defineIssueItem({\n path: [],\n message,\n code,\n data,\n received,\n } as Parameters<typeof defineIssueItem>[0]),\n ]);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Slice a parent `defaults` map down to entries that target paths inside a\n * single nested container mount, with the mount-key prefix stripped so the\n * child sees them as local keys. Exact-key matches (the default targets the\n * mount root itself) are skipped — the parent's post-loop fill handles those\n * once the child has returned, since the child is run with `flat: true` and\n * cannot address its own root.\n */\nexport function resolveDefaults(\n defaults: Record<string, any> | undefined,\n key: string,\n): Record<string, any> | undefined {\n if (typeof defaults === 'undefined') {\n return undefined;\n }\n if (key.length === 0) {\n return defaults;\n }\n\n const output: Record<string, any> = {};\n let matched = false;\n const keys = Object.keys(defaults);\n for (const k of keys) {\n if (k.startsWith(`${key}.`)) {\n output[k.slice(key.length + 1)] = defaults[k];\n matched = true;\n }\n }\n return matched ? output : undefined;\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { distinctArray } from 'smob';\n\nexport function buildErrorMessageForAttribute(key: PropertyKey) {\n return `Property ${String(key)} is invalid`;\n}\n\nexport function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>) {\n let names: PropertyKey[];\n if (Array.isArray(input)) {\n names = distinctArray(input);\n } else {\n names = Object.keys(input);\n }\n\n if (names.length === 0) {\n return 'Properties are invalid';\n }\n\n if (names.length > 1) {\n return `Properties ${names.join(', ')} are invalid.`;\n }\n\n return buildErrorMessageForAttribute(names[0]);\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum GroupKey {\n WILDCARD = '*',\n}\n\n/**\n * Atomic vocabulary for `MountOptions.optionalValue`. Each atom matches\n * exactly one runtime value (the exception is `FALSY`, which stays as a\n * composite shortcut). Compose multiple atoms by passing an array:\n * `optionalValue: ['undefined', 'null', 'empty_string']`.\n */\nexport enum OptionalValue {\n /**\n * `value === undefined`. **Default** when `optionalValue` is not set,\n * so the core stays conservative — `0` / `''` / `false` are real\n * values and reach the validator unless the caller opts in.\n */\n UNDEFINED = 'undefined',\n /** `value === null` (does **not** include `undefined`). */\n NULL = 'null',\n /** `value === ''`. */\n EMPTY_STRING = 'empty_string',\n /** `value === 0` (also matches `-0`). */\n ZERO = 'zero',\n /** `value === false`. */\n FALSE = 'false',\n /** `Number.isNaN(value)`. */\n NAN = 'nan',\n /**\n * Composite shortcut — any JS falsy value\n * (`undefined`, `null`, `''`, `0`, `false`, `NaN`). Use when you\n * really mean \"any of the JS falsy sentinels\"; otherwise pick\n * specific atoms (or compose an array) so a `0` / `false` / `''`\n * with a meaningful semantic isn't silently swallowed.\n */\n FALSY = 'falsy',\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { OptionalValue } from '../constants';\n\nexport type OptionalValueInput = `${OptionalValue}` | readonly `${OptionalValue}`[];\n\n/**\n * Check whether `value` qualifies as \"optional\" under the supplied\n * `optionalValue` definition.\n *\n * The definition can be a single atom (`'undefined'`, `'null'`, `'empty_string'`,\n * `'zero'`, `'false'`, `'nan'`, `'falsy'`) or an array of atoms — in array form\n * the value is optional iff **any** atom matches. Atoms match exactly one\n * runtime value (the only exception is `'falsy'`, which stays as a composite\n * shortcut for \"any JS falsy value\"). To skip on `null` *or* `undefined`,\n * pass `['null', 'undefined']` explicitly.\n *\n * Default is `'undefined'` so the core stays conservative — `0` / `''` /\n * `false` reach the validator unless the caller explicitly opts in.\n */\nexport function isOptionalValue(\n value: unknown,\n optionalValue?: OptionalValueInput,\n) {\n const input = optionalValue ?? OptionalValue.UNDEFINED;\n if (Array.isArray(input)) {\n for (const atom of input) {\n if (matchAtom(value, atom)) {\n return true;\n }\n }\n return false;\n }\n return matchAtom(value, input as `${OptionalValue}`);\n}\n\nfunction matchAtom(value: unknown, atom: `${OptionalValue}`): boolean {\n switch (atom) {\n case OptionalValue.UNDEFINED:\n return typeof value === 'undefined';\n case OptionalValue.NULL:\n return value === null;\n case OptionalValue.EMPTY_STRING:\n return value === '';\n case OptionalValue.ZERO:\n return value === 0;\n case OptionalValue.FALSE:\n return value === false;\n case OptionalValue.NAN:\n return typeof value === 'number' && Number.isNaN(value);\n case OptionalValue.FALSY:\n return !value;\n default:\n return false;\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport type PathFilterResolution = {\n skip: boolean,\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n};\n\n/**\n * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's\n * (already-expanded) local `key`. Returns whether to skip the item, plus the\n * filter sub-lists to forward into a child container — with the parent prefix\n * stripped so the child can match purely against its own local keys.\n *\n * Semantics:\n * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so\n * filters are forwarded verbatim.\n * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.\n * - Prefix match (`<key>.…`) only descends into container mounts; leaf\n * validators with deeper-target filters fall through (skipped for include,\n * kept for exclude).\n */\nexport function resolvePathFilter(\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n key: string,\n isContainer: boolean,\n): PathFilterResolution {\n if (key.length === 0) {\n return {\n skip: false,\n pathsToInclude,\n pathsToExclude,\n };\n }\n\n let includeForward: string[] | undefined;\n if (typeof pathsToInclude !== 'undefined') {\n let exact = false;\n const stripped: string[] = [];\n for (const path of pathsToInclude) {\n if (path === key) {\n exact = true;\n } else if (isContainer && path.startsWith(`${key}.`)) {\n stripped.push(path.slice(key.length + 1));\n }\n }\n if (exact) {\n includeForward = undefined;\n } else if (stripped.length > 0) {\n includeForward = stripped;\n } else {\n return {\n skip: true,\n pathsToInclude: undefined,\n pathsToExclude: undefined,\n };\n }\n }\n\n let excludeForward: string[] | undefined;\n if (typeof pathsToExclude !== 'undefined') {\n const stripped: string[] = [];\n for (const path of pathsToExclude) {\n if (path === key) {\n return {\n skip: true,\n pathsToInclude: undefined,\n pathsToExclude: undefined,\n };\n }\n if (isContainer && path.startsWith(`${key}.`)) {\n stripped.push(path.slice(key.length + 1));\n }\n }\n if (stripped.length > 0) {\n excludeForward = stripped;\n }\n }\n\n return {\n skip: false,\n pathsToInclude: includeForward,\n pathsToExclude: excludeForward,\n };\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { arrayToPath } from 'pathtrace';\n\n/**\n * Stringify path array to string.\n *\n * @param input\n */\nexport function stringifyPath(input: PropertyKey[]) : string {\n return arrayToPath(input);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ValidatorDescriptor } from './types';\nimport { isObject } from '../utils';\n\n/**\n * Duck-typed guard for {@link ValidatorDescriptor}. Used by `mount()` to\n * distinguish a descriptor from a bare `Validator` function and from a\n * nested `IContainer` (which is also an object but carries `run` /\n * `safeRun` methods — the descriptor has a `run` function but no\n * `safeRun`).\n *\n * Duck-typed (not `instanceof`) so descriptors built from a different\n * copy of the package — adapters bundling their own `validup` dependency,\n * pnpm workspaces with multiple installs — still round-trip cleanly.\n */\nexport function isValidatorDescriptor<C = unknown, Out = unknown>(\n input: unknown,\n): input is ValidatorDescriptor<C, Out> {\n if (!isObject(input)) {\n return false;\n }\n\n return (\n typeof input.run === 'function' &&\n typeof input.safeRun !== 'function'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ValidatorDescriptor } from './types';\n\n/**\n * Factory for a {@link ValidatorDescriptor}. Mirrors the\n * `defineIssueItem` / `defineIssueGroup` shape used elsewhere in the\n * library so authored validators get a stable, typed construction site.\n *\n * @example\n * const validateEmailUnique = defineValidator({\n * sideEffect: true,\n * run: async (ctx) => {\n * const taken = await api.isEmailTaken(ctx.value as string);\n * if (taken) throw new Error('Email is already taken');\n * return ctx.value;\n * },\n * });\n */\nexport function defineValidator<C = unknown, Out = unknown>(\n descriptor: ValidatorDescriptor<C, Out>,\n): ValidatorDescriptor<C, Out> {\n return descriptor;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Thrown by `Container.runSync` when a validator returns a Promise or a\n * nested container does not implement `runSync`. Marked separately from\n * generic `Error` so the per-mount catch can re-throw it instead of folding\n * it into the issue list (otherwise users would get \"Property X is invalid\"\n * instead of the structural diagnostic).\n *\n * Internal — not exported from the package barrel.\n */\nexport class RunSyncViolationError extends Error {\n override readonly name = 'RunSyncViolationError';\n}\n\n/**\n * Duck-typed check — robust against `instanceof` mismatches when a duplicate\n * copy of the package exists in the dependency tree, or when the throw\n * crosses a realm boundary. Mirrors the `isValidupError` pattern.\n */\nexport function isRunSyncViolation(e: unknown): e is RunSyncViolationError {\n if (e instanceof RunSyncViolationError) {\n return true;\n }\n return (\n typeof e === 'object' &&\n e !== null &&\n (e as { name?: unknown }).name === 'RunSyncViolationError'\n );\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Path } from 'pathtrace';\nimport {\n expandPath,\n getPathValue,\n pathToArray,\n setPathValue,\n} from 'pathtrace';\nimport type {\n IResultCache,\n ResultCacheOutcome,\n ResultCacheSnapshot,\n} from '../cache';\nimport { GroupKey } from '../constants';\nimport { ValidupError, isError, isValidupError } from '../error';\nimport {\n buildErrorMessageForAttribute,\n buildOneOfFailedGroup,\n isOptionalValue,\n resolveDefaults,\n resolvePathFilter,\n} from '../helpers';\nimport { hasOwnProperty, isObject } from '../utils';\nimport type { Validator, ValidatorDescriptor } from '../validator';\nimport { isValidatorDescriptor } from '../validator';\nimport { isContainer } from './check';\nimport type {\n ContainerInput,\n ContainerOptions,\n ContainerRunOptions,\n IContainer,\n Mount,\n MountOptions,\n Result,\n} from './types';\nimport type { Issue } from '../issue';\nimport { IssueCode, defineIssueGroup, defineIssueItem } from '../issue';\nimport { RunSyncViolationError, isRunSyncViolation } from './run-sync-violation';\n\n/**\n * Bundle of state the error path needs from the surrounding run loop.\n * Grouped to keep `collectExecutionFailure`'s signature readable and to make\n * additions (e.g. extra provenance fields for meta stamping) a one-line\n * change at every call site instead of a positional-arg shuffle.\n */\ntype ExecutionFailureContext<C> = {\n error: unknown,\n item: Mount<C>,\n /**\n * The input value handed to the failing mount — retained so we can\n * re-evaluate predicate-optional declarations at error time without\n * relying on a \"predicate already returned false in the run loop\"\n * invariant.\n */\n value: unknown,\n /** Expanded mount path. Prepended to nested `ValidupError` issues. */\n keyParts: PropertyKey[],\n /** Trailing path segment. Drives the wrapping `IssueGroup` shape. */\n pathRelative: PropertyKey | undefined,\n /** Accumulator the error path writes into. */\n issues: Issue[],\n /** Per-run abort signal. If aborted, the throw is re-raised verbatim. */\n signal: AbortSignal | undefined,\n};\n\nexport class Container<\n T extends Record<string, any> = Record<string, any>,\n C = unknown,\n> implements IContainer<T, C> {\n protected options : ContainerOptions<T>;\n\n protected items : Mount<C>[];\n\n // ----------------------------------------------\n\n constructor(options: ContainerOptions<T> = {}) {\n this.options = options;\n this.items = [];\n\n this.initialize();\n }\n\n // ----------------------------------------------\n\n mount(container: IContainer<any, any>) : void;\n\n mount(\n options: MountOptions,\n container: IContainer<any, any>\n ): void;\n\n mount(\n key: Path<T> | (string & {}),\n data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>\n ) : void;\n\n mount(\n key: Path<T> | (string & {}),\n options: MountOptions,\n data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>\n ) : void;\n\n mount(...args: any[]) : void {\n if (args.length < 1) {\n throw new SyntaxError('The mount method requires at least one argument');\n }\n if (args.length > 3) {\n throw new SyntaxError(`mount() accepts at most 3 arguments, got ${args.length}`);\n }\n\n let path : string | undefined;\n let pathSeen = false;\n\n let data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C> | undefined;\n let dataSeen = false;\n // Tracked separately so we don't re-detect on store — `isContainer` /\n // `isValidatorDescriptor` walk the value once each here, then the\n // result is consulted directly when we push onto `this.items`.\n let dataKind: 'container' | 'validator' | 'descriptor' | undefined;\n\n let options: MountOptions = {};\n let optionsSeen = false;\n\n for (const arg of args) {\n if (typeof arg === 'string') {\n if (pathSeen) {\n throw new SyntaxError('mount() received multiple string arguments — only one path is supported.');\n }\n pathSeen = true;\n path = arg;\n continue;\n }\n\n if (typeof arg === 'function') {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'validator';\n continue;\n }\n\n if (isContainer(arg)) {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'container';\n continue;\n }\n\n // Descriptor check goes BEFORE the generic `isObject` branch:\n // a `ValidatorDescriptor` is an object that happens to carry\n // a `run` function but lacks `safeRun`, distinguishing it from\n // both `MountOptions` (no `run`) and `IContainer` (has both\n // `run` and `safeRun`).\n if (isValidatorDescriptor(arg)) {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'descriptor';\n continue;\n }\n\n if (isObject(arg)) {\n if (optionsSeen) {\n throw new SyntaxError('mount() received multiple options objects.');\n }\n optionsSeen = true;\n options = arg;\n }\n }\n\n if (\n dataKind !== 'container' &&\n (typeof path === 'undefined' || path.length === 0)\n ) {\n throw new SyntaxError('Only a container can be mounted without a key.');\n }\n\n if (typeof data === 'undefined' || typeof dataKind === 'undefined') {\n throw new SyntaxError('No container/validator could be extracted from the fn arguments.');\n }\n\n if (dataKind === 'container') {\n this.items.push({\n options,\n data: data as IContainer<any, any>,\n path,\n type: 'container',\n });\n\n return;\n }\n\n if (dataKind === 'descriptor') {\n const descriptor = data as ValidatorDescriptor<C>;\n this.items.push({\n options,\n data: descriptor.run,\n path,\n type: 'validator',\n sideEffect: descriptor.sideEffect,\n });\n return;\n }\n\n this.items.push({\n options,\n data: data as Validator<C>,\n path,\n type: 'validator',\n });\n }\n\n // ----------------------------------------------\n\n /**\n * Run the container against `data`. Default execution mode — async,\n * sequential, throws `ValidupError` on validation failure.\n *\n * Variants for the other execution modes:\n * - `run(data, { parallel: true })` — async, sequential→concurrent. Each\n * mount captures `value` from `data` before any sibling runs, so chained\n * sanitize-then-validate patterns are not supported.\n * - {@link Container.safeRun} — same as `run` but returns a discriminated\n * `Result<T>` instead of throwing on validation failure (still rethrows\n * on abort).\n * - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous\n * variants for graphs where every validator (and every nested container's\n * `runSync`) is synchronous.\n *\n * Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`\n * between mounts (which throws `signal.reason`), and any error raised by a\n * mid-flight validator during an aborted run is re-thrown as-is rather than\n * folded into the issue tree. Callers can therefore distinguish \"validation\n * failed\" from \"operation cancelled,\" but should not assume the thrown value\n * is always `signal.reason` — a validator that throws its own error before\n * the next abort check produces that error instead.\n *\n * @throws ValidupError on validation failure.\n * @throws signal.reason when the abort check fires between mounts.\n * @throws (mid-flight validator error) when a validator throws during an\n * already-aborted run — re-raised as-is rather than wrapped.\n */\n async run(\n data: ContainerInput<T> = {},\n options: ContainerRunOptions<T, C> = {},\n ): Promise<T> {\n if (options.parallel) {\n return this.runParallel(data, options);\n }\n\n const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);\n\n const output: Record<string, any> = {};\n const issues: Issue[] = [];\n\n let itemCount = 0;\n let errorCount = 0;\n\n for (let i = 0; i < this.items.length; i++) {\n // Pre-mount abort check — cheap and short-circuits cleanly without\n // entering the per-mount try/catch (so aborts don't get rewritten\n // into validation issues).\n options.signal?.throwIfAborted();\n\n const item = this.items[i];\n\n if (!this.isItemGroupIncluded(item, options.group)) {\n continue;\n }\n\n let pathCount = 0;\n let pathFailed = false;\n const branchStart = issues.length;\n\n const keys: string[] = item.path ? expandPath(data, item.path) : [''];\n\n for (const key of keys) {\n const keyParts = key ? pathToArray(key) : [];\n\n const pathRelative = keyParts.at(-1);\n const pathAbsolute = [\n ...(options.path ? options.path : []),\n ...keyParts,\n ];\n\n let value: unknown;\n if (key.length > 0) {\n value = hasOwnProperty(output, key) ?\n output[key] :\n getPathValue(data, key);\n } else {\n value = data;\n }\n\n const filter = resolvePathFilter(\n pathsToInclude,\n pathsToExclude,\n key,\n item.type === 'container',\n );\n if (filter.skip) {\n continue;\n }\n\n try {\n const resolvedOptionalValue = item.options.optionalValue ??\n options.optionalValue ??\n this.options.optionalValue;\n const isOptional = typeof item.options.optional === 'function' ?\n item.options.optional(value) :\n item.options.optional &&\n isOptionalValue(value, resolvedOptionalValue);\n\n if (isOptional) {\n if (hasOwnProperty(item.options, 'optionalAs')) {\n output[key] = item.options.optionalAs;\n } else if (hasOwnProperty(options, 'optionalAs')) {\n output[key] = options.optionalAs;\n } else if (hasOwnProperty(this.options, 'optionalAs')) {\n output[key] = this.options.optionalAs;\n } else if (item.options.optionalInclude) {\n output[key] = value;\n }\n } else if (item.type === 'container') {\n const tmp = await item.data.run(\n isObject(value) ? value : {},\n {\n group: options.group,\n flat: true,\n path: pathAbsolute,\n pathsToInclude: filter.pathsToInclude,\n pathsToExclude: filter.pathsToExclude,\n defaults: resolveDefaults(options.defaults, key),\n context: options.context,\n signal: options.signal,\n cache: options.cache,\n optionalValue: options.optionalValue,\n ...(hasOwnProperty(options, 'optionalAs') ?\n { optionalAs: options.optionalAs } : {}),\n },\n );\n\n const tmpKeys = Object.keys(tmp);\n for (const tmpKey of tmpKeys) {\n output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];\n }\n } else if (item.type === 'validator') {\n const snapshot: ResultCacheSnapshot = {\n value,\n context: options.context,\n group: options.group,\n };\n const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);\n if (cached) {\n if (cached.ok) {\n output[key] = cached.value;\n } else {\n // Replay the prior error through the same outer-catch\n // path so issue construction (path prefixing, optional\n // stamping) runs with the *current* `keyParts` — vital\n // when the same container is mounted under different\n // parents across runs.\n throw cached.error;\n }\n } else {\n try {\n const result = await item.data({\n key,\n path: pathAbsolute,\n\n value,\n data,\n group: options.group,\n context: options.context as C,\n signal: options.signal,\n cache: options.cache,\n });\n output[key] = result;\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: true, value: result },\n options.cache,\n options.signal,\n );\n } catch (e) {\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: false, error: e },\n options.cache,\n options.signal,\n );\n throw e;\n }\n }\n }\n } catch (e) {\n this.collectExecutionFailure({\n error: e,\n item,\n value,\n keyParts,\n pathRelative,\n issues,\n signal: options.signal,\n });\n pathFailed = true;\n }\n\n pathCount++;\n }\n\n if (pathCount > 0) {\n itemCount++;\n\n if (pathFailed) {\n errorCount++;\n this.wrapBranchForOneOf(issues, branchStart, item, i);\n }\n }\n }\n\n return this.finalizeOutput(output, options, issues, errorCount, itemCount);\n }\n\n /**\n * Parallel-execution variant of `run()`. All mounts kick off their\n * promises eagerly and the results are merged after `Promise.allSettled`.\n * See `ContainerRunOptions.parallel` for the trade-off note.\n */\n private async runParallel(\n data: ContainerInput<T>,\n options: ContainerRunOptions<T, C>,\n ): Promise<T> {\n const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);\n\n const output: Record<string, any> = {};\n const issues: Issue[] = [];\n\n type KeyTask = {\n key: string,\n keyParts: PropertyKey[],\n pathRelative: PropertyKey | undefined,\n // Retained for `collectExecutionFailure` so it can re-evaluate\n // predicate-optional mounts at error time.\n value: unknown,\n promise: Promise<unknown>,\n kind: 'container' | 'validator',\n };\n\n type ItemGroup = {\n item: Mount<C>,\n // Original registration index in `this.items`. Tracked separately\n // from the position in `itemGroups` because group-filtered mounts\n // are dropped from `itemGroups` — without this, `data.branch`\n // emitted by `wrapBranchForOneOf` would not match the\n // registration order seen by the consumer.\n mountIndex: number,\n tasks: KeyTask[],\n // optional/skip paths that completed inline still count toward\n // the per-item pathCount used for oneOf / errorCount tracking.\n syncPathCount: number,\n };\n\n const itemGroups: ItemGroup[] = [];\n\n for (let i = 0; i < this.items.length; i++) {\n options.signal?.throwIfAborted();\n\n const item = this.items[i];\n if (!this.isItemGroupIncluded(item, options.group)) {\n continue;\n }\n\n const tasks: KeyTask[] = [];\n let syncPathCount = 0;\n\n const keys: string[] = item.path ? expandPath(data, item.path) : [''];\n for (const key of keys) {\n const keyParts = key ? pathToArray(key) : [];\n const pathRelative = keyParts.at(-1);\n const pathAbsolute = [\n ...(options.path ? options.path : []),\n ...keyParts,\n ];\n\n let value: unknown;\n if (key.length > 0) {\n // Parallel mode reads `data` only — `output[key]` from a\n // sibling mount is intentionally NOT consulted (the\n // sibling may not have completed yet).\n value = getPathValue(data, key);\n } else {\n value = data;\n }\n\n const filter = resolvePathFilter(\n pathsToInclude,\n pathsToExclude,\n key,\n item.type === 'container',\n );\n if (filter.skip) {\n continue;\n }\n\n const resolvedOptionalValue = item.options.optionalValue ??\n options.optionalValue ??\n this.options.optionalValue;\n const isOptional = typeof item.options.optional === 'function' ?\n item.options.optional(value) :\n item.options.optional &&\n isOptionalValue(value, resolvedOptionalValue);\n\n if (isOptional) {\n if (hasOwnProperty(item.options, 'optionalAs')) {\n output[key] = item.options.optionalAs;\n } else if (hasOwnProperty(options, 'optionalAs')) {\n output[key] = options.optionalAs;\n } else if (hasOwnProperty(this.options, 'optionalAs')) {\n output[key] = this.options.optionalAs;\n } else if (item.options.optionalInclude) {\n output[key] = value;\n }\n syncPathCount++;\n continue;\n }\n\n let promise: Promise<unknown>;\n if (item.type === 'container') {\n promise = item.data.run(\n isObject(value) ? value : {},\n {\n group: options.group,\n flat: true,\n path: pathAbsolute,\n pathsToInclude: filter.pathsToInclude,\n pathsToExclude: filter.pathsToExclude,\n defaults: resolveDefaults(options.defaults, key),\n context: options.context,\n signal: options.signal,\n parallel: true,\n cache: options.cache,\n optionalValue: options.optionalValue,\n ...(hasOwnProperty(options, 'optionalAs') ?\n { optionalAs: options.optionalAs } : {}),\n },\n );\n } else {\n const snapshot: ResultCacheSnapshot = {\n value,\n context: options.context,\n group: options.group,\n };\n const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);\n if (cached) {\n // Materialize cached outcomes as already-settled promises\n // so the existing `Promise.allSettled` merge loop handles\n // them identically to fresh runs — no parallel-specific\n // replay code path.\n promise = cached.ok ?\n Promise.resolve(cached.value) :\n Promise.reject(cached.error);\n } else {\n // Wrap sync validators in a microtask so the surrounding\n // `Promise.allSettled` always sees a thenable. Cache\n // writes happen inside the wrapper so the entry is\n // persisted before the promise settles.\n const itemData = item.data;\n const captureItem = item;\n const captureKey = key;\n const captureSnapshot = snapshot;\n promise = (async () => {\n try {\n const result = await itemData({\n key,\n path: pathAbsolute,\n value,\n data,\n group: options.group,\n context: options.context as C,\n signal: options.signal,\n cache: options.cache,\n });\n this.writeCachedOutcome(\n captureItem,\n captureKey,\n captureSnapshot,\n { ok: true, value: result },\n options.cache,\n options.signal,\n );\n return result;\n } catch (e) {\n this.writeCachedOutcome(\n captureItem,\n captureKey,\n captureSnapshot,\n { ok: false, error: e },\n options.cache,\n options.signal,\n );\n throw e;\n }\n })();\n }\n }\n\n tasks.push({\n key,\n keyParts,\n pathRelative,\n value,\n promise,\n kind: item.type,\n });\n }\n\n if (tasks.length > 0 || syncPathCount > 0) {\n itemGroups.push({\n item,\n mountIndex: i,\n tasks,\n syncPathCount,\n });\n }\n }\n\n // Wait for all groups concurrently. Promises were already kicked off\n // eagerly above; this just collects their settled state.\n const settledByGroup = await Promise.all(itemGroups.map(\n (group) => Promise.allSettled(group.tasks.map((t) => t.promise)),\n ));\n\n // Re-check the abort signal after settling. Sequential `run`/`runSync`\n // probe between every mount; the parallel variant can only check here\n // and before `finalizeOutput`. Without this, validators that ignore\n // `ctx.signal` would let an aborted run resolve to a successful result.\n options.signal?.throwIfAborted();\n\n let itemCount = 0;\n let errorCount = 0;\n\n for (const [i, {\n item,\n mountIndex,\n tasks,\n syncPathCount,\n }] of itemGroups.entries()) {\n const settled = settledByGroup[i];\n\n let pathFailed = false;\n const branchStart = issues.length;\n for (const [j, task] of tasks.entries()) {\n const result = settled[j];\n\n if (result.status === 'fulfilled') {\n if (task.kind === 'container') {\n const tmp = result.value as Record<string, any>;\n const tmpKeys = Object.keys(tmp);\n for (const tmpKey of tmpKeys) {\n output[this.mergePaths(task.key, tmpKey)] = tmp[tmpKey];\n }\n } else {\n output[task.key] = result.value;\n }\n } else {\n this.collectExecutionFailure({\n error: result.reason,\n item,\n value: task.value,\n keyParts: task.keyParts,\n pathRelative: task.pathRelative,\n issues,\n signal: options.signal,\n });\n pathFailed = true;\n }\n }\n\n if (tasks.length + syncPathCount > 0) {\n itemCount++;\n if (pathFailed) {\n errorCount++;\n // Use the original registration index so `data.branch`\n // matches the registration order regardless of group\n // filtering — sequential `run()` / `runSync()` already\n // pass the registration index directly.\n this.wrapBranchForOneOf(issues, branchStart, item, mountIndex);\n }\n }\n }\n\n // Final guard before returning a (potentially successful) value — if\n // the run was aborted after the post-settle check but before the merge\n // loop finished, propagate the abort instead of returning stale data.\n options.signal?.throwIfAborted();\n\n return this.finalizeOutput(output, options, issues, errorCount, itemCount);\n }\n\n async safeRun(input: ContainerInput<T> = {}, options: ContainerRunOptions<T, C> = {}): Promise<Result<T>> {\n try {\n const data = await this.run(input, options);\n return { success: true, data };\n } catch (e) {\n return this.wrapSafeRunError(e, options);\n }\n }\n\n /**\n * Synchronous variant of {@link Container.run}. Use it for purely\n * synchronous validator graphs where the microtask overhead of `await`\n * per mount matters (e.g. driving a reactive UI without a `pending`\n * flicker on every keystroke).\n *\n * Each mounted validator's return value MUST NOT be a thenable, and every\n * nested container MUST implement `runSync`. Either violation throws\n * `RunSyncViolationError` (structural — distinct from validation\n * failures), so the diagnostic is surfaced verbatim rather than wrapped\n * into a `ValidupError`. The companion {@link Container.safeRunSync}\n * still rethrows these for the same reason.\n *\n * No `parallel` variant — synchronous graphs don't benefit from\n * concurrency, and `Promise.allSettled` is async by definition.\n *\n * Aborts surface the same way as {@link Container.run}: the\n * `signal.throwIfAborted()` check between mounts throws `signal.reason`,\n * and a mid-flight validator throw during an already-aborted run is\n * re-raised verbatim. Don't assume the thrown value is always\n * `signal.reason`.\n *\n * @throws ValidupError on validation failure.\n * @throws RunSyncViolationError when a validator returns a Promise or a\n * nested container does not implement `runSync`.\n * @throws signal.reason when the abort check fires between mounts.\n * @throws (mid-flight validator error) when a validator throws during an\n * already-aborted run.\n */\n runSync(\n data: ContainerInput<T> = {},\n options: ContainerRunOptions<T, C> = {},\n ): T {\n const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);\n\n const output: Record<string, any> = {};\n const issues: Issue[] = [];\n\n let itemCount = 0;\n let errorCount = 0;\n\n for (let i = 0; i < this.items.length; i++) {\n options.signal?.throwIfAborted();\n\n const item = this.items[i];\n\n if (!this.isItemGroupIncluded(item, options.group)) {\n continue;\n }\n\n let pathCount = 0;\n let pathFailed = false;\n const branchStart = issues.length;\n\n const keys: string[] = item.path ? expandPath(data, item.path) : [''];\n\n for (const key of keys) {\n const keyParts = key ? pathToArray(key) : [];\n\n const pathRelative = keyParts.at(-1);\n const pathAbsolute = [\n ...(options.path ? options.path : []),\n ...keyParts,\n ];\n\n let value: unknown;\n if (key.length > 0) {\n value = hasOwnProperty(output, key) ?\n output[key] :\n getPathValue(data, key);\n } else {\n value = data;\n }\n\n const filter = resolvePathFilter(\n pathsToInclude,\n pathsToExclude,\n key,\n item.type === 'container',\n );\n if (filter.skip) {\n continue;\n }\n\n try {\n const resolvedOptionalValue = item.options.optionalValue ??\n options.optionalValue ??\n this.options.optionalValue;\n const isOptional = typeof item.options.optional === 'function' ?\n item.options.optional(value) :\n item.options.optional &&\n isOptionalValue(value, resolvedOptionalValue);\n\n if (isOptional) {\n if (hasOwnProperty(item.options, 'optionalAs')) {\n output[key] = item.options.optionalAs;\n } else if (hasOwnProperty(options, 'optionalAs')) {\n output[key] = options.optionalAs;\n } else if (hasOwnProperty(this.options, 'optionalAs')) {\n output[key] = this.options.optionalAs;\n } else if (item.options.optionalInclude) {\n output[key] = value;\n }\n } else if (item.type === 'container') {\n const childRunSync = (\n item.data as IContainer<any, any> & {\n runSync?: (...args: any[]) => any\n }\n ).runSync;\n if (typeof childRunSync !== 'function') {\n throw new RunSyncViolationError(`runSync: nested container at \"${key || '<root>'}\" does not implement runSync`);\n }\n\n const tmp = childRunSync.call(item.data, isObject(value) ? value : {}, {\n group: options.group,\n flat: true,\n path: pathAbsolute,\n pathsToInclude: filter.pathsToInclude,\n pathsToExclude: filter.pathsToExclude,\n defaults: resolveDefaults(options.defaults, key),\n context: options.context,\n signal: options.signal,\n cache: options.cache,\n optionalValue: options.optionalValue,\n ...(hasOwnProperty(options, 'optionalAs') ?\n { optionalAs: options.optionalAs } : {}),\n });\n\n const tmpKeys = Object.keys(tmp);\n for (const tmpKey of tmpKeys) {\n output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];\n }\n } else if (item.type === 'validator') {\n const snapshot: ResultCacheSnapshot = {\n value,\n context: options.context,\n group: options.group,\n };\n const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);\n if (cached) {\n if (cached.ok) {\n output[key] = cached.value;\n } else {\n throw cached.error;\n }\n } else {\n try {\n const result = item.data({\n key,\n path: pathAbsolute,\n\n value,\n data,\n group: options.group,\n context: options.context as C,\n signal: options.signal,\n cache: options.cache,\n });\n if (\n result !== null &&\n typeof result === 'object' &&\n typeof (result as { then?: unknown }).then === 'function'\n ) {\n // Don't cache: structural violation, not a\n // validation outcome.\n throw new RunSyncViolationError(`runSync: validator at \"${key || '<root>'}\" returned a Promise`);\n }\n output[key] = result;\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: true, value: result },\n options.cache,\n options.signal,\n );\n } catch (e) {\n // RunSyncViolation is structural — don't pollute\n // the cache with a graph-level error that the\n // next run might reach through different mounts.\n if (!isRunSyncViolation(e)) {\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: false, error: e },\n options.cache,\n options.signal,\n );\n }\n throw e;\n }\n }\n }\n } catch (e) {\n this.collectExecutionFailure({\n error: e,\n item,\n value,\n keyParts,\n pathRelative,\n issues,\n signal: options.signal,\n });\n pathFailed = true;\n }\n\n pathCount++;\n }\n\n if (pathCount > 0) {\n itemCount++;\n\n if (pathFailed) {\n errorCount++;\n this.wrapBranchForOneOf(issues, branchStart, item, i);\n }\n }\n }\n\n return this.finalizeOutput(output, options, issues, errorCount, itemCount);\n }\n\n safeRunSync(input: ContainerInput<T> = {}, options: ContainerRunOptions<T, C> = {}): Result<T> {\n try {\n const data = this.runSync(input, options);\n return { success: true, data };\n } catch (e) {\n return this.wrapSafeRunError(e, options);\n }\n }\n\n /**\n * Lookup helper for the per-mount result cache.\n *\n * Returns `undefined` (forcing a real run) for any of:\n * - No `cache` supplied — caller didn't opt in.\n * - Mount isn't a validator — container mounts run their own\n * inner loop, which consults the cache for their own mounts.\n * - Validator declared `sideEffect: true` — its result depends on\n * inputs the snapshot doesn't capture (sibling fields, network,\n * global state), so caching would be unsound.\n * - No prior entry stored for this `(mount, key)` pair.\n * - Stored snapshot's `value` / `context` / `group` don't all match\n * the current invocation by `Object.is`.\n */\n private resolveCachedOutcome(\n item: Mount<C>,\n key: string,\n snapshot: ResultCacheSnapshot,\n cache: IResultCache | undefined,\n ): ResultCacheOutcome | undefined {\n if (\n !cache ||\n item.type !== 'validator' ||\n item.sideEffect === true\n ) {\n return undefined;\n }\n const entry = cache.get(item, key);\n if (!entry) {\n return undefined;\n }\n if (\n Object.is(entry.snapshot.value, snapshot.value) &&\n Object.is(entry.snapshot.context, snapshot.context) &&\n Object.is(entry.snapshot.group, snapshot.group)\n ) {\n return entry.outcome;\n }\n return undefined;\n }\n\n /**\n * Store the outcome of a fresh validator invocation. No-ops in the\n * same cases `resolveCachedOutcome` returns `undefined` for, plus:\n *\n * - `signal.aborted` — the throw was caused by cancellation, not by\n * a validation outcome we want to remember. Caching the abort\n * would mean future replays surface \"AbortError\" as a fake\n * validation issue every time the same snapshot is seen, even\n * in fully-completed runs.\n *\n * `RunSyncViolationError`s are filtered out at the call site\n * (`runSync` only) because they're structural — the validator\n * graph is wrong, not the input.\n */\n private writeCachedOutcome(\n item: Mount<C>,\n key: string,\n snapshot: ResultCacheSnapshot,\n outcome: ResultCacheOutcome,\n cache: IResultCache | undefined,\n signal: AbortSignal | undefined,\n ): void {\n if (\n !cache ||\n item.type !== 'validator' ||\n item.sideEffect === true ||\n signal?.aborted\n ) {\n return;\n }\n cache.set(item, key, { snapshot, outcome });\n }\n\n private resolveContainerFilters(options: ContainerRunOptions<T, C>): {\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n } {\n let pathsToInclude: string[] | undefined;\n if (options.pathsToInclude) {\n pathsToInclude = options.pathsToInclude as string[];\n } else if (this.options.pathsToInclude) {\n pathsToInclude = this.options.pathsToInclude as string[];\n }\n\n let pathsToExclude: string[] | undefined;\n if (options.pathsToExclude) {\n pathsToExclude = options.pathsToExclude as string[];\n } else if (this.options.pathsToExclude) {\n pathsToExclude = this.options.pathsToExclude as string[];\n }\n\n return { pathsToInclude, pathsToExclude };\n }\n\n /**\n * Prepend `keyParts` to a child issue's `path` and — when the child is\n * an `IssueGroup` — recurse into its nested issues so every leaf carries\n * the parent prefix. Without recursion, a child container that already\n * wrapped its own multi-issue mount in a group (or a `oneOf` child) would\n * surface inner items with paths missing the parent segment, breaking\n * downstream consumers that rely on `flattenIssueItems` for per-field\n * lookup (e.g. `@validup/vue`).\n */\n private prefixIssuePath(issue: Issue, keyParts: PropertyKey[]): Issue {\n const prefixed: Issue = {\n ...issue,\n path: [...keyParts, ...(issue.path || [])],\n };\n if (prefixed.type === 'group') {\n prefixed.issues = prefixed.issues.map(\n (nested) => this.prefixIssuePath(nested, keyParts),\n );\n }\n return prefixed;\n }\n\n /**\n * Translate a throw raised by one execution step (one validator or\n * nested-container invocation, from the surrounding `run` loop) into\n * accumulated issues and push them onto `context.issues`. Re-throws when\n * the run was aborted (signal-aware validators) so abort errors are not\n * mangled into validation issues.\n *\n * \"Mount\" is the *setup-time* verb (`container.mount(...)`); what failed\n * here is the *execution* of an already-mounted unit — hence the name.\n *\n * The context object captures everything the error path needs to know\n * about the failing step: the thrown value (`error`), the mount\n * descriptor (`item`), the current input (`value` — kept around so we\n * can re-evaluate predicate-optional declarations at error time), the\n * expanded path (`keyParts` — used to prepend to nested `ValidupError`\n * issues) and the trailing segment (`pathRelative` — used when wrapping\n * multi-issue or container emissions into an `IssueGroup`). The\n * destination accumulator (`issues`) and the abort `signal` round out\n * what's needed to handle the failure.\n *\n * @modifies context.issues — appends one or more entries per call.\n */\n private collectExecutionFailure(context: ExecutionFailureContext<C>): void {\n const {\n error,\n item,\n value,\n keyParts,\n pathRelative,\n issues,\n signal,\n } = context;\n\n if (signal?.aborted) {\n throw error;\n }\n // Structural runSync violations are not validation outcomes — they\n // mean the caller can't use runSync against this graph. Surface the\n // diagnostic verbatim instead of wrapping it as \"Property X is invalid\".\n if (isRunSyncViolation(error)) {\n throw error;\n }\n\n // Mounts whose `optional` declaration resolves truthy for the current\n // `value` stamp their own emissions with `meta.optional: true`, so\n // consumers (e.g. `@validup/vue`'s severity helper) can downgrade UX\n // gating for fields the schema permits to be blank.\n //\n // Resolution mirrors the run-loop check (e.g. lines 254-256):\n //\n // - `optional: true` → tag\n // - `optional: false` → don't tag (matches runtime's truthy filter)\n // - `optional: (v) => boolean` → invoke the predicate with the\n // current value and tag iff it returns truthy. Today the run\n // loop only enters this error path when the predicate returned\n // false (otherwise the validator would have been skipped), so\n // this branch is effectively \"don't tag\" — but the explicit\n // re-evaluation keeps the code's intent self-evident and\n // decouples it from that invariant.\n // - `optional: undefined` → don't tag\n //\n // Per the \"no inheritance\" decision: issues bubbled up unchanged from\n // a child Container's own `ValidupError` are NOT stamped here — the\n // child's own per-mount tagging is authoritative, and a leaf inside a\n // required-on-its-own-mount field stays unmarked even if its parent\n // mount was optional. This matches the \"if you DO provide a role, the\n // role's required fields are still required\" semantics.\n const isOptionalMount = typeof item.options.optional === 'function' ?\n Boolean(item.options.optional(value)) :\n item.options.optional === true\n ;\n // Shallow stamp — only the top-level `issue.meta`. Used for the\n // wrapping `IssueGroup` we emit for container mounts (Option B: do\n // not propagate the parent's optional flag onto the bubbled-up child\n // leaves, which retain their own per-mount tagging) and for leaves\n // we construct directly via `defineIssueItem`.\n //\n // We reassign `issue.meta` to a FRESH object rather than mutating\n // the existing one. The top-level `issue` is always safe to mutate\n // here (it's a fresh object from `prefixIssuePath`'s shallow spread\n // or one of the `defineIssue*` factories), but the inner `meta`\n // object can be shared with the validator's original\n // `ValidupError.issues[i].meta` — mutating in place would leak\n // `optional: true` back into the validator's own (possibly cached\n // or replayed) error.\n const markOptional = <I extends Issue>(issue: I): I => {\n if (!isOptionalMount) {\n return issue;\n }\n issue.meta = { ...(issue.meta ?? {}), optional: true };\n return issue;\n };\n\n // Deep stamp — recurse into `IssueGroup.issues`. Used ONLY when the\n // whole tree was produced by *this* validator (e.g. an integration\n // adapter that threw `ValidupError([defineIssueGroup({ issues: [...] })])`).\n // Without this, `flattenIssueItems` would pull out the inner leaves\n // and miss `meta.optional` on them. Not used for container mounts —\n // see Option B above.\n const markOptionalDeep = <I extends Issue>(issue: I): I => {\n if (!isOptionalMount) {\n return issue;\n }\n markOptional(issue);\n if (issue.type === 'group') {\n issue.issues = issue.issues.map((nested) => markOptionalDeep(nested));\n }\n return issue;\n };\n\n const childIssues: Issue[] = [];\n\n if (isValidupError(error)) {\n for (let i = 0; i < error.issues.length; i++) {\n const prefixed = this.prefixIssuePath(error.issues[i], keyParts);\n // Stamp only when a *validator* threw `ValidupError` directly\n // (e.g. an integration adapter like `@validup/zod` reshaping\n // a foreign error into validup issues). Deep so that a\n // validator returning a nested `IssueGroup` tags leaves too.\n // For child Container runs, leave the bubbled tree alone —\n // see comment above.\n childIssues.push(item.type === 'validator' ? markOptionalDeep(prefixed) : prefixed);\n }\n } else if (isError(error)) {\n childIssues.push(markOptional(defineIssueItem({\n path: keyParts,\n message: error.message,\n })));\n } else {\n // Non-`Error` throw (string, plain object, null, …). Without a\n // synthetic issue here, the run would still flag the mount as\n // failed but the resulting `ValidupError.issues` would not\n // mention the throw at all — caller sees \"validation failed\"\n // with no diagnostic. Surface the stringified value so the\n // failure is at least traceable.\n childIssues.push(markOptional(defineIssueItem({\n path: keyParts,\n message: typeof error === 'string' && error.length > 0 ? error : `Non-Error throw: ${String(error)}`,\n })));\n }\n\n if (pathRelative) {\n if (item.type === 'container' || childIssues.length > 1) {\n // The wrapping group is itself an emission of *this* mount —\n // stamp it (shallow) so a tree-walking consumer can read the\n // optional signal at the group level. The leaves inside\n // follow the \"no inheritance\" rule and stay untouched for\n // container mounts; for multi-leaf validator mounts, the\n // leaves were already stamped above.\n issues.push(markOptional(defineIssueGroup({\n message: buildErrorMessageForAttribute(String(pathRelative)),\n data: { name: String(pathRelative) },\n path: keyParts,\n issues: childIssues,\n })));\n } else {\n issues.push(...childIssues);\n }\n } else {\n issues.push(...childIssues);\n }\n }\n\n /**\n * For `oneOf` containers, wrap the issues produced by a single branch\n * (slice from `branchStart` to the end of `issues`) into one sub-group\n * so per-branch identity is preserved in the final aggregate. Non-oneOf\n * containers leave the issue list untouched — they don't need branch\n * partitioning.\n *\n * The wrapping group's `path` is `[]` (the branch wraps everything\n * inside it; per-leaf paths are unchanged); `data.branch` is the\n * mount index; and `data.name` (when set) is the mount path so\n * consumers can label \"branch X failed\" without recomputing the\n * registration order.\n */\n private wrapBranchForOneOf(\n issues: Issue[],\n branchStart: number,\n item: Mount<C>,\n branchIndex: number,\n ): void {\n if (!this.options.oneOf) {\n return;\n }\n const branchIssues = issues.splice(branchStart);\n const data: Record<string, unknown> = { branch: branchIndex };\n if (item.path) {\n data.name = item.path;\n }\n issues.push(defineIssueGroup({\n message: item.path ?\n `Branch \"${item.path}\" failed` :\n `Branch ${branchIndex} failed`,\n data,\n path: [],\n issues: branchIssues,\n }));\n }\n\n /**\n * Apply post-loop semantics: oneOf aggregation, error throw, defaults\n * fill, and flat-vs-nested output expansion.\n */\n private finalizeOutput(\n output: Record<string, any>,\n options: ContainerRunOptions<T, C>,\n issues: Issue[],\n errorCount: number,\n itemCount: number,\n ): T {\n if (this.options.oneOf) {\n // Guard against the \"all branches filtered out\" case (group /\n // pathsToInclude / pathsToExclude can leave itemCount === 0).\n // Without it, a oneOf container with nothing to run would throw\n // ONE_OF_FAILED with an empty issues list. Shared\n // `buildOneOfFailedGroup` keeps the ONE_OF_FAILED shape in\n // lockstep with compose's any-of path so consumers / i18n\n // catalogs only format one variant.\n if (itemCount > 0 && errorCount === itemCount) {\n throw new ValidupError([buildOneOfFailedGroup(issues, { path: options.path ? options.path : [] })]);\n }\n } else if (errorCount > 0) {\n throw new ValidupError(issues);\n }\n\n if (options.defaults) {\n const defaultKeys = Object.keys(options.defaults);\n for (const defaultKey of defaultKeys) {\n if (\n !hasOwnProperty(output, defaultKey) ||\n typeof output[defaultKey] === 'undefined'\n ) {\n output[defaultKey] = (options.defaults as Record<string, any>)[defaultKey];\n }\n }\n }\n\n if (options.flat) {\n return output as T;\n }\n\n const temp: Record<string, any> = {};\n const keys = Object.keys(output);\n for (const key of keys) {\n setPathValue(temp, key, output[key]);\n }\n return temp as T;\n }\n\n private wrapSafeRunError(e: unknown, options: ContainerRunOptions<T, C>): Result<T> {\n // Abort is not a validation outcome — propagate it. Wrapping it\n // as a synthetic `Result.failure` would produce a misleading\n // \"AbortError\" issue at path `[]`.\n if (options.signal?.aborted) {\n throw e;\n }\n // Same reasoning for `runSync` structural violations.\n if (isRunSyncViolation(e)) {\n throw e;\n }\n\n if (isValidupError(e)) {\n return { success: false, error: e };\n }\n\n if (isError(e)) {\n return {\n success: false,\n error: new ValidupError([\n defineIssueItem({\n path: [],\n message: e.message,\n }),\n ]),\n };\n }\n\n // Non-`Error` throw (string, plain object, null, …). Surface a\n // stringified diagnostic so `Result.error.issues` is never empty —\n // an empty issue list with `success: false` is a confusing API\n // signal (\"validation failed\" with no diagnostic) and is what\n // landed in 0.x for non-Error throws.\n return {\n success: false,\n error: new ValidupError([\n defineIssueItem({\n path: [],\n message: typeof e === 'string' && e.length > 0 ? e : `Non-Error throw: ${String(e)}`,\n }),\n ]),\n };\n }\n\n private isItemGroupIncluded(\n item: Mount<C>,\n group?: string,\n ) : boolean {\n if (group === GroupKey.WILDCARD) {\n return true;\n }\n\n if (item.options.group) {\n if (Array.isArray(item.options.group)) {\n if (item.options.group.includes(GroupKey.WILDCARD)) {\n return true;\n }\n\n if (group && item.options.group.includes(group)) {\n return true;\n }\n } else {\n if (item.options.group === GroupKey.WILDCARD) {\n return true;\n }\n\n if (item.options.group === group) {\n return true;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Join flat-output keys with `.` separators, preserving any pre-existing\n * leading dot on the right-hand side. Note: keys containing a *literal*\n * dot collide with the dotted-path syntax used for nested-output\n * expansion (see `setPathValue` in `pathtrace`) and will produce\n * ambiguous output when re-expanded — avoid mounting/returning such keys.\n */\n private mergePaths(...args: (string | undefined)[]) {\n let output : string = '';\n\n for (const arg of args) {\n if (!arg || arg.length === 0) {\n continue;\n }\n\n if (arg.at(0) === '.') {\n output += arg;\n } else {\n output += output.length > 0 ? `.${arg}` : arg;\n }\n }\n\n return output;\n }\n\n protected initialize() : void {\n\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { Container, isContainer } from '../container';\nimport type {\n ContainerOptions,\n IContainer,\n MountOptions,\n} from '../container/types';\nimport type { IBuilder, MountTarget } from './types';\nimport type { Validator } from '../validator';\n\ntype ValidatorStep<C> = {\n kind: 'validator',\n key: string,\n validator: Validator<C>,\n options: MountOptions,\n};\n\ntype NestStep<C> = {\n kind: 'nest',\n key: string,\n child: IContainer<any, C>,\n options: MountOptions,\n};\n\ntype Step<C> = ValidatorStep<C> | NestStep<C>;\n\nfunction isBuilder(value: unknown): value is IBuilder<Record<string, any>, unknown> {\n return typeof value === 'object' &&\n value !== null &&\n typeof (value as { build?: unknown }).build === 'function' &&\n typeof (value as { mount?: unknown }).mount === 'function';\n}\n\nexport class Builder<T extends Record<string, any>, C> implements IBuilder<T, C> {\n private readonly options: ContainerOptions<any>;\n\n private readonly steps: ReadonlyArray<Step<C>>;\n\n constructor(options: ContainerOptions<any>, steps: ReadonlyArray<Step<C>>) {\n this.options = options;\n this.steps = steps;\n }\n\n mount(key: string, ...rest: unknown[]): IBuilder<any, C> {\n let options: MountOptions = {};\n let target: MountTarget<C>;\n\n if (rest.length === 1) {\n target = rest[0] as MountTarget<C>;\n } else {\n options = rest[0] as MountOptions;\n target = rest[1] as MountTarget<C>;\n }\n\n let step: Step<C>;\n if (isBuilder(target)) {\n step = {\n kind: 'nest',\n key,\n child: (target as IBuilder<any, C>).build(),\n options,\n };\n } else if (isContainer(target)) {\n step = {\n kind: 'nest',\n key,\n child: target as IContainer<any, C>,\n options,\n };\n } else {\n step = {\n kind: 'validator',\n key,\n validator: target as Validator<C>,\n options,\n };\n }\n\n return new Builder<any, C>(this.options, [...this.steps, step]);\n }\n\n oneOf(): IBuilder<T, C> {\n return new Builder<T, C>(\n { ...this.options, oneOf: true },\n this.steps,\n );\n }\n\n pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C> {\n return new Builder<T, C>(\n {\n ...this.options,\n pathsToInclude: [\n ...((this.options.pathsToInclude as string[]) ?? []),\n ...paths,\n ] as ContainerOptions<any>['pathsToInclude'],\n },\n this.steps,\n );\n }\n\n pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C> {\n return new Builder<T, C>(\n {\n ...this.options,\n pathsToExclude: [\n ...((this.options.pathsToExclude as string[]) ?? []),\n ...paths,\n ] as ContainerOptions<any>['pathsToExclude'],\n },\n this.steps,\n );\n }\n\n build(): Container<T, C> {\n const container = new Container<T, C>(this.options as ContainerOptions<T>);\n for (const step of this.steps) {\n if (step.kind === 'nest') {\n container.mount(step.key, step.options, step.child);\n } else {\n container.mount(step.key, step.options, step.validator);\n }\n }\n return container;\n }\n}\n\n/**\n * Entry point for the compile-time-typed schema builder. The accumulator\n * starts at `{}` and grows as `.mount(...)` calls are chained;\n * `.build()` returns a `Container<T, C>` whose `run()` reflects the\n * accumulated shape.\n *\n * Pass the context type as the generic parameter to flow it through nested\n * builders and validator factories: `defineSchema<MyContext>()`.\n */\nexport function defineSchema<C = unknown>(): IBuilder<{}, C> {\n return new Builder<{}, C>({}, []);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IResultCache } from './types';\nimport { isObject } from '../utils';\n\n/**\n * Duck-typed guard for {@link IResultCache}. Avoids `instanceof`\n * checks so caches constructed from a different copy of the package\n * (workspaces with duplicated `validup` installs, adapter bundles)\n * still round-trip cleanly.\n */\nexport function isResultCache(input: unknown): input is IResultCache {\n if (!isObject(input)) {\n return false;\n }\n\n return (\n typeof input.get === 'function' &&\n typeof input.set === 'function' &&\n typeof input.delete === 'function' &&\n typeof input.clear === 'function'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IResultCache, ResultCacheEntry } from './types';\n\n/**\n * Default in-memory {@link IResultCache} implementation.\n *\n * Backed by a two-level `Map`:\n * - outer key — Mount reference (opaque object)\n * - inner key — expanded path (string)\n *\n * `Map` is used for both levels (rather than a `WeakMap` on the outer)\n * so `clear()` is supported. Cache entries become unreachable when the\n * owning composable / caller drops its reference to the\n * `ResultCache` instance; in the typical `@validup/vue` flow that\n * happens on `onScopeDispose`, which lines up with component unmount.\n *\n * Snapshot equality (the \"is this still valid?\" check) is the run\n * loop's job — see `container/module.ts`. This class is dumb storage.\n */\nexport class ResultCache implements IResultCache {\n private store: Map<object, Map<string, ResultCacheEntry>>;\n\n constructor() {\n this.store = new Map();\n }\n\n get(mount: object, key: string): ResultCacheEntry | undefined {\n return this.store.get(mount)?.get(key);\n }\n\n set(mount: object, key: string, entry: ResultCacheEntry): void {\n let inner = this.store.get(mount);\n if (!inner) {\n inner = new Map();\n this.store.set(mount, inner);\n }\n inner.set(key, entry);\n }\n\n delete(mount: object, key?: string): void {\n if (typeof key === 'undefined') {\n this.store.delete(mount);\n return;\n }\n const inner = this.store.get(mount);\n if (!inner) {\n return;\n }\n inner.delete(key);\n if (inner.size === 0) {\n this.store.delete(mount);\n }\n }\n\n clear(): void {\n this.store.clear();\n }\n}\n"],"mappings":";;;;AAOA,SAAgB,eAAoD,KAAQ,MAAwC;CAChH,OAAO,OAAO,UAAU,eAAe,KAAK,KAAK,IAAI;AACzD;;;ACFA,SAAgB,SAAS,OAA+C;CACpE,OAAO,CAAC,CAAC,SACL,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK;AAC5B;;;ACDA,SAAgB,YAAY,OAAsC;CAC9D,OAAO,SAAS,KAAK,KACjB,OAAO,MAAM,QAAQ,cACrB,OAAO,MAAM,YAAY;AACjC;;;ACHA,IAAa,eAAb,cAAkC,UAAU;CACxC;CAEA,YAAY,SAAkB,CAAC,GAAG;EAC9B,MAAM,QAAQ,OAAO,KAAK,UAAU,cAAc,MAAM,IAAI,CAAC;EAC7D,MAAM,EAAE,SAAS,+BAA+B,KAAK,EAAE,CAAC;EAExD,KAAK,SAAS;CAClB;CAEA,SAAyE;EACrE,OAAO;GACH,GAAG,MAAM,OAAO;GAChB,QAAQ,KAAK;EACjB;CACJ;AACJ;;;ACZA,SAAS,YAAY,OAAyC;CAC1D,IAAI,CAAC,MAAM,QAAQ,KAAK,GACpB,OAAO;CAGX,OAAO,MAAM,OAAO,OAAO,OAAO,OAAO,YACzC,OAAO,OAAO,YACd,OAAO,OAAO,QAAQ;AAC1B;AAEA,SAAS,YAAY,OAA6D;CAC9E,IAAI,CAAC,SAAS,KAAK,GACf,OAAO;CAGX,IAAI,OAAO,MAAM,YAAY,UACzB,OAAO;CAGX,IAAI,CAAC,YAAY,MAAM,IAAI,GACvB,OAAO;CAGX,OAAO,OAAO,MAAM,SAAS,eACzB,SAAS,MAAM,IAAI;AAC3B;AAEA,SAAgB,YAAY,OAAqC;CAC7D,IAAI,CAAC,YAAY,KAAK,GAClB,OAAO;CAGX,IAAI,MAAM,SAAS,QACf,OAAO;CAGX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,KAAK,MAAM,IAAI,KAAK;EAClC,IAAI,CAAC,OACD;EAEJ,MAAM,OAAO,GAAG;EAChB,IAAI,MAAM,SAAS,GACf,KAAK,MAAM,OAAO,KAAK;CAE/B;CAEA,QAAc;EACV,KAAK,MAAM,MAAM;CACrB;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["interpolate"],"sources":["../src/utils/has-own-property.ts","../src/utils/object.ts","../src/container/check.ts","../src/container/paths-strict-violation.ts","../src/container/run-sync-violation.ts","../src/container/structural-throw.ts","../src/error/base.ts","../src/issue/check.ts","../src/issue/constants.ts","../src/issue/define.ts","../src/issue/flatten.ts","../src/issue/format.ts","../src/error/check.ts","../src/helpers/error-to-issues.ts","../src/helpers/one-of-failed.ts","../src/helpers/compose.ts","../src/helpers/create-error.ts","../src/helpers/defaults.ts","../src/helpers/error.ts","../src/constants.ts","../src/helpers/optional-value.ts","../src/helpers/path-filter.ts","../src/helpers/path-stringify.ts","../src/validator/check.ts","../src/validator/define.ts","../src/container/module.ts","../src/builder/module.ts","../src/cache/check.ts","../src/cache/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown> {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function isObject(input: unknown) : input is Record<string, any> {\n return !!input &&\n typeof input === 'object' &&\n !Array.isArray(input);\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isObject } from '../utils';\nimport type { IContainer } from './types';\n\nexport function isContainer(input: unknown) : input is IContainer {\n return isObject(input) &&\n typeof input.run === 'function' &&\n typeof input.safeRun === 'function';\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport type PathsStrictViolationInput = {\n pathsToInclude?: string[],\n pathsToExclude?: string[],\n};\n\n/**\n * Thrown by a `Container` run (all variants) when `pathsStrict` is enabled and\n * one or more `pathsToInclude` / `pathsToExclude` entries matched **no mount** —\n * neither an exact key match nor a prefix descent into a container mount. It\n * signals a misconfigured validator graph (typically a mount key that was\n * renamed out from under a caller's static path list), NOT a validation failure\n * of the input.\n *\n * Like `RunSyncViolationError` it is structural, so the per-mount catch and\n * `safeRun` / `safeRunSync` re-throw it verbatim instead of folding it into the\n * issue list or a `Result.failure`. Unlike `RunSyncViolationError` it IS\n * exported from the package barrel — the whole point is that consumers catch it,\n * read `pathsToInclude` / `pathsToExclude`, and surface which paths went stale.\n *\n * The reported paths are **absolute** (prefixed with the owning container's\n * `path` when the violation happens inside a nested container), so a caller sees\n * `user.email` rather than the child-local `email`.\n */\nexport class PathsStrictViolationError extends Error {\n override readonly name = 'PathsStrictViolationError';\n\n /** Absolute `pathsToInclude` entries that matched no mount. */\n readonly pathsToInclude: string[];\n\n /** Absolute `pathsToExclude` entries that matched no mount. */\n readonly pathsToExclude: string[];\n\n constructor(input: PathsStrictViolationInput) {\n const pathsToInclude = input.pathsToInclude ?? [];\n const pathsToExclude = input.pathsToExclude ?? [];\n\n const parts: string[] = [];\n if (pathsToInclude.length > 0) {\n parts.push(`pathsToInclude has no mount for: ${pathsToInclude.join(', ')}`);\n }\n if (pathsToExclude.length > 0) {\n parts.push(`pathsToExclude has no mount for: ${pathsToExclude.join(', ')}`);\n }\n\n super(`pathsStrict: ${parts.join('; ')}`);\n\n this.pathsToInclude = pathsToInclude;\n this.pathsToExclude = pathsToExclude;\n }\n}\n\n/**\n * Duck-typed check — robust against `instanceof` mismatches when a duplicate\n * copy of the package exists in the dependency tree, or when the throw crosses\n * a realm boundary. Mirrors the `isValidupError` / `isRunSyncViolation` pattern.\n */\nexport function isPathsStrictViolation(e: unknown): e is PathsStrictViolationError {\n if (e instanceof PathsStrictViolationError) {\n return true;\n }\n return (\n typeof e === 'object' &&\n e !== null &&\n (e as { name?: unknown }).name === 'PathsStrictViolationError'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Thrown by `Container.runSync` when a validator returns a Promise or a\n * nested container does not implement `runSync`. Marked separately from\n * generic `Error` so the per-mount catch can re-throw it instead of folding\n * it into the issue list (otherwise users would get \"Property X is invalid\"\n * instead of the structural diagnostic).\n *\n * Internal — not exported from the package barrel.\n */\nexport class RunSyncViolationError extends Error {\n override readonly name = 'RunSyncViolationError';\n}\n\n/**\n * Duck-typed check — robust against `instanceof` mismatches when a duplicate\n * copy of the package exists in the dependency tree, or when the throw\n * crosses a realm boundary. Mirrors the `isValidupError` pattern.\n */\nexport function isRunSyncViolation(e: unknown): e is RunSyncViolationError {\n if (e instanceof RunSyncViolationError) {\n return true;\n }\n return (\n typeof e === 'object' &&\n e !== null &&\n (e as { name?: unknown }).name === 'RunSyncViolationError'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isPathsStrictViolation } from './paths-strict-violation';\nimport { isRunSyncViolation } from './run-sync-violation';\n\n/**\n * Should this thrown value escape the issue-folding path verbatim?\n *\n * Three unrelated reasons say yes, and every site in `Container` that folds a\n * throw into `Issue[]` has to ask all three. Collapsing them into one predicate\n * keeps the list in a single place — a fourth carve-out is one edit, not three.\n *\n * 1. **The run was cancelled.** `signal.aborted` is a *run-state* read, not a\n * property of `error`. During an aborted run the thrown value is re-raised\n * **as-is** — it is NOT necessarily `signal.reason`, because a mid-flight\n * validator may throw its own error before the next abort check fires. That\n * contract is public (see the `@throws` block on {@link Container.run}), so\n * this leg must stay a signal read and must never become an\n * `isAbortError(error)` test.\n * 2. **`RunSyncViolationError`.** Structural: the caller cannot use `runSync`\n * against this graph. Folding it in would surface \"Property X is invalid\"\n * instead of the diagnostic.\n * 3. **`PathsStrictViolationError`.** Structural: the validator graph is\n * misconfigured (a `pathsToInclude` / `pathsToExclude` entry matched no\n * mount), not the input. It reaches a parent's per-mount catch because the\n * child `run()` is awaited inside the `try`.\n *\n * Both error legs delegate to the duck-typed guards rather than `instanceof`,\n * so a throw crossing a realm boundary or originating from a duplicate copy of\n * the package is still recognised.\n *\n * **Name caveat.** \"Structural\" describes legs 2 and 3 exactly; leg 1 is run\n * state, so an aborted run makes this return `true` for *any* value —\n * including a plain validation `ValidupError` from a validator that finished\n * just before the abort landed. The name is kept for continuity with the\n * comments it replaces; read it as \"must not be folded into issues\", not as a\n * statement about the error's type.\n *\n * Deliberately **not** a type predicate: the abort leg is true for arbitrary\n * values, so `error is RunSyncViolationError | PathsStrictViolationError` would\n * be an unsound narrowing. Every current caller re-throws immediately, but a\n * future one might not.\n *\n * Internal — not exported from `container/index.ts`, and therefore not from the\n * package barrel. It composes `isRunSyncViolation`, which is deliberately\n * private; publishing the composite would leak that decision into the public,\n * semver-protected surface.\n */\nexport function isStructuralThrow(error: unknown, signal?: AbortSignal): boolean {\n return Boolean(signal?.aborted) ||\n isRunSyncViolation(error) ||\n isPathsStrictViolation(error);\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from '@ebec/core';\nimport { buildErrorMessageForAttributes, stringifyPath } from '../helpers';\nimport type { Issue } from '../issue';\n\nexport class ValidupError extends BaseError {\n readonly issues: Issue[];\n\n constructor(issues: Issue[] = []) {\n const paths = issues.map((issue) => stringifyPath(issue.path));\n super({ message: buildErrorMessageForAttributes(paths) });\n\n this.issues = issues;\n }\n\n override toJSON(): ReturnType<BaseError['toJSON']> & { issues: Issue[] } {\n return {\n ...super.toJSON(),\n issues: this.issues,\n };\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isObject } from '../utils';\nimport type {\n Issue, \n IssueBase, \n IssueGroup, \n IssueItem,\n} from './types';\n\nfunction isIssuePath(input: unknown) : input is PropertyKey[] {\n if (!Array.isArray(input)) {\n return false;\n }\n\n return input.every((el) => typeof el === 'string' ||\n typeof el === 'number' ||\n typeof el === 'symbol');\n}\n\nfunction isBaseIssue(input: unknown) : input is IssueBase & { [ke: string]: any } {\n if (!isObject(input)) {\n return false;\n }\n\n if (typeof input.message !== 'string') {\n return false;\n }\n\n if (!isIssuePath(input.path)) {\n return false;\n }\n\n return typeof input.meta === 'undefined' ||\n isObject(input.meta);\n}\n\nexport function isIssueItem(input: unknown) : input is IssueItem {\n if (!isBaseIssue(input)) {\n return false;\n }\n\n if (input.type !== 'item') {\n return false;\n }\n\n return typeof input.code === 'string';\n}\n\nexport function isIssueGroup(input: unknown) : input is IssueGroup {\n if (!isBaseIssue(input)) {\n return false;\n }\n\n if (input.type !== 'group') {\n return false;\n }\n\n return Array.isArray(input.issues) &&\n input.issues.every((issue) => isIssueItem(issue) || isIssueGroup(issue));\n}\n\nexport function isIssue(input: unknown) : input is Issue {\n return isIssueGroup(input) || isIssueItem(input);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Vocabulary of well-known issue codes. Adapter packages map foreign\n * validator codes onto these so consumer-side translation catalogs\n * (e.g. `@ilingo/validup`) can ship one localized message per code\n * instead of falling back to a generic \"invalid value\" fallback.\n *\n * Tracks the common ground between vuelidate, zod, joi, and yup. The\n * core lifts from vuelidate's catalog (snake_cased to match validup's\n * convention); modern format codes (`PATTERN`, `UUID`, `DATE`,\n * `JSON`, `BASE64`, `STRONG_PASSWORD`, …) cover ground vuelidate\n * predates. Every format code names the format positively (`UUID`,\n * `EMAIL`, `URL`, …) rather than the failure mode (`NOT_UUID`,\n * `INVALID_EMAIL`) so the registry reads consistently.\n *\n * Ad-hoc / project-specific codes still work — `IssueItem.code` is\n * widened to `IssueCode | (string & {})`, so `defineIssueItem({ code:\n * 'email_taken', ... })` is valid. If you want a typed const for your\n * own codes, define one alongside this one:\n *\n * ```ts\n * import { IssueCode } from 'validup';\n *\n * export const AppCode = {\n * ...IssueCode,\n * EMAIL_TAKEN: 'email_taken',\n * } as const;\n * ```\n *\n * Each entry's JSDoc documents the structured `data` adapters should\n * attach when constructing the issue — templates can rely on those\n * placeholders being present (`{{min}}`, `{{max}}`, `{{other}}`, etc.).\n */\nexport const IssueCode = {\n // ──────────────────────────── Generic / structural ────────────────────────────\n /** Generic fallback when no more-specific code applies. `data`: — */\n VALUE_INVALID: 'value_invalid',\n /** Every branch of a `oneOf` container failed. `data`: — */\n ONE_OF_FAILED: 'one_of_failed',\n\n // ──────────────────────────── Presence ────────────────────────────\n /** Value is missing, `undefined`, `null`, or empty per the validator's semantics. `data`: — */\n REQUIRED: 'required',\n\n // ──────────────────────────── Type assertions ────────────────────────────\n /** Value contains characters outside the alphabetical set. `data`: — */\n ALPHA: 'alpha',\n /** Value contains characters outside the alphanumeric set. `data`: — */\n ALPHA_NUM: 'alpha_num',\n /** Value is not a number. `data`: — */\n NUMERIC: 'numeric',\n /** Value is not an integer. `data`: — */\n INTEGER: 'integer',\n /** Value is not a decimal number. `data`: — */\n DECIMAL: 'decimal',\n\n // ──────────────────────────── Length (strings, arrays) ────────────────────────────\n /** Value is shorter than the configured minimum. `data`: `{ min: number }` */\n MIN_LENGTH: 'min_length',\n /** Value is longer than the configured maximum. `data`: `{ max: number }` */\n MAX_LENGTH: 'max_length',\n\n // ──────────────────────────── Numeric range ────────────────────────────\n /** Numeric value is below the configured minimum. `data`: `{ min: number }` */\n MIN_VALUE: 'min_value',\n /** Numeric value is above the configured maximum. `data`: `{ max: number }` */\n MAX_VALUE: 'max_value',\n /** Numeric value falls outside the configured `[min, max]` range. `data`: `{ min: number, max: number }` */\n BETWEEN: 'between',\n\n // ──────────────────────────── String format ────────────────────────────\n /** Value is not a valid email address. `data`: — */\n EMAIL: 'email',\n /** Value is not a valid URL. `data`: — */\n URL: 'url',\n /** Value is not a valid IP address. `data`: — */\n IP_ADDRESS: 'ip_address',\n /** Value is not a valid MAC address. `data`: — */\n MAC_ADDRESS: 'mac_address',\n /** Value is not a valid UUID. `data`: — */\n UUID: 'uuid',\n /** Value is not a valid date / cannot be parsed as a date. `data`: — */\n DATE: 'date',\n /**\n * Value does not match the expected regex pattern. `data`:\n * `{ pattern: string }` — source of the regex without flags so\n * catalogs can quote it in human-readable form.\n */\n PATTERN: 'pattern',\n /** Value is not valid JSON. `data`: — */\n JSON: 'json',\n /** Value is not valid base64. `data`: — */\n BASE64: 'base64',\n /**\n * Value does not meet the configured strong-password rules. `data`:\n * `{ minLength?: number, minLowercase?: number, minUppercase?: number,\n * minNumbers?: number, minSymbols?: number }` — only the keys the\n * adapter chose to surface; missing keys mean \"the default for that\n * setting wasn't configured.\"\n */\n STRONG_PASSWORD: 'strong_password',\n\n // ──────────────────────────── Comparison ────────────────────────────\n /**\n * Value must equal another named field's value (sibling-field assertion,\n * e.g. password-confirm). `data`: `{ other: string }` — the name of\n * the field being compared against.\n */\n SAME_AS: 'same_as',\n} as const;\n\nexport type IssueCode = typeof IssueCode[keyof typeof IssueCode];\n\n/**\n * Per-code `data` contract for the well-known vocabulary. Producers\n * (`defineIssueItem`, `createValidupError`, adapter `error.ts` modules)\n * thread this through their type signatures so TS rejects mismatched\n * payloads at compile time — e.g. `STRONG_PASSWORD` with `data:\n * { pointsPerUnique: 5 }` (a validator.js scoring weight, not a strength\n * requirement) fails to type-check. Codes absent from this map carry no\n * `data`; ad-hoc string codes fall back to the open\n * `Record<string, unknown>` shape on the raw `IssueItem` branch.\n *\n * Extensible via TypeScript declaration merging — third-party adapters\n * and apps that want typed data for their own codes can augment this\n * interface, and the producer-side gatekeep (`defineIssueItem`,\n * `createValidupError`) will type-check their payloads too:\n *\n * ```ts\n * // In a third-party package or app:\n * declare module 'validup' {\n * interface IssueDataByCode {\n * email_taken: { existingUserId: string };\n * }\n * }\n *\n * defineIssueItem({\n * code: 'email_taken',\n * path: ['email'],\n * message: 'Already in use',\n * data: { existingUserId: 'u_42' }, // typed and required\n * });\n * ```\n *\n * Keep entries here in lockstep with the JSDoc on the corresponding\n * `IssueCode` entry — the type-level enforcement and the documentation\n * are two views of the same contract.\n */\nexport interface IssueDataByCode {\n min_length: { min: number };\n max_length: { max: number };\n min_value: { min: number };\n max_value: { max: number };\n between: { min: number, max: number };\n pattern: { pattern: string };\n strong_password: {\n minLength?: number,\n minLowercase?: number,\n minUppercase?: number,\n minNumbers?: number,\n minSymbols?: number,\n };\n same_as: { other: string };\n}\n\n/**\n * `IssueCode` values that carry a documented `data` payload — keys of\n * {@link IssueDataByCode}. Producers using one of these codes must\n * supply the matching `data` shape.\n */\nexport type ParameterizedIssueCode = keyof IssueDataByCode;\n\n/**\n * `IssueCode` values that carry no `data` (`VALUE_INVALID`, `EMAIL`,\n * `REQUIRED`, …). Producers using one of these codes must omit `data`\n * (or pass `undefined`).\n */\nexport type BareIssueCode = Exclude<IssueCode, ParameterizedIssueCode>;\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { IssueCode } from './constants';\nimport type {\n BareIssueCode,\n IssueDataByCode,\n ParameterizedIssueCode,\n} from './constants';\nimport type {\n IssueBase,\n IssueGroup,\n IssueItem,\n IssueItemBare,\n IssueItemRaw,\n IssueItemTyped,\n ResolveIssueCode,\n} from './types';\n\ninterface DefineIssueItemCommon extends Omit<IssueBase, 'data'> {\n received?: unknown,\n expected?: unknown,\n}\n\n/**\n * Per-call `data` shape for {@link defineIssueItem}. The `data`\n * requirement is selected from the resolved `code`:\n *\n * - Parameterized code → `data` required, typed per {@link IssueDataByCode}.\n * - Bare code (incl. omitted, which resolves to `VALUE_INVALID`)\n * → `data` must be absent / `undefined`.\n * - Ad-hoc string code → `data` optional `Record`.\n */\ntype DefineIssueItemData<C> = DefineIssueItemCommon & {\n code?: C,\n} & (\n ResolveIssueCode<C> extends ParameterizedIssueCode ?\n { data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode] } :\n ResolveIssueCode<C> extends BareIssueCode ?\n { data?: undefined } :\n { data?: Record<string, unknown> }\n);\n\n/**\n * Return type for {@link defineIssueItem} — picks the concrete `IssueItem`\n * variant matching the resolved `code`.\n */\ntype DefineIssueItemReturn<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ?\n Extract<IssueItemTyped, { code: ResolveIssueCode<C> }> :\n ResolveIssueCode<C> extends BareIssueCode ?\n Extract<IssueItemBare, { code: ResolveIssueCode<C> }> :\n IssueItemRaw;\n\n/**\n * Build an `IssueItem`. TS uses the supplied `code` to pick the right\n * `data` requirement at the call site — passing `MIN_LENGTH` without\n * `data: { min }` is a compile error; passing `STRONG_PASSWORD` with\n * `data: { pointsPerUnique: 5 }` is a compile error.\n *\n * `code` may be omitted (defaults to `IssueCode.VALUE_INVALID` — bare,\n * no data).\n */\nexport function defineIssueItem<C extends string | undefined = undefined>(\n data: DefineIssueItemData<C>,\n): DefineIssueItemReturn<C> {\n return {\n type: 'item',\n ...data,\n code: (data as { code?: string }).code || IssueCode.VALUE_INVALID,\n } as unknown as DefineIssueItemReturn<C>;\n}\n\nexport function defineIssueGroup(data: Omit<IssueGroup, 'type'>): IssueGroup {\n return {\n type: 'group',\n ...data,\n };\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isIssueGroup, isIssueItem } from './check';\nimport type { Issue, IssueGroup, IssueItem } from './types';\n\nexport function flattenIssueItems(issues: Issue[]): IssueItem[] {\n const output: IssueItem[] = [];\n for (const issue of issues) {\n if (isIssueItem(issue)) {\n output.push(issue);\n } else {\n output.push(...flattenIssueItems(issue.issues));\n }\n }\n return output;\n}\n\nexport function flattenIssueGroups(issues: Issue[]): IssueGroup[] {\n const output: IssueGroup[] = [];\n for (const issue of issues) {\n if (isIssueGroup(issue)) {\n output.push(issue);\n output.push(...flattenIssueGroups(issue.issues));\n }\n }\n return output;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { interpolate } from '@ebec/core';\nimport type { IssueCode } from './constants';\nimport type { Issue } from './types';\n\n/**\n * Map of issue `code` → message template. Templates use `{name}` placeholders\n * — the same syntax `@ebec/core`'s `interpolate` understands — and are\n * resolved against `Issue.data` at format time.\n *\n * ```ts\n * const de: IssueMessageTemplates = {\n * value_invalid: 'Wert ist ungültig',\n * one_of_failed: 'Keine der Varianten war erfolgreich',\n * };\n * ```\n */\nexport type IssueMessageTemplates = Partial<Record<IssueCode, string>> & Record<string, string>;\n\n/**\n * Render an issue's user-facing message.\n *\n * Resolution order:\n * 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.\n * 2. Else return `issue.message` (the default English rendering set at\n * construction time).\n * 3. Else return `fallback`.\n */\nexport function formatIssue(\n issue: Issue,\n templates?: IssueMessageTemplates,\n fallback: string = '',\n): string {\n if (templates && issue.code) {\n const template = templates[issue.code];\n if (typeof template === 'string') {\n return interpolate(template, issue.data || {});\n }\n }\n if (typeof issue.message === 'string' && issue.message.length > 0) {\n return issue.message;\n }\n return fallback;\n}\n\n// Re-export ebec's `interpolate` so consumers writing custom formatters don't\n// need a direct dependency on `@ebec/core`. Same `{name}` placeholder syntax.\nexport { interpolate } from '@ebec/core';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isIssue } from '../issue';\nimport { hasOwnProperty, isObject } from '../utils';\nimport { ValidupError } from './base';\n\nexport function isError(input: unknown) : input is Error & { [key: string]: any } {\n // Primary check: anything that walks like an Error in this realm.\n // Keeps cross-realm fallbacks (e.g. errors from another iframe / vm\n // context where `instanceof Error` is false) duck-typed via the\n // `message` shape — which also matches `ValidupError`-shaped throws\n // from a duplicate copy of the package.\n if (input instanceof Error) {\n return true;\n }\n\n if (!isObject(input)) {\n return false;\n }\n\n return typeof input.message === 'string' && typeof input.name === 'string';\n}\n\nexport function isValidupError(error: unknown) : error is ValidupError {\n if (!isError(error)) {\n return false;\n }\n\n if (error instanceof ValidupError) {\n return true;\n }\n\n if (!hasOwnProperty(error, 'issues')) {\n return false;\n }\n\n return Array.isArray(error.issues) &&\n error.issues.every((issue) => isIssue(issue));\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isError, isValidupError } from '../error';\nimport { IssueCode, defineIssueItem } from '../issue';\nimport type { Issue } from '../issue';\n\n/**\n * Options for {@link errorToIssues}. Defaults match what the\n * orchestrating helpers (compose's collect-all catch, composeAnyOf's\n * branch-failure path) want out of the box.\n */\nexport type ErrorToIssuesOptions = {\n /**\n * Code stamped on the synthetic `IssueItem` when the thrown value\n * is an `Error` or a non-`Error` throw. Defaults to\n * `IssueCode.VALUE_INVALID`. `ValidupError` issues are spread\n * verbatim and DO NOT get this code applied; their own codes are\n * preserved.\n */\n code?: IssueCode | (string & {}),\n /**\n * Path on the synthetic `IssueItem`. Defaults to `[]`.\n * `ValidupError` issues are spread verbatim with their original\n * paths intact — callers that want to prefix or transform spread\n * paths should do so after this fold (the surrounding Container\n * run loop does this in `prefixIssuePath`, for example).\n */\n path?: PropertyKey[],\n};\n\n/**\n * The \"given an unknown throw, produce `Issue[]`\" cascade shared by\n * the validator-orchestrating helpers. The branching is identical\n * at each site — `ValidupError` fans out, `Error` becomes one item,\n * anything else gets a defensive stringify — so it lives here.\n *\n * - `ValidupError` → returns a fresh array containing each of its\n * `issues` verbatim (callers can map/prefix after).\n * - `Error` → returns one `IssueItem` carrying the message + supplied\n * code/path.\n * - Anything else (string, plain object, `null`, …) → returns one\n * defensively-stringified `IssueItem` so the aggregate is never\n * silently missing a contributing failure.\n *\n * Callers layer their own per-site concerns on top of the returned\n * issues: path prefixing, optional stamping, per-branch index\n * stamping, etc.\n */\nexport function errorToIssues(\n error: unknown,\n options: ErrorToIssuesOptions = {},\n): Issue[] {\n const code = options.code ?? IssueCode.VALUE_INVALID;\n const path = options.path ?? [];\n\n if (isValidupError(error)) {\n return [...error.issues];\n }\n\n if (isError(error)) {\n return [defineIssueItem({\n path,\n code,\n message: error.message,\n })];\n }\n\n return [defineIssueItem({\n path,\n code,\n message: typeof error === 'string' && error.length > 0 ?\n error :\n `Non-Error throw: ${String(error)}`,\n })];\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { IssueCode, defineIssueGroup } from '../issue';\nimport type { Issue, IssueGroup } from '../issue';\n\n/**\n * Options for {@link buildOneOfFailedGroup}.\n */\nexport type BuildOneOfFailedGroupOptions = {\n /**\n * Path on the wrapping group. Defaults to `[]` — most callers\n * (compose's `composeAnyOf`, the run-loop entry to a oneOf\n * container) emit the group at the boundary they own and let the\n * surrounding context attach a path.\n */\n path?: PropertyKey[],\n /**\n * Override the default English message. The wrapping group\n * carries `code: IssueCode.ONE_OF_FAILED`, so i18n catalogs key\n * off the code rather than the message; the message is only the\n * fallback rendering.\n */\n message?: string,\n};\n\n/**\n * Build the `IssueGroup` that wraps an every-branch-failed aggregate\n * — used by `composeAnyOf` (validator-level oneOf) AND\n * `Container.finalizeOutput` (container-level `oneOf` option). Sharing\n * the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so\n * consumers / i18n catalogs only need one format for both modes.\n */\nexport function buildOneOfFailedGroup(\n branchIssues: Issue[],\n options: BuildOneOfFailedGroupOptions = {},\n): IssueGroup {\n return defineIssueGroup({\n code: IssueCode.ONE_OF_FAILED,\n message: options.message ?? 'None of the branches succeeded',\n path: options.path ?? [],\n issues: branchIssues,\n });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isContainer } from '../container/check';\n// Leaf module, not the `../container` barrel — the barrel re-exports\n// `container/module.ts`, which imports from `../helpers`. Same discipline as\n// the `container/check` import above.\nimport { isStructuralThrow } from '../container/structural-throw';\nimport type { IContainer } from '../container/types';\nimport { ValidupError } from '../error';\nimport type { Issue } from '../issue';\nimport { isObject } from '../utils';\nimport { errorToIssues } from './error-to-issues';\nimport { buildOneOfFailedGroup } from './one-of-failed';\nimport type { Validator, ValidatorContext } from '../validator';\n\n/**\n * A composable element — either a bare `Validator<C>` function or a\n * fully-built `IContainer<T, C>` instance. Containers participate\n * with the same contract as validators (transform-or-throw); the\n * dispatcher (`invokeComposeElement`) hides the call-shape difference.\n *\n * `IContainer<any, any>` (rather than something tighter) keeps the\n * compose array heterogeneous — a chain can mix schemas / containers\n * with different output shapes without forcing the caller to widen\n * generics at every call site. The cost is that the composed\n * `Validator`'s `Out` defaults to `unknown` (same as before).\n */\nexport type ComposeElement<C = unknown> = Validator<C> | IContainer<any, any>;\n\n/**\n * Options for {@link compose}. Discriminated on `oneOf` so the type\n * surface enforces the (`bail` × `oneOf`) combinations that actually\n * make sense:\n *\n * - `{}` / `{ bail?: boolean }` / `{ oneOf: false }` — the **all**\n * strategy: every validator must pass, stages thread their return\n * value into the next, `bail` controls fail-fast vs. collect-all.\n * - `{ oneOf: true }` — the **any-of** strategy: the first branch to\n * succeed wins and the composed validator returns its value;\n * `bail` is rejected at compile time because there's no chain to\n * bail out of.\n */\nexport type ComposeOptions = {\n /**\n * Run every validator and require all to pass (default). Stages\n * thread their return into the next; `bail` controls whether the\n * first failure stops the chain (`true`, default) or every failure\n * is collected into one aggregate `ValidupError` (`false`).\n *\n * **Threading rule.** A stage's return replaces the threaded\n * `ctx.value` only when defined — `undefined` is treated as a\n * pass-through so pure checks that don't re-emit `ctx.value`\n * compose cleanly with transformers. Stages that DO want to\n * explicitly clear the field must throw or return a sentinel.\n */\n oneOf?: false,\n bail?: boolean,\n} | {\n /**\n * Run branches as alternatives in registration order — the first\n * one to succeed wins, subsequent branches are not invoked, and\n * the composed validator returns the winning branch's value\n * (falling back to `ctx.value` if the winning branch returned\n * `undefined`). When *every* branch fails, the composed validator\n * throws a `ValidupError` whose first issue is an `IssueGroup`\n * with `code: IssueCode.ONE_OF_FAILED` carrying every branch's\n * collected failures (per-branch index surfaced via\n * `data: { branch }`). Symmetric with\n * `Container.options.oneOf`, just at the validator level.\n *\n * Each branch sees the original `ctx.value` — no threading\n * across alternatives, since branches aren't a pipeline.\n * `bail` is intentionally rejected at the type level under this\n * mode: there's no chain to fail-fast over.\n */\n oneOf: true,\n};\n\n/**\n * Compose multiple validators into a single `Validator`.\n *\n * Default (`oneOf: false`) — validators run in order; each stage's\n * return value feeds the next as `ctx.value`. A stage that returns\n * `undefined` is treated as a pass-through (upstream value continues\n * down the chain), so pure checks that don't re-emit `ctx.value`\n * compose cleanly with transformers. `bail: true` (default) stops at\n * the first failure; `bail: false` collects every failure into a\n * single `ValidupError`.\n *\n * `oneOf: true` — branches run as alternatives in registration order;\n * the first branch to succeed wins and subsequent branches are not\n * invoked. When every branch fails, the composed validator throws a\n * `ValidupError` whose first issue is an `IssueGroup` with\n * `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.\n *\n * Elements can be bare `Validator<C>` functions OR fully-built\n * `IContainer<T, C>` instances — the dispatcher detects which and\n * either calls the function with the threaded `ctx` or invokes the\n * container's `run(value, { group, context, signal, path })` with\n * the threaded value as input. Containers participate with the same\n * transform-or-throw contract; their output replaces the threaded\n * value in the all-strategy chain, and a successful container wins\n * the branch in `oneOf` mode.\n *\n * @example\n * // Fail-fast (default) — sanitize then validate\n * container.mount('email', compose([\n * trim(),\n * isEmail(),\n * isLength({ max: 254 }),\n * ]));\n *\n * // Collect-all — surface every broken rule for a richer error UI\n * container.mount('password', compose([\n * isLength({ min: 8 }),\n * isAlphanumeric(),\n * matches(/[0-9]/),\n * ], { bail: false }));\n *\n * // Any-of — accept either an email or a phone number on the same field\n * container.mount('contact', compose([\n * isEmail(),\n * isMobilePhone(),\n * ], { oneOf: true }));\n *\n * // Any-of with a container branch — accept a contact string OR a\n * // nested address object validated by its own container.\n * container.mount('contact', composeOneOf([\n * isEmail(),\n * isMobilePhone(),\n * addressContainer,\n * ]));\n *\n * Throws that aren't `ValidupError` / `Error` (raw strings, plain\n * objects, null) are synthesized into a single `IssueItem` so the\n * aggregate is never silently missing a contributing failure — mirrors\n * `Container.recordMountError`'s defensive behavior.\n */\nexport function compose<C = unknown>(\n elements: ComposeElement<C>[],\n options: ComposeOptions = {},\n): Validator<C> {\n if (options.oneOf === true) {\n return composeAnyOf(elements);\n }\n\n const bail = options.bail ?? true;\n\n return async (ctx) => {\n const issues: Issue[] = [];\n let { value } = ctx;\n\n for (const element of elements) {\n try {\n // Spread a fresh ctx per stage so the threaded value\n // doesn't leak back to the caller via the input\n // reference — callers that compose inside their own\n // validator can keep reading `ctx.value` after the\n // composed call returns without seeing the post-thread\n // mutation.\n const result = await invokeComposeElement(element, { ...ctx, value });\n if (typeof result !== 'undefined') {\n value = result;\n }\n } catch (e) {\n // `bail` re-raises everything, so the structural check only\n // matters for the `{ bail: false }` opt-in — which otherwise\n // folds a cancelled run or a misconfigured graph into the\n // aggregate `ValidupError` alongside real validation issues,\n // leaving the caller unable to tell them apart.\n if (bail || isStructuralThrow(e, ctx.signal)) {\n throw e;\n }\n\n // Failing stage doesn't get to mutate the threaded\n // value — `value` keeps whatever the last successful\n // stage produced, so the next validator runs against a\n // well-defined input. Use the shared `errorToIssues`\n // cascade so the ValidupError / Error / non-Error fold\n // stays in lockstep with composeAnyOf and other\n // call sites.\n for (const issue of errorToIssues(e)) {\n issues.push(issue);\n }\n }\n }\n\n if (issues.length > 0) {\n throw new ValidupError(issues);\n }\n\n return value;\n };\n}\n\n/**\n * Sugar for `compose(elements, { oneOf: true })`. Reads more\n * naturally at the call site when the alternative semantic is the\n * intent, mirrors `Container`'s own `oneOf` option.\n */\nexport function composeOneOf<C = unknown>(\n elements: ComposeElement<C>[],\n): Validator<C> {\n return compose(elements, { oneOf: true });\n}\n\n/**\n * The `oneOf` execution path. Carved out so `compose`'s body stays\n * focused on the all-strategy chain and so the abort / per-branch\n * issue plumbing has somewhere to live without nesting.\n *\n * Each branch sees the original `ctx.value` (no threading across\n * alternatives). The first defined return wins; an `undefined` return\n * from a successful branch falls back to `ctx.value` so the\n * pass-through rule stays symmetric with the all-strategy path.\n *\n * Aborts are re-raised verbatim from inside the try (matches Container\n * behavior): a cancelled run isn't a validation outcome to wrap.\n */\nfunction composeAnyOf<C>(elements: ComposeElement<C>[]): Validator<C> {\n return async (ctx) => {\n const branchIssues: Issue[] = [];\n\n for (const [index, element] of elements.entries()) {\n // Pre-branch abort check — short-circuits cleanly before we\n // enter the per-branch try/catch, so aborts never get\n // rewritten into branch-failure issues.\n ctx.signal?.throwIfAborted();\n\n try {\n const result = await invokeComposeElement(element, { ...ctx });\n // First branch to succeed wins — pass-through rule:\n // if the winning branch didn't bother re-emitting\n // `ctx.value`, surface the input as the output.\n return typeof result === 'undefined' ? ctx.value : result;\n } catch (e) {\n // Cancellations and structural graph violations surface\n // verbatim instead of being folded into a branch failure —\n // the caller can distinguish \"no branch matched\" from\n // \"operation cancelled\" or \"this graph is misconfigured\".\n //\n // A container element raising `PathsStrictViolationError` or\n // `RunSyncViolationError` is not a branch that \"didn't match\";\n // it is a bug in the composition, and burying it under\n // `ONE_OF_FAILED` hides the one diagnostic that identifies it.\n if (isStructuralThrow(e, ctx.signal)) {\n throw e;\n }\n\n const wrapped = wrapBranchIssues(e, index);\n for (const issue of wrapped) {\n branchIssues.push(issue);\n }\n }\n }\n\n // Every branch (including the empty-branch-list case) failed.\n // Use the shared `buildOneOfFailedGroup` so consumers /\n // i18n catalogs handle compose's any-of the same way they\n // handle `Container.options.oneOf`.\n throw new ValidupError([buildOneOfFailedGroup(branchIssues)]);\n };\n}\n\n/**\n * Dispatch one compose element against the current `ctx`. Containers\n * receive `ctx.value` as their input (normalised to `{}` for non-object\n * values, mirroring how the `Container.run` loop handles a nested\n * container mounted against a non-object value); validators receive\n * `ctx` itself.\n *\n * Forwarded to the child container's `run`:\n *\n * - `group`, `context`, `signal` — the threaded run-level options\n * surfaced on `ctx`. Letting the child see `ctx.signal` matters for\n * aborting in-flight child validation when the outer run is\n * cancelled.\n * - `path: ctx.path` — used by the child's mounts to compute their\n * own `ctx.path`, so a validator inside the child sees the\n * absolute path it sits at (`['foo', 'street']`, not just\n * `['street']`). Issue *paths* in the final thrown error don't\n * depend on this forwarding — the outer Container's\n * `prefixIssuePath` step rebuilds them from each level's own\n * `keyParts` — but validators that inspect `ctx.path` (for\n * logging, custom error formatting, etc.) would see a misleading\n * relative path without it.\n * - `cache: ctx.cache` — the outer Container surfaces its run-level\n * `IResultCache` on `ctx`, so threading it here keeps a\n * container-as-branch participating in the same per-mount cache\n * the outer container is using. Without this forward, mounts\n * inside a compose-branch container would silently bypass the\n * cache, breaking the cache contract for the\n * `composeOneOf([…, childContainer])` shape.\n *\n * Other run-level options (`pathsToInclude`, `pathsToExclude`,\n * `defaults`, `parallel`) are intentionally NOT forwarded — they're\n * normally narrowed per-mount by the parent's run loop\n * (`resolvePathFilter`, `resolveDefaults`), and compose doesn't have\n * the parent mount key it would need to compute the equivalent\n * narrowing. A `composeOneOf` branch that's a container therefore\n * runs all of its mounts regardless of the outer's include/exclude\n * filter; if you need that level of inheritance, mount the container\n * directly with `container.mount(...)` instead of routing it through\n * compose.\n */\nasync function invokeComposeElement<C>(\n element: ComposeElement<C>,\n ctx: ValidatorContext<C>,\n): Promise<unknown> {\n if (isContainer(element)) {\n return element.run(\n isObject(ctx.value) ? ctx.value : {},\n {\n path: ctx.path,\n group: ctx.group,\n context: ctx.context,\n signal: ctx.signal,\n cache: ctx.cache,\n },\n );\n }\n // `isContainer` narrows `element` to `IContainer`, but the\n // negative branch leaves it as the original union — TypeScript\n // doesn't subtract `IContainer` from a union containing\n // `Validator<C>` because their structural shapes overlap\n // (functions are objects). Cast to recover the call signature.\n return (element as Validator<C>)(ctx);\n}\n\n/**\n * Normalize one branch's failure into `Issue[]` ready to merge into\n * the outer `ONE_OF_FAILED` group. Each issue is tagged with\n * `data: { branch: index }` so a tree-walking consumer can report\n * \"branch N failed because ...\" without needing to reconstruct\n * registration order.\n *\n * Delegates the unknown-throw → `Issue[]` fold to the shared\n * `errorToIssues` cascade; only the per-branch stamping is local\n * concern. Spread issues are shallow-cloned before stamping so the\n * `ValidupError` instance's `issues` array on the caller side isn't\n * mutated when a consumer reads `.data.branch` later.\n */\nfunction wrapBranchIssues(error: unknown, index: number): Issue[] {\n const stamp = <I extends Issue>(issue: I): I => {\n issue.data = { ...(issue.data ?? {}), branch: index };\n return issue;\n };\n return errorToIssues(error).map((issue) => stamp({ ...issue }));\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ValidupError } from '../error';\nimport { defineIssueItem } from '../issue';\nimport type { \n BareIssueCode, \n IssueCode, \n IssueDataByCode, \n ParameterizedIssueCode, \n ResolveIssueCode, \n} from '../issue';\n\n/**\n * Trailing-args shape selected by the resolved `code`:\n *\n * - Parameterized code → `data` is required and typed.\n * - Bare code → no trailing arg accepted.\n * - Ad-hoc string code → `data?: Record<string, unknown>` optional.\n */\ntype CreateValidupErrorTail<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ?\n [data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode]] :\n ResolveIssueCode<C> extends BareIssueCode ?\n [] :\n [data?: Record<string, unknown>];\n\n/**\n * Build a `ValidupError` carrying a single `IssueItem` with the supplied\n * code / message / data. Sugar for the common one-issue failure\n * construction used by adapters and hand-rolled validators.\n *\n * The caller throws — keeping the `throw` keyword at the call site\n * makes the failure path obvious in the validator function body:\n *\n * ```ts\n * if (!validator.isEmail(s)) {\n * throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');\n * }\n *\n * if (!isInRange(s)) {\n * throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });\n * }\n * ```\n *\n * The `code` you pass selects the `data` requirement at compile time:\n * parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their\n * typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any\n * other string falls through to an open `Record<string, unknown>` data\n * argument.\n *\n * For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),\n * build a `ValidupError` directly with\n * `new ValidupError([defineIssueItem(...), …])`.\n */\nexport function createValidupError<C extends string = typeof IssueCode.VALUE_INVALID>(\n received: unknown,\n code: C,\n message: string,\n ...rest: CreateValidupErrorTail<C>\n): ValidupError {\n const data = rest[0] as Record<string, unknown> | undefined;\n return new ValidupError([\n defineIssueItem({\n path: [],\n message,\n code,\n data,\n received,\n } as Parameters<typeof defineIssueItem>[0]),\n ]);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Slice a parent `defaults` map down to entries that target paths inside a\n * single nested container mount, with the mount-key prefix stripped so the\n * child sees them as local keys. Exact-key matches (the default targets the\n * mount root itself) are skipped — the parent's post-loop fill handles those\n * once the child has returned, since the child is run with `flat: true` and\n * cannot address its own root.\n */\nexport function resolveDefaults(\n defaults: Record<string, any> | undefined,\n key: string,\n): Record<string, any> | undefined {\n if (typeof defaults === 'undefined') {\n return undefined;\n }\n if (key.length === 0) {\n return defaults;\n }\n\n const output: Record<string, any> = {};\n let matched = false;\n const keys = Object.keys(defaults);\n for (const k of keys) {\n if (k.startsWith(`${key}.`)) {\n output[k.slice(key.length + 1)] = defaults[k];\n matched = true;\n }\n }\n return matched ? output : undefined;\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { distinctArray } from 'smob';\n\nexport function buildErrorMessageForAttribute(key: PropertyKey) {\n return `Property ${String(key)} is invalid`;\n}\n\nexport function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>) {\n let names: PropertyKey[];\n if (Array.isArray(input)) {\n names = distinctArray(input);\n } else {\n names = Object.keys(input);\n }\n\n if (names.length === 0) {\n return 'Properties are invalid';\n }\n\n if (names.length > 1) {\n return `Properties ${names.join(', ')} are invalid.`;\n }\n\n return buildErrorMessageForAttribute(names[0]);\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum GroupKey {\n WILDCARD = '*',\n}\n\n/**\n * Atomic vocabulary for `MountOptions.optionalValue`. Each atom matches\n * exactly one runtime value (the exception is `FALSY`, which stays as a\n * composite shortcut). Compose multiple atoms by passing an array:\n * `optionalValue: ['undefined', 'null', 'empty_string']`.\n */\nexport enum OptionalValue {\n /**\n * `value === undefined`. **Default** when `optionalValue` is not set,\n * so the core stays conservative — `0` / `''` / `false` are real\n * values and reach the validator unless the caller opts in.\n */\n UNDEFINED = 'undefined',\n /** `value === null` (does **not** include `undefined`). */\n NULL = 'null',\n /** `value === ''`. */\n EMPTY_STRING = 'empty_string',\n /** `value === 0` (also matches `-0`). */\n ZERO = 'zero',\n /** `value === false`. */\n FALSE = 'false',\n /** `Number.isNaN(value)`. */\n NAN = 'nan',\n /**\n * Composite shortcut — any JS falsy value\n * (`undefined`, `null`, `''`, `0`, `false`, `NaN`). Use when you\n * really mean \"any of the JS falsy sentinels\"; otherwise pick\n * specific atoms (or compose an array) so a `0` / `false` / `''`\n * with a meaningful semantic isn't silently swallowed.\n */\n FALSY = 'falsy',\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { OptionalValue } from '../constants';\n\nexport type OptionalValueInput = `${OptionalValue}` | readonly `${OptionalValue}`[];\n\n/**\n * Check whether `value` qualifies as \"optional\" under the supplied\n * `optionalValue` definition.\n *\n * The definition can be a single atom (`'undefined'`, `'null'`, `'empty_string'`,\n * `'zero'`, `'false'`, `'nan'`, `'falsy'`) or an array of atoms — in array form\n * the value is optional iff **any** atom matches. Atoms match exactly one\n * runtime value (the only exception is `'falsy'`, which stays as a composite\n * shortcut for \"any JS falsy value\"). To skip on `null` *or* `undefined`,\n * pass `['null', 'undefined']` explicitly.\n *\n * Default is `'undefined'` so the core stays conservative — `0` / `''` /\n * `false` reach the validator unless the caller explicitly opts in.\n */\nexport function isOptionalValue(\n value: unknown,\n optionalValue?: OptionalValueInput,\n) {\n const input = optionalValue ?? OptionalValue.UNDEFINED;\n if (Array.isArray(input)) {\n for (const atom of input) {\n if (matchAtom(value, atom)) {\n return true;\n }\n }\n return false;\n }\n return matchAtom(value, input as `${OptionalValue}`);\n}\n\nfunction matchAtom(value: unknown, atom: `${OptionalValue}`): boolean {\n switch (atom) {\n case OptionalValue.UNDEFINED:\n return typeof value === 'undefined';\n case OptionalValue.NULL:\n return value === null;\n case OptionalValue.EMPTY_STRING:\n return value === '';\n case OptionalValue.ZERO:\n return value === 0;\n case OptionalValue.FALSE:\n return value === false;\n case OptionalValue.NAN:\n return typeof value === 'number' && Number.isNaN(value);\n case OptionalValue.FALSY:\n return !value;\n default:\n return false;\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport type PathFilterResolution = {\n skip: boolean,\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n};\n\n/**\n * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's\n * (already-expanded) local `key`. Returns whether to skip the item, plus the\n * filter sub-lists to forward into a child container — with the parent prefix\n * stripped so the child can match purely against its own local keys.\n *\n * Semantics:\n * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so\n * filters are forwarded verbatim.\n * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.\n * - Prefix match (`<key>.…`) only descends into container mounts; leaf\n * validators with deeper-target filters fall through (skipped for include,\n * kept for exclude).\n */\nexport function resolvePathFilter(\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n key: string,\n isContainer: boolean,\n): PathFilterResolution {\n if (key.length === 0) {\n return {\n skip: false,\n pathsToInclude,\n pathsToExclude,\n };\n }\n\n let includeForward: string[] | undefined;\n if (typeof pathsToInclude !== 'undefined') {\n let exact = false;\n const stripped: string[] = [];\n for (const path of pathsToInclude) {\n if (path === key) {\n exact = true;\n } else if (isContainer && path.startsWith(`${key}.`)) {\n stripped.push(path.slice(key.length + 1));\n }\n }\n if (exact) {\n includeForward = undefined;\n } else if (stripped.length > 0) {\n includeForward = stripped;\n } else {\n return {\n skip: true,\n pathsToInclude: undefined,\n pathsToExclude: undefined,\n };\n }\n }\n\n let excludeForward: string[] | undefined;\n if (typeof pathsToExclude !== 'undefined') {\n const stripped: string[] = [];\n for (const path of pathsToExclude) {\n if (path === key) {\n return {\n skip: true,\n pathsToInclude: undefined,\n pathsToExclude: undefined,\n };\n }\n if (isContainer && path.startsWith(`${key}.`)) {\n stripped.push(path.slice(key.length + 1));\n }\n }\n if (stripped.length > 0) {\n excludeForward = stripped;\n }\n }\n\n return {\n skip: false,\n pathsToInclude: includeForward,\n pathsToExclude: excludeForward,\n };\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { arrayToPath } from 'pathtrace';\n\n/**\n * Stringify path array to string.\n *\n * @param input\n */\nexport function stringifyPath(input: PropertyKey[]) : string {\n return arrayToPath(input);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ValidatorDescriptor } from './types';\nimport { isObject } from '../utils';\n\n/**\n * Duck-typed guard for {@link ValidatorDescriptor}. Used by `mount()` to\n * distinguish a descriptor from a bare `Validator` function and from a\n * nested `IContainer` (which is also an object but carries `run` /\n * `safeRun` methods — the descriptor has a `run` function but no\n * `safeRun`).\n *\n * Duck-typed (not `instanceof`) so descriptors built from a different\n * copy of the package — adapters bundling their own `validup` dependency,\n * pnpm workspaces with multiple installs — still round-trip cleanly.\n */\nexport function isValidatorDescriptor<C = unknown, Out = unknown>(\n input: unknown,\n): input is ValidatorDescriptor<C, Out> {\n if (!isObject(input)) {\n return false;\n }\n\n return (\n typeof input.run === 'function' &&\n typeof input.safeRun !== 'function'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ValidatorDescriptor } from './types';\n\n/**\n * Factory for a {@link ValidatorDescriptor}. Mirrors the\n * `defineIssueItem` / `defineIssueGroup` shape used elsewhere in the\n * library so authored validators get a stable, typed construction site.\n *\n * @example\n * const validateEmailUnique = defineValidator({\n * sideEffect: true,\n * run: async (ctx) => {\n * const taken = await api.isEmailTaken(ctx.value as string);\n * if (taken) throw new Error('Email is already taken');\n * return ctx.value;\n * },\n * });\n */\nexport function defineValidator<C = unknown, Out = unknown>(\n descriptor: ValidatorDescriptor<C, Out>,\n): ValidatorDescriptor<C, Out> {\n return descriptor;\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Path } from 'pathtrace';\nimport {\n expandPath,\n getPathValue,\n pathToArray,\n setPathValue,\n} from 'pathtrace';\nimport type {\n IResultCache,\n ResultCacheOutcome,\n ResultCacheSnapshot,\n} from '../cache';\nimport { GroupKey } from '../constants';\nimport { ValidupError, isError, isValidupError } from '../error';\nimport type { PathFilterResolution } from '../helpers';\nimport {\n buildErrorMessageForAttribute,\n buildOneOfFailedGroup,\n errorToIssues,\n isOptionalValue,\n resolveDefaults,\n resolvePathFilter,\n stringifyPath,\n} from '../helpers';\nimport { hasOwnProperty, isObject } from '../utils';\nimport type { TwinBody } from 'twinop';\nimport { op, runTwinAsync, runTwinSync } from 'twinop';\nimport type {\n Validator,\n ValidatorContext,\n ValidatorDescriptor,\n} from '../validator';\nimport { isValidatorDescriptor } from '../validator';\nimport { isContainer } from './check';\nimport type {\n ContainerInput,\n ContainerOptions,\n ContainerRunOptions,\n IContainer,\n Mount,\n MountOptions,\n Result,\n} from './types';\nimport type { Issue } from '../issue';\nimport { IssueCode, defineIssueGroup, defineIssueItem } from '../issue';\nimport { RunSyncViolationError } from './run-sync-violation';\nimport { PathsStrictViolationError } from './paths-strict-violation';\nimport { isStructuralThrow } from './structural-throw';\n\n/**\n * Bundle of state the error path needs from the surrounding run loop.\n * Grouped to keep `collectExecutionFailure`'s signature readable and to make\n * additions (e.g. extra provenance fields for meta stamping) a one-line\n * change at every call site instead of a positional-arg shuffle.\n */\ntype ExecutionFailureContext<C> = {\n error: unknown,\n item: Mount<C>,\n /**\n * The input value handed to the failing mount — retained so we can\n * re-evaluate predicate-optional declarations at error time without\n * relying on a \"predicate already returned false in the run loop\"\n * invariant.\n */\n value: unknown,\n /** Expanded mount path. Prepended to nested `ValidupError` issues. */\n keyParts: PropertyKey[],\n /** Trailing path segment. Drives the wrapping `IssueGroup` shape. */\n pathRelative: PropertyKey | undefined,\n /** Accumulator the error path writes into. */\n issues: Issue[],\n /** Per-run abort signal. If aborted, the throw is re-raised verbatim. */\n signal: AbortSignal | undefined,\n};\n\n/**\n * Everything a single `(mount, expanded key)` pair needs before the mount can\n * be dispatched. Produced once per key by `Container.prepareMountKey` and\n * consumed identically by the twin body and by `runParallel`.\n *\n * Notably absent: the mount's input `value`. Sequential runs chain-read\n * `output` before `data` (so sanitize-then-validate works across sibling\n * mounts) while `runParallel` reads `data` only — that asymmetry is a\n * documented behavioural difference, so it stays in the caller and this stays\n * pure.\n */\ntype MountKeyPlan = {\n /** Expanded key split into segments. Prefixed onto child issue paths. */\n keyParts: PropertyKey[],\n /** Trailing segment. Drives the wrapping `IssueGroup` shape on failure. */\n pathRelative: PropertyKey | undefined,\n /** Global path (parent prefix + `keyParts`) handed to validators/children. */\n pathAbsolute: PropertyKey[],\n /** Include/exclude verdict plus the sub-lists to forward to a child. */\n filter: PathFilterResolution,\n};\n\n/**\n * Outcome of the optional gate for one `(mount, value)` pair.\n *\n * - `skip: false` — the mount runs normally.\n * - `skip: true, write: true` — the mount is skipped and `value` is assigned\n * to `output[key]`.\n * - `skip: true, write: false` — the mount is skipped and the key is omitted.\n *\n * `write` is what carries the presence-not-value semantics of `optionalAs`:\n * `{ skip: true, write: true, value: undefined }` is the deliberate \"emit\n * `undefined`\" directive, distinct from \"omit the key\".\n */\ntype OptionalDirective = {\n skip: boolean,\n write: boolean,\n value?: unknown,\n};\n\n/**\n * Structural thenable probe. Used by the sync side of the validator effect to\n * reject the one thing a synchronous graph cannot tolerate: a validator that\n * returned a promise.\n */\nfunction isThenable(input: unknown): input is PromiseLike<unknown> {\n return isObject(input) &&\n typeof (input as { then?: unknown }).then === 'function';\n}\n\nexport class Container<\n T extends Record<string, any> = Record<string, any>,\n C = unknown,\n> implements IContainer<T, C> {\n protected options : ContainerOptions<T>;\n\n protected items : Mount<C>[];\n\n // ----------------------------------------------\n\n constructor(options: ContainerOptions<T> = {}) {\n this.options = options;\n this.items = [];\n\n this.initialize();\n }\n\n // ----------------------------------------------\n\n mount(container: IContainer<any, any>) : void;\n\n mount(\n options: MountOptions,\n container: IContainer<any, any>\n ): void;\n\n mount(\n key: Path<T> | (string & {}),\n data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>\n ) : void;\n\n mount(\n key: Path<T> | (string & {}),\n options: MountOptions,\n data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>\n ) : void;\n\n mount(...args: any[]) : void {\n if (args.length < 1) {\n throw new SyntaxError('The mount method requires at least one argument');\n }\n if (args.length > 3) {\n throw new SyntaxError(`mount() accepts at most 3 arguments, got ${args.length}`);\n }\n\n let path : string | undefined;\n let pathSeen = false;\n\n let data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C> | undefined;\n let dataSeen = false;\n // Tracked separately so we don't re-detect on store — `isContainer` /\n // `isValidatorDescriptor` walk the value once each here, then the\n // result is consulted directly when we push onto `this.items`.\n let dataKind: 'container' | 'validator' | 'descriptor' | undefined;\n\n let options: MountOptions = {};\n let optionsSeen = false;\n\n for (const arg of args) {\n if (typeof arg === 'string') {\n if (pathSeen) {\n throw new SyntaxError('mount() received multiple string arguments — only one path is supported.');\n }\n pathSeen = true;\n path = arg;\n continue;\n }\n\n if (typeof arg === 'function') {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'validator';\n continue;\n }\n\n if (isContainer(arg)) {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'container';\n continue;\n }\n\n // Descriptor check goes BEFORE the generic `isObject` branch:\n // a `ValidatorDescriptor` is an object that happens to carry\n // a `run` function but lacks `safeRun`, distinguishing it from\n // both `MountOptions` (no `run`) and `IContainer` (has both\n // `run` and `safeRun`).\n if (isValidatorDescriptor(arg)) {\n if (dataSeen) {\n throw new SyntaxError('mount() received multiple validator/container arguments.');\n }\n dataSeen = true;\n data = arg;\n dataKind = 'descriptor';\n continue;\n }\n\n if (isObject(arg)) {\n if (optionsSeen) {\n throw new SyntaxError('mount() received multiple options objects.');\n }\n optionsSeen = true;\n options = arg;\n }\n }\n\n if (\n dataKind !== 'container' &&\n (typeof path === 'undefined' || path.length === 0)\n ) {\n throw new SyntaxError('Only a container can be mounted without a key.');\n }\n\n if (typeof data === 'undefined' || typeof dataKind === 'undefined') {\n throw new SyntaxError('No container/validator could be extracted from the fn arguments.');\n }\n\n if (dataKind === 'container') {\n this.items.push({\n options,\n data: data as IContainer<any, any>,\n path,\n type: 'container',\n });\n\n return;\n }\n\n if (dataKind === 'descriptor') {\n const descriptor = data as ValidatorDescriptor<C>;\n this.items.push({\n options,\n data: descriptor.run,\n path,\n type: 'validator',\n sideEffect: descriptor.sideEffect,\n });\n return;\n }\n\n this.items.push({\n options,\n data: data as Validator<C>,\n path,\n type: 'validator',\n });\n }\n\n // ----------------------------------------------\n\n /**\n * Run the container against `data`. Default execution mode — async,\n * sequential, throws `ValidupError` on validation failure.\n *\n * Variants for the other execution modes:\n * - `run(data, { parallel: true })` — async, sequential→concurrent. Each\n * mount captures `value` from `data` before any sibling runs, so chained\n * sanitize-then-validate patterns are not supported.\n * - {@link Container.safeRun} — same as `run` but returns a discriminated\n * `Result<T>` instead of throwing on validation failure (still rethrows\n * on abort).\n * - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous\n * variants for graphs where every validator (and every nested container's\n * `runSync`) is synchronous.\n *\n * Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`\n * between mounts (which throws `signal.reason`), and any error raised by a\n * mid-flight validator during an aborted run is re-thrown as-is rather than\n * folded into the issue tree. Callers can therefore distinguish \"validation\n * failed\" from \"operation cancelled,\" but should not assume the thrown value\n * is always `signal.reason` — a validator that throws its own error before\n * the next abort check produces that error instead.\n *\n * @throws ValidupError on validation failure.\n * @throws signal.reason when the abort check fires between mounts.\n * @throws (mid-flight validator error) when a validator throws during an\n * already-aborted run — re-raised as-is rather than wrapped.\n */\n async run(\n data: ContainerInput<T> = {},\n options: ContainerRunOptions<T, C> = {},\n ): Promise<T> {\n if (options.parallel) {\n return this.runParallel(data, options);\n }\n\n return runTwinAsync(this.runBody(data, options));\n }\n\n /**\n * The single mount-resolution loop behind {@link Container.run} and\n * {@link Container.runSync}.\n *\n * Written as a **twin body** (the `twinop` package): the two impure edges,\n * invoking a validator and descending into a nested container, are yielded\n * as `op(asyncThunk, syncThunk)` pairs, and the driver chosen by the public\n * method (`runTwinAsync` / `runTwinSync`) executes the matching side. Effect\n * errors are thrown back in at the `yield` site, so the cache-write and\n * issue-collection `try`/`catch` blocks below run identically in both\n * variants, with no second copy of the loop to keep in lockstep.\n *\n * The sync thunks own the two structural probes that only `runSync` needs:\n * a nested container that doesn't implement `runSync`, and a validator that\n * returned a thenable. Both throw `RunSyncViolationError`, which the async\n * side cannot produce.\n *\n * `runParallel` deliberately does NOT share this body — a generator is\n * sequential by construction, and expressing \"launch every mount, then\n * settle\" through it would mean yielding batches and giving up the\n * chain-read. It shares the extracted per-key helpers instead\n * (`prepareMountKey` / `resolveOptionalDirective` / `buildChildRunOptions` /\n * `buildValidatorContext`).\n */\n private * runBody(\n data: ContainerInput<T>,\n options: ContainerRunOptions<T, C>,\n ): TwinBody<T> {\n const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);\n const pathsStrict = this.resolvePathsStrict(options);\n // Structural pre-flight — throws before any validator runs.\n this.assertPathsStrict(pathsStrict, data, pathsToInclude, pathsToExclude, options.path);\n\n const output: Record<string, any> = {};\n const issues: Issue[] = [];\n\n let itemCount = 0;\n let errorCount = 0;\n\n for (let i = 0; i < this.items.length; i++) {\n // Pre-mount abort check — cheap and short-circuits cleanly without\n // entering the per-mount try/catch (so aborts don't get rewritten\n // into validation issues).\n options.signal?.throwIfAborted();\n\n const item = this.items[i];\n\n if (!this.isItemGroupIncluded(item, options.group)) {\n continue;\n }\n\n let pathCount = 0;\n let pathFailed = false;\n const branchStart = issues.length;\n\n // Path expansion reads the input, so a hostile accessor (an ORM\n // entity with a lazy relation, a computed getter, a Proxy trap)\n // throws here — before any key exists. Contained rather than left\n // to escape: an escape aborts the whole loop and discards every\n // issue collected by earlier mounts, turning a real multi-field\n // failure into one path-less item. `keys` stays empty so the key\n // loop is skipped while the shared bookkeeping below still counts\n // the mount as one failed path.\n let keys: string[] = [];\n try {\n keys = item.path ? expandPath(data, item.path) : [''];\n } catch (e) {\n const attribution = this.describeKey(item.path || '');\n this.collectExecutionFailure({\n error: e,\n item,\n value: undefined,\n keyParts: attribution.keyParts,\n pathRelative: attribution.pathRelative,\n issues,\n signal: options.signal,\n });\n pathCount = 1;\n pathFailed = true;\n }\n\n for (const key of keys) {\n // Declared outside the `try` so the catch can attribute a\n // pre-dispatch throw: `plan` is `undefined` when\n // `prepareMountKey` itself threw, and `value` is whatever the\n // read managed to produce.\n let plan: MountKeyPlan | undefined;\n let value: unknown;\n\n try {\n plan = this.prepareMountKey(item, key, options, pathsToInclude, pathsToExclude);\n\n if (key.length > 0) {\n value = hasOwnProperty(output, key) ?\n output[key] :\n getPathValue(data, key);\n } else {\n value = data;\n }\n\n if (plan.filter.skip) {\n continue;\n }\n\n const optional = this.resolveOptionalDirective(item, value, options);\n\n if (optional.skip) {\n if (optional.write) {\n output[key] = optional.value;\n }\n } else if (item.type === 'container') {\n const child = item.data;\n const childInput = isObject(value) ? value : {};\n const childOptions = this.buildChildRunOptions(options, key, plan, pathsStrict);\n\n const tmp: Record<string, any> = yield* op(\n () => child.run(childInput, childOptions),\n () => {\n const childRunSync = (\n child as IContainer<any, any> & {\n runSync?: (...args: any[]) => any\n }\n ).runSync;\n if (typeof childRunSync !== 'function') {\n throw new RunSyncViolationError(`runSync: nested container at \"${key || '<root>'}\" does not implement runSync`);\n }\n\n return childRunSync.call(child, childInput, childOptions);\n },\n );\n\n const tmpKeys = Object.keys(tmp);\n for (const tmpKey of tmpKeys) {\n output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];\n }\n } else if (item.type === 'validator') {\n const snapshot: ResultCacheSnapshot = {\n value,\n context: options.context,\n group: options.group,\n };\n const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);\n if (cached) {\n if (cached.ok) {\n output[key] = cached.value;\n } else {\n // Replay the prior error through the same outer-catch\n // path so issue construction (path prefixing, optional\n // stamping) runs with the *current* `keyParts` — vital\n // when the same container is mounted under different\n // parents across runs.\n throw cached.error;\n }\n } else {\n const validator = item.data;\n const ctx = this.buildValidatorContext(key, plan, value, data, options);\n\n try {\n const result = yield* op(\n () => validator(ctx),\n () => {\n const outcome = validator(ctx);\n if (isThenable(outcome)) {\n throw new RunSyncViolationError(`runSync: validator at \"${key || '<root>'}\" returned a Promise`);\n }\n return outcome;\n },\n );\n output[key] = result;\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: true, value: result },\n options.cache,\n options.signal,\n );\n } catch (e) {\n // Structural throws are graph-level errors, not\n // validation outcomes — don't pollute the cache with\n // one the next run might reach through different\n // mounts.\n //\n // Pinned by `cache.spec.ts` → \"does not cache a\n // RunSyncViolationError\": drop this guard and a\n // failed `runSync` poisons the slot, so the next\n // *async* `run()` replays the violation through\n // `collectExecutionFailure` — which rethrows it\n // structurally — instead of succeeding. The same\n // now holds for `PathsStrictViolationError`, which a\n // validator driving its own strict child container\n // can raise and which used to be cached here.\n //\n // `runParallel`'s cache-write catch applies the\n // identical guard — the two sites must agree, or a\n // shared `ResultCache` handed to both run modes\n // would replay entries one of them refuses to write.\n if (!isStructuralThrow(e, options.signal)) {\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: false, error: e },\n options.cache,\n options.signal,\n );\n }\n throw e;\n }\n }\n }\n } catch (e) {\n const attribution = plan || this.describeKey(key);\n this.collectExecutionFailure({\n error: e,\n item,\n value,\n keyParts: attribution.keyParts,\n pathRelative: attribution.pathRelative,\n issues,\n signal: options.signal,\n });\n pathFailed = true;\n }\n\n pathCount++;\n }\n\n if (pathCount > 0) {\n itemCount++;\n\n if (pathFailed) {\n errorCount++;\n this.wrapBranchForOneOf(issues, branchStart, item, i);\n }\n }\n }\n\n return this.finalizeOutput(output, options, issues, errorCount, itemCount);\n }\n\n /**\n * Parallel-execution variant of `run()`. All mounts kick off their\n * promises eagerly and the results are merged after `Promise.allSettled`.\n * See `ContainerRunOptions.parallel` for the trade-off note.\n *\n * Shares every per-key helper with the sequential twin body\n * (`prepareMountKey` / `resolveOptionalDirective` / `buildChildRunOptions` /\n * `buildValidatorContext` / the cache pair) but keeps its own scheduling\n * loop — see the note on {@link Container.runBody} for why it can't be a\n * third twin driver.\n */\n private async runParallel(\n data: ContainerInput<T>,\n options: ContainerRunOptions<T, C>,\n ): Promise<T> {\n const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);\n const pathsStrict = this.resolvePathsStrict(options);\n // Structural pre-flight — throws before any mount's promise is created.\n this.assertPathsStrict(pathsStrict, data, pathsToInclude, pathsToExclude, options.path);\n\n const output: Record<string, any> = {};\n const issues: Issue[] = [];\n\n type KeyTask = {\n key: string,\n keyParts: PropertyKey[],\n pathRelative: PropertyKey | undefined,\n // Retained for `collectExecutionFailure` so it can re-evaluate\n // predicate-optional mounts at error time.\n value: unknown,\n promise: Promise<unknown>,\n kind: 'container' | 'validator',\n };\n\n type ItemGroup = {\n item: Mount<C>,\n // Original registration index in `this.items`. Tracked separately\n // from the position in `itemGroups` because group-filtered mounts\n // are dropped from `itemGroups` — without this, `data.branch`\n // emitted by `wrapBranchForOneOf` would not match the\n // registration order seen by the consumer.\n mountIndex: number,\n tasks: KeyTask[],\n // optional/skip paths that completed inline still count toward\n // the per-item pathCount used for oneOf / errorCount tracking.\n syncPathCount: number,\n };\n\n const itemGroups: ItemGroup[] = [];\n\n for (let i = 0; i < this.items.length; i++) {\n options.signal?.throwIfAborted();\n\n const item = this.items[i];\n if (!this.isItemGroupIncluded(item, options.group)) {\n continue;\n }\n\n const tasks: KeyTask[] = [];\n let syncPathCount = 0;\n\n // Same containment as the twin body, and strictly more urgent\n // here: by the time this runs, earlier mounts' promises are\n // already in flight. An escape would leave them unowned as well\n // as dropping their issues — see {@link Container.ownRejection}.\n let keys: string[] = [];\n try {\n keys = item.path ? expandPath(data, item.path) : [''];\n } catch (e) {\n const attribution = this.describeKey(item.path || '');\n tasks.push({\n key: item.path || '',\n keyParts: attribution.keyParts,\n pathRelative: attribution.pathRelative,\n value: undefined,\n promise: this.ownRejection(Promise.reject(e)),\n kind: item.type,\n });\n }\n\n for (const key of keys) {\n // See the twin body's copy of this block: `plan` stays\n // `undefined` when `prepareMountKey` itself threw, and the\n // catch below turns any pre-dispatch throw into a rejected\n // task instead of letting it escape the scheduling loop.\n let plan: MountKeyPlan | undefined;\n let value: unknown;\n let promise: Promise<unknown>;\n\n try {\n plan = this.prepareMountKey(item, key, options, pathsToInclude, pathsToExclude);\n\n if (key.length > 0) {\n // Parallel mode reads `data` only — `output[key]` from a\n // sibling mount is intentionally NOT consulted (the\n // sibling may not have completed yet).\n value = getPathValue(data, key);\n } else {\n value = data;\n }\n\n if (plan.filter.skip) {\n continue;\n }\n\n const optional = this.resolveOptionalDirective(item, value, options);\n if (optional.skip) {\n if (optional.write) {\n output[key] = optional.value;\n }\n syncPathCount++;\n continue;\n }\n\n promise = this.ownRejection(\n this.dispatchParallelMount(item, key, plan, value, data, options, pathsStrict),\n );\n } catch (e) {\n // Materialized as a rejected task so the single merge loop\n // below folds pre-dispatch and validator failures through\n // the same `collectExecutionFailure` path, preserving both\n // registration order and the sibling mounts' issues.\n promise = this.ownRejection(Promise.reject(e));\n }\n\n const attribution = plan || this.describeKey(key);\n tasks.push({\n key,\n keyParts: attribution.keyParts,\n pathRelative: attribution.pathRelative,\n value,\n promise,\n kind: item.type,\n });\n }\n\n if (tasks.length > 0 || syncPathCount > 0) {\n itemGroups.push({\n item,\n mountIndex: i,\n tasks,\n syncPathCount,\n });\n }\n }\n\n // Wait for all groups concurrently. Promises were already kicked off\n // eagerly above; this just collects their settled state.\n const settledByGroup = await Promise.all(itemGroups.map(\n (group) => Promise.allSettled(group.tasks.map((t) => t.promise)),\n ));\n\n // Re-check the abort signal after settling. Sequential `run`/`runSync`\n // probe between every mount; the parallel variant can only check here\n // and before `finalizeOutput`. Without this, validators that ignore\n // `ctx.signal` would let an aborted run resolve to a successful result.\n options.signal?.throwIfAborted();\n\n let itemCount = 0;\n let errorCount = 0;\n\n for (const [i, {\n item,\n mountIndex,\n tasks,\n syncPathCount,\n }] of itemGroups.entries()) {\n const settled = settledByGroup[i];\n\n let pathFailed = false;\n const branchStart = issues.length;\n for (const [j, task] of tasks.entries()) {\n const result = settled[j];\n\n if (result.status === 'fulfilled') {\n if (task.kind === 'container') {\n const tmp = result.value as Record<string, any>;\n const tmpKeys = Object.keys(tmp);\n for (const tmpKey of tmpKeys) {\n output[this.mergePaths(task.key, tmpKey)] = tmp[tmpKey];\n }\n } else {\n output[task.key] = result.value;\n }\n } else {\n this.collectExecutionFailure({\n error: result.reason,\n item,\n value: task.value,\n keyParts: task.keyParts,\n pathRelative: task.pathRelative,\n issues,\n signal: options.signal,\n });\n pathFailed = true;\n }\n }\n\n if (tasks.length + syncPathCount > 0) {\n itemCount++;\n if (pathFailed) {\n errorCount++;\n // Use the original registration index so `data.branch`\n // matches the registration order regardless of group\n // filtering — sequential `run()` / `runSync()` already\n // pass the registration index directly.\n this.wrapBranchForOneOf(issues, branchStart, item, mountIndex);\n }\n }\n }\n\n // Final guard before returning a (potentially successful) value — if\n // the run was aborted after the post-settle check but before the merge\n // loop finished, propagate the abort instead of returning stale data.\n options.signal?.throwIfAborted();\n\n return this.finalizeOutput(output, options, issues, errorCount, itemCount);\n }\n\n /**\n * Claim ownership of a scheduled mount's rejection.\n *\n * `runParallel` creates every mount's promise eagerly and only attaches\n * `Promise.allSettled` after the whole scheduling loop has run. Any\n * rejection settling in that window — or, worse, any throw that escapes\n * the loop before `allSettled` is reached at all — is unowned, and Node's\n * default `--unhandled-rejections=throw` (this package requires Node >=\n * 24) terminates the process.\n *\n * The no-op subscriber below is a *second* consumer, discarded\n * immediately; the original promise is returned unchanged, so\n * `Promise.allSettled` still observes the real settlement and no outcome\n * is swallowed.\n */\n private ownRejection<P extends Promise<unknown>>(promise: P): P {\n promise.catch(() => { /* ownership only — see doc comment */ });\n\n return promise;\n }\n\n /**\n * Create the in-flight promise for one scheduled mount. Extracted from\n * `runParallel`'s scheduling loop so the loop body reads as\n * \"resolve, gate, dispatch\" and the pre-dispatch `try` stays legible.\n */\n private dispatchParallelMount(\n item: Mount<C>,\n key: string,\n plan: MountKeyPlan,\n value: unknown,\n data: ContainerInput<T>,\n options: ContainerRunOptions<T, C>,\n pathsStrict: boolean,\n ): Promise<unknown> {\n if (item.type === 'container') {\n return item.data.run(\n isObject(value) ? value : {},\n this.buildChildRunOptions(options, key, plan, pathsStrict, true),\n );\n }\n\n const snapshot: ResultCacheSnapshot = {\n value,\n context: options.context,\n group: options.group,\n };\n\n const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);\n if (cached) {\n // Materialize cached outcomes as already-settled promises\n // so the existing `Promise.allSettled` merge loop handles\n // them identically to fresh runs — no parallel-specific\n // replay code path.\n return cached.ok ?\n Promise.resolve(cached.value) :\n Promise.reject(cached.error);\n }\n // Wrap sync validators in a microtask so the surrounding\n // `Promise.allSettled` always sees a thenable. Cache writes happen\n // inside the wrapper so the entry is persisted before the promise\n // settles.\n const validator = item.data;\n const ctx = this.buildValidatorContext(key, plan, value, data, options);\n\n return (async () => {\n try {\n const result = await validator(ctx);\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: true, value: result },\n options.cache,\n options.signal,\n );\n return result;\n } catch (e) {\n // Structural violations are not validation outcomes — the\n // validator graph is wrong, not the input — so they must not\n // be remembered and replayed on a later hit. The twin body\n // carves out the same class of throw at its own cache-write\n // site; this one previously had no filter at all, so a\n // `RunSyncViolationError` or `PathsStrictViolationError`\n // raised by a validator driving its own child container was\n // cached and replayed.\n if (!isStructuralThrow(e, options.signal)) {\n this.writeCachedOutcome(\n item,\n key,\n snapshot,\n { ok: false, error: e },\n options.cache,\n options.signal,\n );\n }\n throw e;\n }\n })();\n }\n\n async safeRun(input: ContainerInput<T> = {}, options: ContainerRunOptions<T, C> = {}): Promise<Result<T>> {\n try {\n const data = await this.run(input, options);\n return { success: true, data };\n } catch (e) {\n return this.wrapSafeRunError(e, options);\n }\n }\n\n /**\n * Synchronous variant of {@link Container.run}. Use it for purely\n * synchronous validator graphs where the microtask overhead of `await`\n * per mount matters (e.g. driving a reactive UI without a `pending`\n * flicker on every keystroke).\n *\n * Each mounted validator's return value MUST NOT be a thenable, and every\n * nested container MUST implement `runSync`. Either violation throws\n * `RunSyncViolationError` (structural — distinct from validation\n * failures), so the diagnostic is surfaced verbatim rather than wrapped\n * into a `ValidupError`. The companion {@link Container.safeRunSync}\n * still rethrows these for the same reason.\n *\n * No `parallel` variant — synchronous graphs don't benefit from\n * concurrency, and `Promise.allSettled` is async by definition.\n *\n * Aborts surface the same way as {@link Container.run}: the\n * `signal.throwIfAborted()` check between mounts throws `signal.reason`,\n * and a mid-flight validator throw during an already-aborted run is\n * re-raised verbatim. Don't assume the thrown value is always\n * `signal.reason`.\n *\n * @throws ValidupError on validation failure.\n * @throws RunSyncViolationError when a validator returns a Promise or a\n * nested container does not implement `runSync`.\n * @throws signal.reason when the abort check fires between mounts.\n * @throws (mid-flight validator error) when a validator throws during an\n * already-aborted run.\n */\n runSync(\n data: ContainerInput<T> = {},\n options: ContainerRunOptions<T, C> = {},\n ): T {\n return runTwinSync(this.runBody(data, options));\n }\n\n safeRunSync(input: ContainerInput<T> = {}, options: ContainerRunOptions<T, C> = {}): Result<T> {\n try {\n const data = this.runSync(input, options);\n return { success: true, data };\n } catch (e) {\n return this.wrapSafeRunError(e, options);\n }\n }\n\n /**\n * Resolve everything a single `(mount, expanded key)` pair needs before\n * dispatch: the split path parts, the absolute path handed to validators\n * and child containers, and the include/exclude verdict.\n *\n * Shared verbatim by the twin body and `runParallel`. The mount's input\n * `value` is deliberately NOT read here — see {@link MountKeyPlan}.\n */\n private prepareMountKey(\n item: Mount<C>,\n key: string,\n options: ContainerRunOptions<T, C>,\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n ): MountKeyPlan {\n const keyParts = key ? pathToArray(key) : [];\n\n return {\n keyParts,\n pathRelative: keyParts.at(-1),\n pathAbsolute: [\n ...(options.path ? options.path : []),\n ...keyParts,\n ],\n filter: resolvePathFilter(\n pathsToInclude,\n pathsToExclude,\n key,\n item.type === 'container',\n ),\n };\n }\n\n /**\n * Resolve the optional gate and — when it fires — what (if anything) the\n * skipped key contributes to the output.\n *\n * `optional` is the gate (\"may this mount be skipped?\"); `optionalValue` is\n * the definition of absent, resolved mount → run → container. A predicate\n * `optional` wins over the atom vocabulary entirely.\n *\n * The write directive follows the same three layers, but keys off\n * `optionalAs` **presence** rather than its value — `{ optionalAs:\n * undefined }` at any layer is a deliberate \"emit `undefined`\". Only when\n * no layer declares `optionalAs` does the mount-level `optionalInclude`\n * fallback (copy the input through) apply.\n */\n private resolveOptionalDirective(\n item: Mount<C>,\n value: unknown,\n options: ContainerRunOptions<T, C>,\n ): OptionalDirective {\n const resolvedOptionalValue = item.options.optionalValue ??\n options.optionalValue ??\n this.options.optionalValue;\n const isOptional = typeof item.options.optional === 'function' ?\n item.options.optional(value) :\n item.options.optional &&\n isOptionalValue(value, resolvedOptionalValue);\n\n if (!isOptional) {\n return { skip: false, write: false };\n }\n\n let write = true;\n let writeValue: unknown;\n if (hasOwnProperty(item.options, 'optionalAs')) {\n writeValue = item.options.optionalAs;\n } else if (hasOwnProperty(options, 'optionalAs')) {\n writeValue = options.optionalAs;\n } else if (hasOwnProperty(this.options, 'optionalAs')) {\n writeValue = this.options.optionalAs;\n } else if (item.options.optionalInclude) {\n writeValue = value;\n } else {\n write = false;\n }\n\n return {\n skip: true,\n write,\n value: writeValue,\n };\n }\n\n /**\n * Re-resolve a mount's `optional` declaration for the `meta.optional`\n * stamp applied by {@link Container.collectExecutionFailure}.\n *\n * Split out from `resolveOptionalDirective` because the two calls answer\n * different questions at different times: the directive decides whether to\n * *run* the mount, this decides whether to *tag* the mount's issues. The\n * split is what lets this one contain a throw the gate cannot.\n *\n * A predicate that throws degrades to `false` (don't tag) rather than\n * propagating. This is load-bearing, not defensive: the caller is a\n * `catch` handler with no `try` above it inside the run loop, and the very\n * throw it is folding may be the predicate's own. Re-raising here escapes\n * the error path entirely, discarding **every issue collected so far** and\n * replacing them with one path-less item — so a mainstream idiom like\n * `optional: (v) => v.trim().length === 0` would, on the first absent\n * field, wipe out every other field's validation error.\n *\n * `false` is the conservative fallback: the mount's issues surface at full\n * severity instead of being downgraded to a warning by consumers such as\n * `@validup/vue`'s `getSeverity`. The predicate's failure is not swallowed\n * — it is already being folded into an issue by the caller.\n */\n private resolveOptionalStamp(item: Mount<C>, value: unknown): boolean {\n if (typeof item.options.optional === 'function') {\n try {\n return Boolean(item.options.optional(value));\n } catch {\n return false;\n }\n }\n\n return item.options.optional === true;\n }\n\n /**\n * Attribution fallback for a throw raised before a {@link MountKeyPlan}\n * exists — path expansion, key preparation, or the mount's value read.\n *\n * Produces the same `keyParts` / `pathRelative` pair `prepareMountKey`\n * would have, so a pre-dispatch failure is attributed to the mount that\n * caused it rather than surfacing path-less. For an item-level failure\n * (path expansion) the caller passes the *unexpanded* mount path, so a\n * glob mount is identified by its literal pattern (`items.*.name`) — the\n * keys it would have expanded to are precisely what could not be computed.\n */\n private describeKey(key: string): {\n keyParts: PropertyKey[],\n pathRelative: PropertyKey | undefined,\n } {\n const keyParts: PropertyKey[] = key ? pathToArray(key) : [];\n\n return { keyParts, pathRelative: keyParts.at(-1) };\n }\n\n /**\n * Build the option bag forwarded into a nested container's `run` /\n * `runSync`. Single source of truth for what a child inherits, so a new\n * run option is threaded downward in one place instead of three.\n */\n private buildChildRunOptions(\n options: ContainerRunOptions<T, C>,\n key: string,\n plan: MountKeyPlan,\n pathsStrict: boolean,\n parallel = false,\n ): ContainerRunOptions<any, C> {\n return {\n group: options.group,\n flat: true,\n path: plan.pathAbsolute,\n pathsToInclude: plan.filter.pathsToInclude,\n pathsToExclude: plan.filter.pathsToExclude,\n // Not forwarded into keyless (`key === ''`) children: they share\n // the parent namespace and receive the filter list verbatim, so\n // strict there would throw for paths owned by the parent's own\n // sibling mounts. Keyless subtrees are a deliberate strict blind\n // spot.\n ...(pathsStrict && key.length > 0 ? { pathsStrict: true } : {}),\n defaults: resolveDefaults(options.defaults, key),\n context: options.context,\n signal: options.signal,\n cache: options.cache,\n ...(parallel ? { parallel: true } : {}),\n optionalValue: options.optionalValue,\n // Presence, not value — see `resolveOptionalDirective`. The child\n // must see the layer's intent (emit-undefined vs. not-set) verbatim.\n ...(hasOwnProperty(options, 'optionalAs') ?\n { optionalAs: options.optionalAs } : {}),\n };\n }\n\n /**\n * Build the context object handed to a mounted validator.\n */\n private buildValidatorContext(\n key: string,\n plan: MountKeyPlan,\n value: unknown,\n data: ContainerInput<T>,\n options: ContainerRunOptions<T, C>,\n ): ValidatorContext<C> {\n return {\n key,\n path: plan.pathAbsolute,\n\n value,\n data: data as Record<string, any>,\n group: options.group,\n context: options.context as C,\n signal: options.signal,\n cache: options.cache,\n };\n }\n\n /**\n * Lookup helper for the per-mount result cache.\n *\n * Returns `undefined` (forcing a real run) for any of:\n * - No `cache` supplied — caller didn't opt in.\n * - Mount isn't a validator — container mounts run their own\n * inner loop, which consults the cache for their own mounts.\n * - Validator declared `sideEffect: true` — its result depends on\n * inputs the snapshot doesn't capture (sibling fields, network,\n * global state), so caching would be unsound.\n * - No prior entry stored for this `(mount, key)` pair.\n * - Stored snapshot's `value` / `context` / `group` don't all match\n * the current invocation by `Object.is`.\n */\n private resolveCachedOutcome(\n item: Mount<C>,\n key: string,\n snapshot: ResultCacheSnapshot,\n cache: IResultCache | undefined,\n ): ResultCacheOutcome | undefined {\n if (\n !cache ||\n item.type !== 'validator' ||\n item.sideEffect === true\n ) {\n return undefined;\n }\n const entry = cache.get(item, key);\n if (!entry) {\n return undefined;\n }\n if (\n Object.is(entry.snapshot.value, snapshot.value) &&\n Object.is(entry.snapshot.context, snapshot.context) &&\n Object.is(entry.snapshot.group, snapshot.group)\n ) {\n return entry.outcome;\n }\n return undefined;\n }\n\n /**\n * Store the outcome of a fresh validator invocation. No-ops in the\n * same cases `resolveCachedOutcome` returns `undefined` for, plus:\n *\n * - `signal.aborted` — the throw was caused by cancellation, not by\n * a validation outcome we want to remember. Caching the abort\n * would mean future replays surface \"AbortError\" as a fake\n * validation issue every time the same snapshot is seen, even\n * in fully-completed runs.\n *\n * `RunSyncViolationError`s are filtered out at the call site\n * (`runSync` only) because they're structural — the validator\n * graph is wrong, not the input.\n */\n private writeCachedOutcome(\n item: Mount<C>,\n key: string,\n snapshot: ResultCacheSnapshot,\n outcome: ResultCacheOutcome,\n cache: IResultCache | undefined,\n signal: AbortSignal | undefined,\n ): void {\n if (\n !cache ||\n item.type !== 'validator' ||\n item.sideEffect === true ||\n signal?.aborted\n ) {\n return;\n }\n cache.set(item, key, { snapshot, outcome });\n }\n\n private resolveContainerFilters(options: ContainerRunOptions<T, C>): {\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n } {\n let pathsToInclude: string[] | undefined;\n if (options.pathsToInclude) {\n pathsToInclude = options.pathsToInclude as string[];\n } else if (this.options.pathsToInclude) {\n pathsToInclude = this.options.pathsToInclude as string[];\n }\n\n let pathsToExclude: string[] | undefined;\n if (options.pathsToExclude) {\n pathsToExclude = options.pathsToExclude as string[];\n } else if (this.options.pathsToExclude) {\n pathsToExclude = this.options.pathsToExclude as string[];\n }\n\n return { pathsToInclude, pathsToExclude };\n }\n\n /**\n * Resolve the effective `pathsStrict` flag. Run-level wins over\n * container-level; unset anywhere is `false` (the silent, back-compatible\n * default).\n */\n private resolvePathsStrict(options: ContainerRunOptions<T, C>): boolean {\n return options.pathsStrict ?? this.options.pathsStrict ?? false;\n }\n\n /**\n * Structural pre-flight for `pathsStrict`. Verifies every resolved\n * `pathsToInclude` / `pathsToExclude` entry is satisfied by *this*\n * container — either an exact match against an expanded mount key, or a\n * prefix descent into a container mount (whose child re-checks the\n * forwarded remainder, since `pathsStrict` threads downward). Anything\n * unmatched throws {@link PathsStrictViolationError} with absolute paths.\n *\n * No-ops unless strict is on AND at least one filter list is present, so\n * the overhead on the common (non-strict) path is a single `??` chain.\n *\n * Notes on the match rules (kept in lockstep with `resolvePathFilter`):\n * - Keyless container mounts share the parent namespace and receive the\n * filter list verbatim, so a path could be owned by the keyless child\n * OR by a keyed sibling here — the parent can't tell without recursing.\n * To avoid false positives it treats every entry as satisfied when any\n * keyless container is present, and `pathsStrict` is NOT forwarded into\n * keyless children (that would throw for parent-sibling paths). Net:\n * keyless subtrees are a strict blind spot (\"out of scope\" per the issue).\n * - Group filtering is intentionally ignored: a mount excluded from the\n * active group still exists, so a path targeting it is not \"stale\".\n * - Expansion uses the same `expandPath(data, item.path)` the run loop\n * uses, so glob mounts are matched against the keys they actually\n * expand to for the given `data`.\n */\n private assertPathsStrict(\n strict: boolean,\n data: ContainerInput<T>,\n pathsToInclude: string[] | undefined,\n pathsToExclude: string[] | undefined,\n parentPath: PropertyKey[] | undefined,\n ): void {\n if (!strict) {\n return;\n }\n const hasInclude = typeof pathsToInclude !== 'undefined' && pathsToInclude.length > 0;\n const hasExclude = typeof pathsToExclude !== 'undefined' && pathsToExclude.length > 0;\n if (!hasInclude && !hasExclude) {\n return;\n }\n\n const expanded: { keys: string[], isContainer: boolean }[] = [];\n let hasKeylessContainer = false;\n for (const item of this.items) {\n const keys: string[] = item.path ? expandPath(data, item.path) : [''];\n const itemIsContainer = item.type === 'container';\n if (itemIsContainer && keys.some((key) => key.length === 0)) {\n hasKeylessContainer = true;\n }\n expanded.push({ keys, isContainer: itemIsContainer });\n }\n\n const isSatisfied = (path: string): boolean => {\n // A keyless container forwards the whole filter list verbatim, so\n // the remainder is strict-checked inside that child — treat every\n // entry as locally satisfied to avoid a false positive here.\n if (hasKeylessContainer) {\n return true;\n }\n for (const entry of expanded) {\n for (const key of entry.keys) {\n if (key.length === 0) {\n continue;\n }\n if (path === key) {\n return true;\n }\n if (entry.isContainer && path.startsWith(`${key}.`)) {\n return true;\n }\n }\n }\n return false;\n };\n\n const toAbsolute = (path: string): string => {\n if (!parentPath || parentPath.length === 0) {\n return path;\n }\n return stringifyPath([...parentPath, ...pathToArray(path)]);\n };\n\n const unmatchedInclude = hasInclude ?\n pathsToInclude!.filter((path) => !isSatisfied(path)).map(toAbsolute) :\n [];\n const unmatchedExclude = hasExclude ?\n pathsToExclude!.filter((path) => !isSatisfied(path)).map(toAbsolute) :\n [];\n\n if (unmatchedInclude.length > 0 || unmatchedExclude.length > 0) {\n throw new PathsStrictViolationError({\n pathsToInclude: unmatchedInclude,\n pathsToExclude: unmatchedExclude,\n });\n }\n }\n\n /**\n * Prepend `keyParts` to a child issue's `path` and — when the child is\n * an `IssueGroup` — recurse into its nested issues so every leaf carries\n * the parent prefix. Without recursion, a child container that already\n * wrapped its own multi-issue mount in a group (or a `oneOf` child) would\n * surface inner items with paths missing the parent segment, breaking\n * downstream consumers that rely on `flattenIssueItems` for per-field\n * lookup (e.g. `@validup/vue`).\n */\n private prefixIssuePath(issue: Issue, keyParts: PropertyKey[]): Issue {\n const prefixed: Issue = {\n ...issue,\n path: [...keyParts, ...(issue.path || [])],\n };\n if (prefixed.type === 'group') {\n prefixed.issues = prefixed.issues.map(\n (nested) => this.prefixIssuePath(nested, keyParts),\n );\n }\n return prefixed;\n }\n\n /**\n * Translate a throw raised by one execution step (one validator or\n * nested-container invocation, from the surrounding `run` loop) into\n * accumulated issues and push them onto `context.issues`. Re-throws when\n * the run was aborted (signal-aware validators) so abort errors are not\n * mangled into validation issues.\n *\n * \"Mount\" is the *setup-time* verb (`container.mount(...)`); what failed\n * here is the *execution* of an already-mounted unit — hence the name.\n *\n * The context object captures everything the error path needs to know\n * about the failing step: the thrown value (`error`), the mount\n * descriptor (`item`), the current input (`value` — kept around so we\n * can re-evaluate predicate-optional declarations at error time), the\n * expanded path (`keyParts` — used to prepend to nested `ValidupError`\n * issues) and the trailing segment (`pathRelative` — used when wrapping\n * multi-issue or container emissions into an `IssueGroup`). The\n * destination accumulator (`issues`) and the abort `signal` round out\n * what's needed to handle the failure.\n *\n * @modifies context.issues — appends one or more entries per call.\n */\n private collectExecutionFailure(context: ExecutionFailureContext<C>): void {\n const {\n error,\n item,\n value,\n keyParts,\n pathRelative,\n issues,\n signal,\n } = context;\n\n // Cancellation and structural graph violations are not validation\n // outcomes — surface them verbatim rather than burying them under a\n // generic \"Property X is invalid\". See {@link isStructuralThrow} for\n // why each of the three legs is carved out.\n if (isStructuralThrow(error, signal)) {\n throw error;\n }\n\n // Mounts whose `optional` declaration resolves truthy for the current\n // `value` stamp their own emissions with `meta.optional: true`, so\n // consumers (e.g. `@validup/vue`'s severity helper) can downgrade UX\n // gating for fields the schema permits to be blank.\n //\n // Resolution mirrors the run-loop check (e.g. lines 254-256):\n //\n // - `optional: true` → tag\n // - `optional: false` → don't tag (matches runtime's truthy filter)\n // - `optional: (v) => boolean` → invoke the predicate with the\n // current value and tag iff it returns truthy. The run loop\n // normally only enters this error path when the predicate\n // returned false (otherwise the validator would have been\n // skipped), so this branch is usually \"don't tag\" — but the\n // explicit re-evaluation keeps the code's intent self-evident\n // and decouples it from that invariant. The one case where the\n // predicate did NOT return false is when it *threw*, which is\n // why the re-invocation is contained — see\n // {@link Container.resolveOptionalStamp}.\n // - `optional: undefined` → don't tag\n //\n // Per the \"no inheritance\" decision: issues bubbled up unchanged from\n // a child Container's own `ValidupError` are NOT stamped here — the\n // child's own per-mount tagging is authoritative, and a leaf inside a\n // required-on-its-own-mount field stays unmarked even if its parent\n // mount was optional. This matches the \"if you DO provide a role, the\n // role's required fields are still required\" semantics.\n const isOptionalMount = this.resolveOptionalStamp(item, value);\n // Shallow stamp — only the top-level `issue.meta`. Used for the\n // wrapping `IssueGroup` we emit for container mounts (Option B: do\n // not propagate the parent's optional flag onto the bubbled-up child\n // leaves, which retain their own per-mount tagging) and for leaves\n // we construct directly via `defineIssueItem`.\n //\n // We reassign `issue.meta` to a FRESH object rather than mutating\n // the existing one. The top-level `issue` is always safe to mutate\n // here (it's a fresh object from `prefixIssuePath`'s shallow spread\n // or one of the `defineIssue*` factories), but the inner `meta`\n // object can be shared with the validator's original\n // `ValidupError.issues[i].meta` — mutating in place would leak\n // `optional: true` back into the validator's own (possibly cached\n // or replayed) error.\n const markOptional = <I extends Issue>(issue: I): I => {\n if (!isOptionalMount) {\n return issue;\n }\n issue.meta = { ...(issue.meta ?? {}), optional: true };\n return issue;\n };\n\n // Deep stamp — recurse into `IssueGroup.issues`. Used ONLY when the\n // whole tree was produced by *this* validator (e.g. an integration\n // adapter that threw `ValidupError([defineIssueGroup({ issues: [...] })])`).\n // Without this, `flattenIssueItems` would pull out the inner leaves\n // and miss `meta.optional` on them. Not used for container mounts —\n // see Option B above.\n const markOptionalDeep = <I extends Issue>(issue: I): I => {\n if (!isOptionalMount) {\n return issue;\n }\n markOptional(issue);\n if (issue.type === 'group') {\n issue.issues = issue.issues.map((nested) => markOptionalDeep(nested));\n }\n return issue;\n };\n\n const childIssues: Issue[] = [];\n\n if (isValidupError(error)) {\n for (let i = 0; i < error.issues.length; i++) {\n const prefixed = this.prefixIssuePath(error.issues[i], keyParts);\n // Stamp only when a *validator* threw `ValidupError` directly\n // (e.g. an integration adapter like `@validup/zod` reshaping\n // a foreign error into validup issues). Deep so that a\n // validator returning a nested `IssueGroup` tags leaves too.\n // For child Container runs, leave the bubbled tree alone —\n // see comment above.\n childIssues.push(item.type === 'validator' ? markOptionalDeep(prefixed) : prefixed);\n }\n } else if (isError(error)) {\n childIssues.push(markOptional(defineIssueItem({\n path: keyParts,\n message: error.message,\n })));\n } else {\n // Non-`Error` throw (string, plain object, null, …). Without a\n // synthetic issue here, the run would still flag the mount as\n // failed but the resulting `ValidupError.issues` would not\n // mention the throw at all — caller sees \"validation failed\"\n // with no diagnostic. Surface the stringified value so the\n // failure is at least traceable.\n childIssues.push(markOptional(defineIssueItem({\n path: keyParts,\n message: typeof error === 'string' && error.length > 0 ? error : `Non-Error throw: ${String(error)}`,\n })));\n }\n\n if (pathRelative) {\n if (item.type === 'container' || childIssues.length > 1) {\n // The wrapping group is itself an emission of *this* mount —\n // stamp it (shallow) so a tree-walking consumer can read the\n // optional signal at the group level. The leaves inside\n // follow the \"no inheritance\" rule and stay untouched for\n // container mounts; for multi-leaf validator mounts, the\n // leaves were already stamped above.\n issues.push(markOptional(defineIssueGroup({\n message: buildErrorMessageForAttribute(String(pathRelative)),\n data: { name: String(pathRelative) },\n path: keyParts,\n issues: childIssues,\n })));\n } else {\n issues.push(...childIssues);\n }\n } else {\n issues.push(...childIssues);\n }\n }\n\n /**\n * For `oneOf` containers, wrap the issues produced by a single branch\n * (slice from `branchStart` to the end of `issues`) into one sub-group\n * so per-branch identity is preserved in the final aggregate. Non-oneOf\n * containers leave the issue list untouched — they don't need branch\n * partitioning.\n *\n * The wrapping group's `path` is `[]` (the branch wraps everything\n * inside it; per-leaf paths are unchanged); `data.branch` is the\n * mount index; and `data.name` (when set) is the mount path so\n * consumers can label \"branch X failed\" without recomputing the\n * registration order.\n */\n private wrapBranchForOneOf(\n issues: Issue[],\n branchStart: number,\n item: Mount<C>,\n branchIndex: number,\n ): void {\n if (!this.options.oneOf) {\n return;\n }\n const branchIssues = issues.splice(branchStart);\n const data: Record<string, unknown> = { branch: branchIndex };\n if (item.path) {\n data.name = item.path;\n }\n issues.push(defineIssueGroup({\n message: item.path ?\n `Branch \"${item.path}\" failed` :\n `Branch ${branchIndex} failed`,\n data,\n path: [],\n issues: branchIssues,\n }));\n }\n\n /**\n * Apply post-loop semantics: oneOf aggregation, error throw, defaults\n * fill, and flat-vs-nested output expansion.\n */\n private finalizeOutput(\n output: Record<string, any>,\n options: ContainerRunOptions<T, C>,\n issues: Issue[],\n errorCount: number,\n itemCount: number,\n ): T {\n if (this.options.oneOf) {\n // Guard against the \"all branches filtered out\" case (group /\n // pathsToInclude / pathsToExclude can leave itemCount === 0).\n // Without it, a oneOf container with nothing to run would throw\n // ONE_OF_FAILED with an empty issues list. Shared\n // `buildOneOfFailedGroup` keeps the ONE_OF_FAILED shape in\n // lockstep with compose's any-of path so consumers / i18n\n // catalogs only format one variant.\n if (itemCount > 0 && errorCount === itemCount) {\n throw new ValidupError([buildOneOfFailedGroup(issues, { path: options.path ? options.path : [] })]);\n }\n } else if (errorCount > 0) {\n throw new ValidupError(issues);\n }\n\n if (options.defaults) {\n const defaultKeys = Object.keys(options.defaults);\n for (const defaultKey of defaultKeys) {\n if (\n !hasOwnProperty(output, defaultKey) ||\n typeof output[defaultKey] === 'undefined'\n ) {\n output[defaultKey] = (options.defaults as Record<string, any>)[defaultKey];\n }\n }\n }\n\n if (options.flat) {\n return output as T;\n }\n\n const temp: Record<string, any> = {};\n const keys = Object.keys(output);\n for (const key of keys) {\n setPathValue(temp, key, output[key]);\n }\n return temp as T;\n }\n\n private wrapSafeRunError(e: unknown, options: ContainerRunOptions<T, C>): Result<T> {\n // Cancellation and structural graph violations propagate instead of\n // being reshaped into a path-less `Result.failure` — the exact same\n // decision `collectExecutionFailure` makes. See\n // {@link isStructuralThrow} for the per-leg rationale.\n if (isStructuralThrow(e, options.signal)) {\n throw e;\n }\n\n // Identity passthrough — deliberately NOT routed through\n // `errorToIssues`. That helper spreads `issues` into a plain array,\n // and rebuilding a `ValidupError` around it would drop the subclass,\n // `cause`, and any custom property the thrower attached. `safeRun`\n // hands back the exact object `run` would have thrown.\n if (isValidupError(e)) {\n return { success: false, error: e };\n }\n\n // Everything else — an `Error`, or a raw `throw` of a string / plain\n // object / `null` — folds through the shared cascade at its defaults\n // (`code: VALUE_INVALID`, `path: []`), which reproduces every issue\n // *value* this site built by hand before, including the verbatim\n // non-empty-string case. One thing did change: `errorToIssues` passes\n // `code` inside the `defineIssueItem` payload rather than letting the\n // factory append it, so the key insertion order is now\n // `type, path, code, message` where this site emitted\n // `type, path, message, code`. Deep-equality is unaffected;\n // `JSON.stringify` bytes are not. That aligns this site with compose's\n // fold sites and leaves `collectExecutionFailure` — which still builds\n // its items by hand — as the odd one out.\n //\n // `path` is empty because the throw escaped the run loop before any\n // mount key was resolved; a *mounted* unit's failure never arrives\n // here (`collectExecutionFailure` folds that one, with the mount path\n // attached — though see its own note: a keyless mount also yields\n // `path: []`).\n //\n // The fold is not defensive-only: reaching it needs no `Container`\n // subclass. The per-mount value read sits outside the per-mount\n // `try`, so a throwing accessor or Proxy trap on the input lands\n // here — see `test/unit/safe-run-error.spec.ts`, which pins every\n // branch including the \"non-empty string throw stays verbatim\" case\n // and the never-empty `issues` guarantee.\n return { success: false, error: new ValidupError(errorToIssues(e)) };\n }\n\n private isItemGroupIncluded(\n item: Mount<C>,\n group?: string,\n ) : boolean {\n if (group === GroupKey.WILDCARD) {\n return true;\n }\n\n if (item.options.group) {\n if (Array.isArray(item.options.group)) {\n if (item.options.group.includes(GroupKey.WILDCARD)) {\n return true;\n }\n\n if (group && item.options.group.includes(group)) {\n return true;\n }\n } else {\n if (item.options.group === GroupKey.WILDCARD) {\n return true;\n }\n\n if (item.options.group === group) {\n return true;\n }\n }\n\n return false;\n }\n\n return true;\n }\n\n /**\n * Join flat-output keys with `.` separators, preserving any pre-existing\n * leading dot on the right-hand side. Note: keys containing a *literal*\n * dot collide with the dotted-path syntax used for nested-output\n * expansion (see `setPathValue` in `pathtrace`) and will produce\n * ambiguous output when re-expanded — avoid mounting/returning such keys.\n */\n private mergePaths(...args: (string | undefined)[]) {\n let output : string = '';\n\n for (const arg of args) {\n if (!arg || arg.length === 0) {\n continue;\n }\n\n if (arg.at(0) === '.') {\n output += arg;\n } else {\n output += output.length > 0 ? `.${arg}` : arg;\n }\n }\n\n return output;\n }\n\n protected initialize() : void {\n\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { Container, isContainer } from '../container';\nimport type {\n ContainerOptions,\n IContainer,\n MountOptions,\n} from '../container/types';\nimport type { IBuilder, MountTarget } from './types';\nimport type { Validator } from '../validator';\n\ntype ValidatorStep<C> = {\n kind: 'validator',\n key: string,\n validator: Validator<C>,\n options: MountOptions,\n};\n\ntype NestStep<C> = {\n kind: 'nest',\n key: string,\n child: IContainer<any, C>,\n options: MountOptions,\n};\n\ntype Step<C> = ValidatorStep<C> | NestStep<C>;\n\nfunction isBuilder(value: unknown): value is IBuilder<Record<string, any>, unknown> {\n return typeof value === 'object' &&\n value !== null &&\n typeof (value as { build?: unknown }).build === 'function' &&\n typeof (value as { mount?: unknown }).mount === 'function';\n}\n\nexport class Builder<T extends Record<string, any>, C> implements IBuilder<T, C> {\n private readonly options: ContainerOptions<any>;\n\n private readonly steps: ReadonlyArray<Step<C>>;\n\n constructor(options: ContainerOptions<any>, steps: ReadonlyArray<Step<C>>) {\n this.options = options;\n this.steps = steps;\n }\n\n mount(key: string, ...rest: unknown[]): IBuilder<any, C> {\n let options: MountOptions = {};\n let target: MountTarget<C>;\n\n if (rest.length === 1) {\n target = rest[0] as MountTarget<C>;\n } else {\n options = rest[0] as MountOptions;\n target = rest[1] as MountTarget<C>;\n }\n\n let step: Step<C>;\n if (isBuilder(target)) {\n step = {\n kind: 'nest',\n key,\n child: (target as IBuilder<any, C>).build(),\n options,\n };\n } else if (isContainer(target)) {\n step = {\n kind: 'nest',\n key,\n child: target as IContainer<any, C>,\n options,\n };\n } else {\n step = {\n kind: 'validator',\n key,\n validator: target as Validator<C>,\n options,\n };\n }\n\n return new Builder<any, C>(this.options, [...this.steps, step]);\n }\n\n oneOf(): IBuilder<T, C> {\n return new Builder<T, C>(\n { ...this.options, oneOf: true },\n this.steps,\n );\n }\n\n pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C> {\n return new Builder<T, C>(\n {\n ...this.options,\n pathsToInclude: [\n ...((this.options.pathsToInclude as string[]) ?? []),\n ...paths,\n ] as ContainerOptions<any>['pathsToInclude'],\n },\n this.steps,\n );\n }\n\n pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C> {\n return new Builder<T, C>(\n {\n ...this.options,\n pathsToExclude: [\n ...((this.options.pathsToExclude as string[]) ?? []),\n ...paths,\n ] as ContainerOptions<any>['pathsToExclude'],\n },\n this.steps,\n );\n }\n\n pathsStrict(strict = true): IBuilder<T, C> {\n return new Builder<T, C>(\n { ...this.options, pathsStrict: strict },\n this.steps,\n );\n }\n\n build(): Container<T, C> {\n const container = new Container<T, C>(this.options as ContainerOptions<T>);\n for (const step of this.steps) {\n if (step.kind === 'nest') {\n container.mount(step.key, step.options, step.child);\n } else {\n container.mount(step.key, step.options, step.validator);\n }\n }\n return container;\n }\n}\n\n/**\n * Entry point for the compile-time-typed schema builder. The accumulator\n * starts at `{}` and grows as `.mount(...)` calls are chained;\n * `.build()` returns a `Container<T, C>` whose `run()` reflects the\n * accumulated shape.\n *\n * Pass the context type as the generic parameter to flow it through nested\n * builders and validator factories: `defineSchema<MyContext>()`.\n */\nexport function defineSchema<C = unknown>(): IBuilder<{}, C> {\n return new Builder<{}, C>({}, []);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IResultCache } from './types';\nimport { isObject } from '../utils';\n\n/**\n * Duck-typed guard for {@link IResultCache}. Avoids `instanceof`\n * checks so caches constructed from a different copy of the package\n * (workspaces with duplicated `validup` installs, adapter bundles)\n * still round-trip cleanly.\n */\nexport function isResultCache(input: unknown): input is IResultCache {\n if (!isObject(input)) {\n return false;\n }\n\n return (\n typeof input.get === 'function' &&\n typeof input.set === 'function' &&\n typeof input.delete === 'function' &&\n typeof input.clear === 'function'\n );\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IResultCache, ResultCacheEntry } from './types';\n\n/**\n * Default in-memory {@link IResultCache} implementation.\n *\n * Backed by a two-level `Map`:\n * - outer key — Mount reference (opaque object)\n * - inner key — expanded path (string)\n *\n * `Map` is used for both levels (rather than a `WeakMap` on the outer)\n * so `clear()` is supported. Cache entries become unreachable when the\n * owning composable / caller drops its reference to the\n * `ResultCache` instance; in the typical `@validup/vue` flow that\n * happens on `onScopeDispose`, which lines up with component unmount.\n *\n * Snapshot equality (the \"is this still valid?\" check) is the run\n * loop's job — see `container/module.ts`. This class is dumb storage.\n */\nexport class ResultCache implements IResultCache {\n private store: Map<object, Map<string, ResultCacheEntry>>;\n\n constructor() {\n this.store = new Map();\n }\n\n get(mount: object, key: string): ResultCacheEntry | undefined {\n return this.store.get(mount)?.get(key);\n }\n\n set(mount: object, key: string, entry: ResultCacheEntry): void {\n let inner = this.store.get(mount);\n if (!inner) {\n inner = new Map();\n this.store.set(mount, inner);\n }\n inner.set(key, entry);\n }\n\n delete(mount: object, key?: string): void {\n if (typeof key === 'undefined') {\n this.store.delete(mount);\n return;\n }\n const inner = this.store.get(mount);\n if (!inner) {\n return;\n }\n inner.delete(key);\n if (inner.size === 0) {\n this.store.delete(mount);\n }\n }\n\n clear(): void {\n this.store.clear();\n }\n}\n"],"mappings":";;;;;AAOA,SAAgB,eAAoD,KAAQ,MAAwC;CAChH,OAAO,OAAO,UAAU,eAAe,KAAK,KAAK,IAAI;AACzD;;;ACFA,SAAgB,SAAS,OAA+C;CACpE,OAAO,CAAC,CAAC,SACL,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK;AAC5B;;;ACDA,SAAgB,YAAY,OAAsC;CAC9D,OAAO,SAAS,KAAK,KACjB,OAAO,MAAM,QAAQ,cACrB,OAAO,MAAM,YAAY;AACjC;;;;;;;;;;;;;;;;;;;;;ACgBA,IAAa,4BAAb,cAA+C,MAAM;CACjD,OAAyB;;CAGzB;;CAGA;CAEA,YAAY,OAAkC;EAC1C,MAAM,iBAAiB,MAAM,kBAAkB,CAAC;EAChD,MAAM,iBAAiB,MAAM,kBAAkB,CAAC;EAEhD,MAAM,QAAkB,CAAC;EACzB,IAAI,eAAe,SAAS,GACxB,MAAM,KAAK,oCAAoC,eAAe,KAAK,IAAI,GAAG;EAE9E,IAAI,eAAe,SAAS,GACxB,M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