claude-crap 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../node_modules/ajv/lib/compile/codegen/code.ts", "../../node_modules/ajv/lib/compile/codegen/scope.ts", "../../node_modules/ajv/lib/compile/codegen/index.ts", "../../node_modules/ajv/lib/compile/util.ts", "../../node_modules/ajv/lib/compile/names.ts", "../../node_modules/ajv/lib/compile/errors.ts", "../../node_modules/ajv/lib/compile/validate/boolSchema.ts", "../../node_modules/ajv/lib/compile/rules.ts", "../../node_modules/ajv/lib/compile/validate/applicability.ts", "../../node_modules/ajv/lib/compile/validate/dataType.ts", "../../node_modules/ajv/lib/compile/validate/defaults.ts", "../../node_modules/ajv/lib/vocabularies/code.ts", "../../node_modules/ajv/lib/compile/validate/keyword.ts", "../../node_modules/ajv/lib/compile/validate/subschema.ts", "../../node_modules/fast-deep-equal/index.js", "../../node_modules/json-schema-traverse/index.js", "../../node_modules/ajv/lib/compile/resolve.ts", "../../node_modules/ajv/lib/compile/validate/index.ts", "../../node_modules/ajv/lib/runtime/validation_error.ts", "../../node_modules/ajv/lib/compile/ref_error.ts", "../../node_modules/ajv/lib/compile/index.ts", "../../node_modules/ajv/dist/refs/data.json", "../../node_modules/fast-uri/lib/utils.js", "../../node_modules/fast-uri/lib/schemes.js", "../../node_modules/fast-uri/index.js", "../../node_modules/ajv/lib/runtime/uri.ts", "../../node_modules/ajv/lib/core.ts", "../../node_modules/ajv/lib/vocabularies/core/id.ts", "../../node_modules/ajv/lib/vocabularies/core/ref.ts", "../../node_modules/ajv/lib/vocabularies/core/index.ts", "../../node_modules/ajv/lib/vocabularies/validation/limitNumber.ts", "../../node_modules/ajv/lib/vocabularies/validation/multipleOf.ts", "../../node_modules/ajv/lib/runtime/ucs2length.ts", "../../node_modules/ajv/lib/vocabularies/validation/limitLength.ts", "../../node_modules/ajv/lib/vocabularies/validation/pattern.ts", "../../node_modules/ajv/lib/vocabularies/validation/limitProperties.ts", "../../node_modules/ajv/lib/vocabularies/validation/required.ts", "../../node_modules/ajv/lib/vocabularies/validation/limitItems.ts", "../../node_modules/ajv/lib/runtime/equal.ts", "../../node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts", "../../node_modules/ajv/lib/vocabularies/validation/const.ts", "../../node_modules/ajv/lib/vocabularies/validation/enum.ts", "../../node_modules/ajv/lib/vocabularies/validation/index.ts", "../../node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts", "../../node_modules/ajv/lib/vocabularies/applicator/items.ts", "../../node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts", "../../node_modules/ajv/lib/vocabularies/applicator/items2020.ts", "../../node_modules/ajv/lib/vocabularies/applicator/contains.ts", "../../node_modules/ajv/lib/vocabularies/applicator/dependencies.ts", "../../node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts", "../../node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts", "../../node_modules/ajv/lib/vocabularies/applicator/properties.ts", "../../node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts", "../../node_modules/ajv/lib/vocabularies/applicator/not.ts", "../../node_modules/ajv/lib/vocabularies/applicator/anyOf.ts", "../../node_modules/ajv/lib/vocabularies/applicator/oneOf.ts", "../../node_modules/ajv/lib/vocabularies/applicator/allOf.ts", "../../node_modules/ajv/lib/vocabularies/applicator/if.ts", "../../node_modules/ajv/lib/vocabularies/applicator/thenElse.ts", "../../node_modules/ajv/lib/vocabularies/applicator/index.ts", "../../node_modules/ajv/lib/vocabularies/format/format.ts", "../../node_modules/ajv/lib/vocabularies/format/index.ts", "../../node_modules/ajv/lib/vocabularies/metadata.ts", "../../node_modules/ajv/lib/vocabularies/draft7.ts", "../../node_modules/ajv/lib/vocabularies/discriminator/types.ts", "../../node_modules/ajv/lib/vocabularies/discriminator/index.ts", "../../node_modules/ajv/dist/refs/json-schema-draft-07.json", "../../node_modules/ajv/lib/ajv.ts", "../../src/index.ts", "../../src/adapters/common.ts", "../../src/adapters/semgrep.ts", "../../src/adapters/eslint.ts", "../../src/adapters/bandit.ts", "../../src/adapters/stryker.ts", "../../src/adapters/dart-analyzer.ts", "../../src/adapters/dotnet-format.ts", "../../src/adapters/index.ts", "../../src/ast/tree-sitter-engine.ts", "../../src/ast/cyclomatic.ts", "../../src/ast/language-config.ts", "../../src/config.ts", "../../src/dashboard/server.ts", "../../src/shared/exclusions.ts", "../../src/metrics/tdr.ts", "../../src/metrics/score.ts", "../../src/dashboard/file-detail.ts", "../../src/workspace-guard.ts", "../../src/metrics/crap.ts", "../../src/metrics/workspace-walker.ts", "../../src/sarif/sarif-store.ts", "../../src/sarif/sarif-builder.ts", "../../src/sarif/sarif-validator.ts", "../../src/crap-config.ts", "../../src/tools/test-harness.ts", "../../src/scanner/auto-scan.ts", "../../src/scanner/detector.ts", "../../src/scanner/runner.ts", "../../src/scanner/bootstrap.ts", "../../src/scanner/complexity-scanner.ts", "../../src/monorepo/project-map.ts", "../../src/schemas/tool-schemas.ts"],
4
- "sourcesContent": ["// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record<string, number | undefined>\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n", "import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set<string>\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record<string, ValueReference[] | undefined>\n\ntype ScopeValues = {\n [Prefix in string]?: Map<unknown, ValueScopeName>\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set<ValueScopeName>\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set<string>\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n", "import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private rhs?: SafeExpr\n ) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(\n readonly lhs: Code,\n public rhs: SafeExpr,\n private readonly sideEffects?: boolean\n ) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(\n lhs: Code,\n private readonly op: Code,\n rhs: SafeExpr,\n sideEffects?: boolean\n ) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(\n private condition: Code | boolean,\n nodes?: ChildNode[]\n ) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(\n public name: Name,\n public args: Code,\n public async?: boolean\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record<string, SafeExpr | undefined>\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not<T extends Code | SafeExpr>(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n", "import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem<T>(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc<T extends SomeEvaluated> = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude<T, true> | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs<T extends SomeEvaluated> {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude<T, true>) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated<T extends SomeEvaluated>({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc<EvaluatedProperties>\n items: MergeEvaluatedFunc<EvaluatedItems>\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n", "import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n", "import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n", "import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n", "import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = (typeof _jsonTypes)[number]\n\nconst jsonTypes: Set<string> = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n", "import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n", "import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set<JSONType> = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n", "import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n", "import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n", "import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n", "import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set<string>\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set<string>()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n", "'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n", "import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponent} from \"fast-uri\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponent): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set<string> = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let innerBaseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") innerBaseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = innerBaseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n", "import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n", "import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial<ErrorObject>[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial<ErrorObject>[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n", "import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n", "import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport {URIComponent} from \"fast-uri\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set<string> // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set<string>(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URIComponent,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n", "{\n \"$id\": \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n \"description\": \"Meta-schema for $data reference (JSON AnySchema extension proposal)\",\n \"type\": \"object\",\n \"required\": [\"$data\"],\n \"properties\": {\n \"$data\": {\n \"type\": \"string\",\n \"anyOf\": [{\"format\": \"relative-json-pointer\"}, {\"format\": \"json-pointer\"}]\n }\n },\n \"additionalProperties\": false\n}\n", "'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$/u)\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n let acc = ''\n let code = 0\n let i = 0\n\n for (i = 0; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (code === 48) {\n continue\n }\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n break\n }\n\n for (i += 1; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n }\n return acc\n}\n\n/**\n * @typedef {Object} GetIPV6Result\n * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.\n * @property {string} address - The parsed IPv6 address.\n * @property {string} [zone] - The zone identifier, if present.\n */\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {Array<string>} buffer\n * @returns {boolean}\n */\nfunction consumeIsZone (buffer) {\n buffer.length = 0\n return true\n}\n\n/**\n * @param {Array<string>} buffer\n * @param {Array<string>} address\n * @param {GetIPV6Result} output\n * @returns {boolean}\n */\nfunction consumeHextets (buffer, address, output) {\n if (buffer.length) {\n const hex = stringArrayToHexStripped(buffer)\n if (hex !== '') {\n address.push(hex)\n } else {\n output.error = true\n return false\n }\n buffer.length = 0\n }\n return true\n}\n\n/**\n * @param {string} input\n * @returns {GetIPV6Result}\n */\nfunction getIPV6 (input) {\n let tokenCount = 0\n const output = { error: false, address: '', zone: '' }\n /** @type {Array<string>} */\n const address = []\n /** @type {Array<string>} */\n const buffer = []\n let endipv6Encountered = false\n let endIpv6 = false\n\n let consume = consumeHextets\n\n for (let i = 0; i < input.length; i++) {\n const cursor = input[i]\n if (cursor === '[' || cursor === ']') { continue }\n if (cursor === ':') {\n if (endipv6Encountered === true) {\n endIpv6 = true\n }\n if (!consume(buffer, address, output)) { break }\n if (++tokenCount > 7) {\n // not valid\n output.error = true\n break\n }\n if (i > 0 && input[i - 1] === ':') {\n endipv6Encountered = true\n }\n address.push(':')\n continue\n } else if (cursor === '%') {\n if (!consume(buffer, address, output)) { break }\n // switch to zone detection\n consume = consumeIsZone\n } else {\n buffer.push(cursor)\n continue\n }\n }\n if (buffer.length) {\n if (consume === consumeIsZone) {\n output.zone = buffer.join('')\n } else if (endIpv6) {\n address.push(buffer.join(''))\n } else {\n address.push(stringArrayToHexStripped(buffer))\n }\n }\n output.address = address.join('')\n return output\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n */\n\n/**\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n const ipv6 = getIPV6(host)\n\n if (!ipv6.error) {\n let newHost = ipv6.address\n let escapedHost = ipv6.address\n if (ipv6.zone) {\n newHost += '%' + ipv6.zone\n escapedHost += '%25' + ipv6.zone\n }\n return { host: newHost, isIPV6: true, escapedHost }\n } else {\n return { host, isIPV6: false }\n }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n let input = path\n const output = []\n let nextSlash = -1\n let len = 0\n\n // eslint-disable-next-line no-cond-assign\n while (len = input.length) {\n if (len === 1) {\n if (input === '.') {\n break\n } else if (input === '/') {\n output.push('/')\n break\n } else {\n output.push(input)\n break\n }\n } else if (len === 2) {\n if (input[0] === '.') {\n if (input[1] === '.') {\n break\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.' || input[1] === '/') {\n output.push('/')\n break\n }\n }\n } else if (len === 3) {\n if (input === '/..') {\n if (output.length !== 0) {\n output.pop()\n }\n output.push('/')\n break\n }\n }\n if (input[0] === '.') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(3)\n continue\n }\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(2)\n continue\n } else if (input[2] === '.') {\n if (input[3] === '/') {\n input = input.slice(3)\n if (output.length !== 0) {\n output.pop()\n }\n continue\n }\n }\n }\n }\n\n // Rule 2E: Move normal path segment to output\n if ((nextSlash = input.indexOf('/', 1)) === -1) {\n output.push(input)\n break\n } else {\n output.push(input.slice(0, nextSlash))\n input = input.slice(nextSlash)\n }\n }\n\n return output.join('')\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @param {boolean} esc\n * @returns {import('../types/index').URIComponent}\n */\nfunction normalizeComponentEncoding (component, esc) {\n const func = esc !== true ? escape : unescape\n if (component.scheme !== undefined) {\n component.scheme = func(component.scheme)\n }\n if (component.userinfo !== undefined) {\n component.userinfo = func(component.userinfo)\n }\n if (component.host !== undefined) {\n component.host = func(component.host)\n }\n if (component.path !== undefined) {\n component.path = func(component.path)\n }\n if (component.query !== undefined) {\n component.query = func(component.query)\n }\n if (component.fragment !== undefined) {\n component.fragment = func(component.fragment)\n }\n return component\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n const uriTokens = []\n\n if (component.userinfo !== undefined) {\n uriTokens.push(component.userinfo)\n uriTokens.push('@')\n }\n\n if (component.host !== undefined) {\n let host = unescape(component.host)\n if (!isIPv4(host)) {\n const ipV6res = normalizeIPv6(host)\n if (ipV6res.isIPV6 === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = component.host\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof component.port === 'number' || typeof component.port === 'string') {\n uriTokens.push(':')\n uriTokens.push(String(component.port))\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n nonSimpleDomain,\n recomposeAuthority,\n normalizeComponentEncoding,\n removeDotSegments,\n isIPv4,\n isUUID,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n", "'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n 'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n if (wsComponent.secure === true) {\n return true\n } else if (wsComponent.secure === false) {\n return false\n } else if (wsComponent.scheme) {\n return (\n wsComponent.scheme.length === 3 &&\n (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n )\n } else {\n return false\n }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n if (!component.host) {\n component.error = component.error || 'HTTP URIs must have a host.'\n }\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n const secure = String(component.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (component.port === (secure ? 443 : 80) || component.port === '') {\n component.port = undefined\n }\n\n // normalize the empty path\n if (!component.path) {\n component.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n wsComponent.secure = wsIsSecure(wsComponent)\n\n // construct resouce name\n wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n wsComponent.path = undefined\n wsComponent.query = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n wsComponent.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponent.secure === 'boolean') {\n wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n wsComponent.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponent.resourceName) {\n const [path, query] = wsComponent.resourceName.split('?')\n wsComponent.path = (path && path !== '/' ? path : undefined)\n wsComponent.query = query\n wsComponent.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponent.fragment = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n if (!urnComponent.path) {\n urnComponent.error = 'URN can not be parsed'\n return urnComponent\n }\n const matches = urnComponent.path.match(URN_REG)\n if (matches) {\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n urnComponent.nid = matches[1].toLowerCase()\n urnComponent.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n urnComponent.path = undefined\n\n if (schemeHandler) {\n urnComponent = schemeHandler.parse(urnComponent, options)\n }\n } else {\n urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n }\n\n return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n if (urnComponent.nid === undefined) {\n throw new Error('URN without nid cannot be serialized')\n }\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n const nid = urnComponent.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n\n if (schemeHandler) {\n urnComponent = schemeHandler.serialize(urnComponent, options)\n }\n\n const uriComponent = urnComponent\n const nss = urnComponent.nss\n uriComponent.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n const uuidComponent = urnComponent\n uuidComponent.uuid = uuidComponent.nss\n uuidComponent.nss = undefined\n\n if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n }\n\n return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n const urnComponent = uuidComponent\n // normalize UUID\n urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n return (\n scheme && (\n SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n ) ||\n undefined\n}\n\nmodule.exports = {\n wsIsSecure,\n SCHEMES,\n isValidSchemeName,\n getSchemeHandler,\n}\n", "'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = /** @type {T} */ (serialize(parse(uri, options), options))\n } else if (typeof uri === 'object') {\n uri = /** @type {T} */ (parse(serialize(uri, options), options))\n }\n return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n schemelessOptions.skipEscape = true\n return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n /** @type {import('./types/index').URIComponent} */\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base component\n relative = parse(serialize(relative, options), options) // normalize relative component\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path[0] === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n if (typeof uriA === 'string') {\n uriA = unescape(uriA)\n uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })\n } else if (typeof uriA === 'object') {\n uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })\n }\n\n if (typeof uriB === 'string') {\n uriB = unescape(uriB)\n uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })\n } else if (typeof uriB === 'object') {\n uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })\n }\n\n return uriA.toLowerCase() === uriB.toLowerCase()\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n const component = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n if (component.path !== undefined) {\n if (!options.skipEscape) {\n component.path = escape(component.path)\n\n if (component.scheme !== undefined) {\n component.path = component.path.split('%3A').join(':')\n }\n } else {\n component.path = unescape(component.path)\n }\n }\n\n if (options.reference !== 'suffix' && component.scheme) {\n uriTokens.push(component.scheme, ':')\n }\n\n const authority = recomposeAuthority(component)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (component.path && component.path[0] !== '/') {\n uriTokens.push('/')\n }\n }\n if (component.path !== undefined) {\n let s = component.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n if (\n authority === undefined &&\n s[0] === '/' &&\n s[1] === '/'\n ) {\n // don't allow the path to start with \"//\"\n s = '/%2F' + s.slice(2)\n }\n\n uriTokens.push(s)\n }\n\n if (component.query !== undefined) {\n uriTokens.push('?', component.query)\n }\n\n if (component.fragment !== undefined) {\n uriTokens.push('#', component.fragment)\n }\n return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n const options = Object.assign({}, opts)\n /** @type {import('./types/index').URIComponent} */\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n\n let isIP = false\n if (options.reference === 'suffix') {\n if (options.scheme) {\n uri = options.scheme + ':' + uri\n } else {\n uri = '//' + uri\n }\n }\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n if (parsed.host) {\n const ipv4result = isIPv4(parsed.host)\n if (ipv4result === false) {\n const ipv6result = normalizeIPv6(parsed.host)\n parsed.host = ipv6result.host.toLowerCase()\n isIP = ipv6result.isIPV6\n } else {\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n // check if scheme can't handle IRIs\n if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n // if host component is a domain name\n if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n // convert Unicode IDN -> ASCII IDN\n try {\n parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n }\n }\n // convert IRI -> URI\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (uri.indexOf('%') !== -1) {\n if (parsed.scheme !== undefined) {\n parsed.scheme = unescape(parsed.scheme)\n }\n if (parsed.host !== undefined) {\n parsed.host = unescape(parsed.host)\n }\n }\n if (parsed.path) {\n parsed.path = escape(unescape(parsed.path))\n }\n if (parsed.fragment) {\n parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return parsed\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponent,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n", "import * as uri from \"fast-uri\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n", "export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin<Opts> {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n specialNumbers?: \"fast\" | \"null\" // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise<AnySchemaObject>\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo<RemovedOptions> = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo<DeprecatedOptions> = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable<Options[K]>\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = {}\n readonly RULES: ValidationRules\n readonly _compilations: Set<SchemaEnv> = new Set()\n private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}\n private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>\n validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n validate<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n data: unknown\n ): data is JTDDataType<T>\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>\n validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>\n validate<T>(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data: unknown | T // to be validated\n ): boolean | Promise<T> {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema<T>(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile<T>(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compile<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n _meta?: boolean\n ): ValidateFunction<JTDDataType<T>>\n compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync<T = unknown>(\n schema: SchemaObject | JSONSchemaType<T>,\n _meta?: boolean\n ): Promise<ValidateFunction<T>>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>\n compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>>\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise<AnyValidateFunction> {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial<Logger> | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n", "import type {CodeKeywordDefinition} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID')\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n", "import type {Vocabulary} from \"../../types\"\nimport idKeyword from \"./id\"\nimport refKeyword from \"./ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n {keyword: \"$comment\"},\n \"definitions\",\n idKeyword,\n refKeyword,\n]\n\nexport default core\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators, Code} from \"../../compile/codegen\"\n\nconst ops = operators\n\ntype Kwd = \"maximum\" | \"minimum\" | \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n maximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n minimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n exclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n exclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitNumberError = ErrorObject<\n Kwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n", "// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {useFunc} from \"../../compile/util\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n if ($data) {\n const {regExp} = it.opts.code\n const regExpCode = regExp.code === \"new RegExp\" ? _`new RegExp` : useFunc(gen, regExp)\n const valid = gen.let(\"valid\")\n gen.try(\n () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),\n () => gen.assign(valid, false)\n )\n cxt.fail$data(_`!${valid}`)\n } else {\n const regExp = usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n", "import type {ErrorObject, Vocabulary} from \"../../types\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport multipleOf, {MultipleOfError} from \"./multipleOf\"\nimport limitLength from \"./limitLength\"\nimport pattern, {PatternError} from \"./pattern\"\nimport limitProperties from \"./limitProperties\"\nimport required, {RequiredError} from \"./required\"\nimport limitItems from \"./limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"./uniqueItems\"\nimport constKeyword, {ConstError} from \"./const\"\nimport enumKeyword, {EnumError} from \"./enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n", "import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n", "import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator<string>\n | FormatValidator<number>\n | AsyncFormatValidator<string>\n | AsyncFormatValidator<number>\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n", "import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n", "import type {Vocabulary} from \"../types\"\n\nexport const metadataVocabulary: Vocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n]\n\nexport const contentVocabulary: Vocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n]\n", "import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft7Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n]\n\nexport default draft7Vocabularies\n", "import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj<E extends DiscrError> = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n", "import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n const ref = sch.$ref\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n", "{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"http://json-schema.org/draft-07/schema#\",\n \"title\": \"Core schema meta-schema\",\n \"definitions\": {\n \"schemaArray\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\"$ref\": \"#\"}\n },\n \"nonNegativeInteger\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"nonNegativeIntegerDefault0\": {\n \"allOf\": [{\"$ref\": \"#/definitions/nonNegativeInteger\"}, {\"default\": 0}]\n },\n \"simpleTypes\": {\n \"enum\": [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n \"stringArray\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"uniqueItems\": true,\n \"default\": []\n }\n },\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"$id\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$schema\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"$ref\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$comment\": {\n \"type\": \"string\"\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"default\": true,\n \"readOnly\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"examples\": {\n \"type\": \"array\",\n \"items\": true\n },\n \"multipleOf\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"maximum\": {\n \"type\": \"number\"\n },\n \"exclusiveMaximum\": {\n \"type\": \"number\"\n },\n \"minimum\": {\n \"type\": \"number\"\n },\n \"exclusiveMinimum\": {\n \"type\": \"number\"\n },\n \"maxLength\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minLength\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"pattern\": {\n \"type\": \"string\",\n \"format\": \"regex\"\n },\n \"additionalItems\": {\"$ref\": \"#\"},\n \"items\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/schemaArray\"}],\n \"default\": true\n },\n \"maxItems\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minItems\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"uniqueItems\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"contains\": {\"$ref\": \"#\"},\n \"maxProperties\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minProperties\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"required\": {\"$ref\": \"#/definitions/stringArray\"},\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"definitions\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"properties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"patternProperties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"propertyNames\": {\"format\": \"regex\"},\n \"default\": {}\n },\n \"dependencies\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/stringArray\"}]\n }\n },\n \"propertyNames\": {\"$ref\": \"#\"},\n \"const\": true,\n \"enum\": {\n \"type\": \"array\",\n \"items\": true,\n \"minItems\": 1,\n \"uniqueItems\": true\n },\n \"type\": {\n \"anyOf\": [\n {\"$ref\": \"#/definitions/simpleTypes\"},\n {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/definitions/simpleTypes\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n ]\n },\n \"format\": {\"type\": \"string\"},\n \"contentMediaType\": {\"type\": \"string\"},\n \"contentEncoding\": {\"type\": \"string\"},\n \"if\": {\"$ref\": \"#\"},\n \"then\": {\"$ref\": \"#\"},\n \"else\": {\"$ref\": \"#\"},\n \"allOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"anyOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"oneOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"not\": {\"$ref\": \"#\"}\n },\n \"default\": true\n}\n", "import type {AnySchemaObject} from \"./types\"\nimport AjvCore from \"./core\"\nimport draft7Vocabularies from \"./vocabularies/draft7\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport * as draft7MetaSchema from \"./refs/json-schema-draft-07.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\"\n\nexport class Ajv extends AjvCore {\n _addVocabularies(): void {\n super._addVocabularies()\n draft7Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nmodule.exports.Ajv = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n", "#!/usr/bin/env node\n/**\n * claude-crap MCP server \u2014 entrypoint.\n *\n * Transport: stdio. The server is launched by `.mcp.json` with the\n * arguments `--transport stdio` and it never opens sockets or listens\n * on the network: all communication with Claude Code happens over\n * stdin/stdout as JSON-RPC messages.\n *\n * What this file wires together:\n *\n * Tools:\n * - compute_crap (CRAP index for one function)\n * - compute_tdr (Technical Debt Ratio for a scope)\n * - analyze_file_ast (tree-sitter AST metrics for a source file)\n * - ingest_sarif (normalize + dedupe an external SARIF report)\n * - ingest_scanner_output (route Semgrep/ESLint/Bandit/Stryker native output through an adapter and persist the normalized SARIF)\n * - require_test_harness (check that a production source file has a matching test)\n * - score_project (aggregate the workspace into Maintainability / Reliability / Security / Overall ratings)\n *\n * Resources:\n * - sonar://metrics/current (live CRAP / TDR / rating snapshot)\n * - sonar://reports/latest.sarif (last consolidated SARIF document)\n *\n * The handlers delegate to pure engines in `./metrics`, `./ast` and\n * `./sarif`, so the index file stays focused on routing and\n * cross-cutting concerns (configuration, logging, error boundaries).\n *\n * @module index\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport pino from \"pino\";\n\nimport { adaptScannerOutput, type KnownScanner } from \"./adapters/index.js\";\nimport { TreeSitterEngine } from \"./ast/tree-sitter-engine.js\";\nimport type { SupportedLanguage } from \"./ast/language-config.js\";\nimport { loadConfig, type CrapConfig } from \"./config.js\";\nimport { startDashboard, type DashboardHandle } from \"./dashboard/server.js\";\nimport { computeCrap } from \"./metrics/crap.js\";\nimport {\n computeProjectScore,\n renderProjectScoreMarkdown,\n type ProjectScore,\n} from \"./metrics/score.js\";\nimport { computeTdr, classifyTdr } from \"./metrics/tdr.js\";\nimport { estimateWorkspaceLoc } from \"./metrics/workspace-walker.js\";\nimport { SarifStore, type PersistedSarif } from \"./sarif/sarif-store.js\";\nimport { validateSarifDocument } from \"./sarif/sarif-validator.js\";\nimport { loadCrapConfig, CrapConfigError } from \"./crap-config.js\";\nimport { findTestFile } from \"./tools/test-harness.js\";\nimport { resolveWithinWorkspace } from \"./workspace-guard.js\";\nimport { autoScan } from \"./scanner/auto-scan.js\";\nimport { bootstrapScanner } from \"./scanner/bootstrap.js\";\nimport { discoverProjectMap, persistProjectMap, type ProjectMap } from \"./monorepo/project-map.js\";\nimport {\n autoScanSchema,\n bootstrapScannerSchema,\n computeCrapSchema,\n computeTdrSchema,\n analyzeFileAstSchema,\n ingestSarifSchema,\n ingestScannerOutputSchema,\n listProjectsSchema,\n requireTestHarnessSchema,\n scoreProjectSchema,\n} from \"./schemas/tool-schemas.js\";\n\n// IMPORTANT: the MCP stdio transport uses stdout for JSON-RPC framing.\n// Anything the server logs MUST go to stderr (fd 2) to avoid corrupting\n// the wire format. We configure pino explicitly to write to fd 2.\nconst logger = pino(\n { level: process.env.CLAUDE_CRAP_LOG_LEVEL ?? \"info\" },\n pino.destination(2),\n);\n\n/**\n * Server bootstrap. Loads configuration, instantiates the long-lived\n * engines (tree-sitter, SARIF store), registers tool and resource\n * handlers, and connects the stdio transport. Exits with a non-zero code\n * on fatal startup errors so that Claude Code surfaces the failure to\n * the user instead of silently running without the plugin.\n */\nasync function main(): Promise<void> {\n const config = loadConfig();\n logger.info(\n { config: { ...config, pluginRoot: \"<redacted>\" } },\n \"claude-crap MCP server starting\",\n );\n\n // Load user-defined exclusions and projectDirs from .claude-crap.json (non-fatal).\n let userExclusions: ReadonlyArray<string> = [];\n let userProjectDirs: ReadonlyArray<string> = [];\n try {\n const crapConfig = loadCrapConfig({ workspaceRoot: config.pluginRoot });\n userExclusions = crapConfig.exclude;\n userProjectDirs = crapConfig.projectDirs;\n if (userExclusions.length > 0) {\n logger.info({ exclude: userExclusions }, \"user exclusions loaded from .claude-crap.json\");\n }\n if (userProjectDirs.length > 0) {\n logger.info({ projectDirs: userProjectDirs }, \"user projectDirs loaded from .claude-crap.json\");\n }\n } catch {\n // Non-fatal \u2014 use empty exclusions.\n }\n\n // Long-lived engines. Created once at boot and reused for every call.\n const astEngine = new TreeSitterEngine();\n const sarifStore = new SarifStore({\n workspaceRoot: config.pluginRoot,\n outputDir: config.sarifOutputDir,\n });\n await sarifStore.loadLatest();\n logger.info(\n { findings: sarifStore.size(), path: sarifStore.consolidatedReportPath },\n \"SARIF store ready\",\n );\n\n // Discover monorepo project map (non-fatal).\n let projectMap: ProjectMap | null = null;\n try {\n projectMap = await discoverProjectMap(config.pluginRoot, { projectDirs: userProjectDirs });\n if (projectMap.isMonorepo) {\n logger.info(\n { projects: projectMap.projects.map((p) => `${p.name}(${p.type})`), count: projectMap.projects.length },\n \"monorepo project map discovered\",\n );\n await persistProjectMap(projectMap, config.pluginRoot);\n\n // If any JS/TS sub-projects need ESLint and it's not available,\n // run bootstrap at the monorepo root to auto-install it. In\n // monorepos, ESLint is hoisted to the root node_modules.\n const needsEslint = projectMap.projects.some(\n (p) => (p.type === \"typescript\" || p.type === \"javascript\") && !p.scannerAvailable,\n );\n if (needsEslint) {\n logger.info(\"monorepo: JS/TS projects detected but ESLint not installed \u2014 bootstrapping\");\n try {\n await bootstrapScanner(config.pluginRoot, sarifStore, logger);\n // Re-discover after install so scannerAvailable reflects reality\n projectMap = await discoverProjectMap(config.pluginRoot, { projectDirs: userProjectDirs });\n await persistProjectMap(projectMap, config.pluginRoot);\n } catch (err) {\n logger.warn({ err: (err as Error).message }, \"monorepo ESLint bootstrap failed\");\n }\n }\n }\n } catch (err) {\n logger.warn({ err: (err as Error).message }, \"project map discovery failed\");\n }\n\n // Try to start the local Vue.js dashboard. Failures here are\n // intentionally non-fatal \u2014 the MCP server still works without it.\n let dashboard: DashboardHandle | null = null;\n try {\n dashboard = await startDashboard({\n config,\n sarifStore,\n workspaceStatsProvider: () => estimateWorkspaceLoc(config.pluginRoot, { exclude: userExclusions }),\n logger,\n astEngine,\n exclude: userExclusions,\n });\n } catch (err) {\n logger.warn(\n { err: (err as Error).message, port: config.dashboardPort },\n \"claude-crap dashboard failed to start \u2014 continuing without it\",\n );\n }\n // Make sure the dashboard is closed when the process exits so the TCP\n // port is freed promptly. SIGINT/SIGTERM may arrive from Claude Code's\n // MCP supervisor, from a developer hitting Ctrl-C, or from the test\n // harness in our integration suite.\n //\n // IMPORTANT: installing a custom signal handler overrides Node's\n // default (which exits the process), so we have to call\n // `process.exit()` ourselves once cleanup finishes. Without this the\n // MCP stdio transport would keep reading stdin forever and the\n // Fastify dashboard would keep its listener open, leaving the whole\n // process alive even after SIGTERM.\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.once(signal, () => {\n void (async () => {\n try {\n await dashboard?.close();\n } catch {\n /* best effort \u2014 dashboard may already be down */\n }\n // 130 is the conventional exit code for SIGINT, 143 for SIGTERM.\n const exitCode = signal === \"SIGINT\" ? 130 : 143;\n process.exit(exitCode);\n })();\n });\n }\n\n const server = new Server(\n {\n name: \"claude-crap\",\n version: \"0.1.0\",\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n },\n );\n\n // ------------------------------------------------------------------\n // Tools \u2014 declaration (list)\n // ------------------------------------------------------------------\n // The tool list is what the LLM sees when it introspects the server.\n // Keep the descriptions short, imperative and fact-based.\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"compute_crap\",\n description:\n \"Compute the CRAP (Change Risk Anti-Patterns) index for a function and block when the score exceeds the configured threshold.\",\n inputSchema: computeCrapSchema,\n },\n {\n name: \"compute_tdr\",\n description:\n \"Compute the Technical Debt Ratio for a scope and return the maintainability rating (A..E).\",\n inputSchema: computeTdrSchema,\n },\n {\n name: \"analyze_file_ast\",\n description:\n \"Analyze a source file with tree-sitter and return deterministic metrics (LOC, cyclomatic complexity, function topology).\",\n inputSchema: analyzeFileAstSchema,\n },\n {\n name: \"ingest_sarif\",\n description:\n \"Ingest a raw SARIF 2.1.0 report from an external scanner (Semgrep, ESLint, Bandit, ...), deduplicate it, and persist the consolidated view.\",\n inputSchema: ingestSarifSchema,\n },\n {\n name: \"ingest_scanner_output\",\n description:\n \"Ingest a scanner's native output (Semgrep, ESLint, Bandit, Stryker), route it through the matching adapter, enrich each finding with an effort estimate, and persist the normalized SARIF report.\",\n inputSchema: ingestScannerOutputSchema,\n },\n {\n name: \"require_test_harness\",\n description:\n \"Check whether a production source file has an accompanying test file. Required by the Golden Rule before any functional code is written.\",\n inputSchema: requireTestHarnessSchema,\n },\n {\n name: \"score_project\",\n description:\n \"Aggregate the project score across Maintainability, Reliability, Security and Overall, returning a chat-friendly Markdown summary, the structured JSON, the local dashboard URL, and the consolidated SARIF report path.\",\n inputSchema: scoreProjectSchema,\n },\n {\n name: \"auto_scan\",\n description:\n \"Auto-detect available scanners (ESLint, Semgrep, Bandit, Stryker) in the workspace, run them, and ingest findings into the SARIF store.\",\n inputSchema: autoScanSchema,\n },\n {\n name: \"bootstrap_scanner\",\n description:\n \"Detect project type, install the right scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create minimal config, and run auto_scan to verify.\",\n inputSchema: bootstrapScannerSchema,\n },\n {\n name: \"list_projects\",\n description: \"List all discovered sub-projects in the workspace. In a monorepo, returns each sub-project with its type, path, and recommended scanner.\",\n inputSchema: listProjectsSchema,\n },\n ],\n }));\n\n // ------------------------------------------------------------------\n // Tools \u2014 call dispatch\n // ------------------------------------------------------------------\n // The MCP SDK has already validated `args` against the tool's JSON\n // Schema by the time this handler runs, so we cast to the expected\n // shape without re-validating. Each branch delegates to a pure engine.\n // Tool dispatch is split across two functions to keep cyclomatic\n // complexity within the configured threshold (15) as the tool count\n // grows. Each function handles a subset of tools.\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n logger.info({ tool: name }, \"Tool call received\");\n return handleToolCall(name, args);\n });\n\n // \u2500\u2500 Per-tool handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Extracted from the switch to keep handleToolCall under the\n // cyclomatic complexity threshold.\n\n type ToolResult = { content: Array<{ type: string; text: string }>; isError?: boolean };\n\n function handleComputeCrap(args: Record<string, unknown>): ToolResult {\n const typed = args as {\n cyclomaticComplexity: number;\n coveragePercent: number;\n functionName: string;\n filePath: string;\n };\n const result = computeCrap(\n { cyclomaticComplexity: typed.cyclomaticComplexity, coveragePercent: typed.coveragePercent },\n config.crapThreshold,\n );\n return {\n content: [{ type: \"text\", text: JSON.stringify(\n { tool: \"compute_crap\", function: typed.functionName, file: typed.filePath, ...result }, null, 2,\n ) }],\n isError: result.exceedsThreshold,\n };\n }\n\n function handleComputeTdr(args: Record<string, unknown>): ToolResult {\n const typed = args as {\n remediationMinutes: number;\n totalLinesOfCode: number;\n scope: \"project\" | \"module\" | \"file\";\n };\n const result = computeTdr({\n remediationMinutes: typed.remediationMinutes,\n totalLinesOfCode: typed.totalLinesOfCode,\n minutesPerLoc: config.minutesPerLoc,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify({ tool: \"compute_tdr\", scope: typed.scope, ...result }, null, 2) }],\n };\n }\n\n async function handleAnalyzeFileAst(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { filePath: string; language: SupportedLanguage };\n const absolutePath = resolveWithinWorkspace(config.pluginRoot, typed.filePath);\n try {\n const metrics = await astEngine.analyzeFile({ filePath: absolutePath, language: typed.language });\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"analyze_file_ast\", ...metrics }, null, 2) }] };\n } catch (err) {\n logger.error({ err, filePath: absolutePath, language: typed.language }, \"analyze_file_ast failed\");\n return {\n content: [{ type: \"text\", text: JSON.stringify(\n { tool: \"analyze_file_ast\", status: \"error\", message: (err as Error).message, filePath: typed.filePath, language: typed.language }, null, 2,\n ) }],\n isError: true,\n };\n }\n }\n\n /** Dispatch a tool call to the correct handler. */\n async function handleToolCall(\n name: string,\n args: Record<string, unknown> | undefined,\n ): Promise<ToolResult> {\n switch (name) {\n case \"compute_crap\":\n return handleComputeCrap(args ?? {});\n case \"compute_tdr\":\n return handleComputeTdr(args ?? {});\n case \"analyze_file_ast\":\n return handleAnalyzeFileAst(args ?? {});\n\n case \"score_project\":\n return handleScoreProject(args ?? {});\n case \"require_test_harness\":\n return handleRequireTestHarness(args ?? {});\n case \"ingest_scanner_output\":\n return handleIngestScannerOutput(args ?? {});\n case \"ingest_sarif\":\n return handleIngestSarif(args ?? {});\n case \"bootstrap_scanner\":\n return handleBootstrapScanner();\n case \"auto_scan\":\n return handleAutoScan();\n case \"list_projects\":\n return handleListProjects();\n default:\n throw new Error(`[claude-crap] Unknown tool: ${name}`);\n }\n }\n\n async function handleScoreProject(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { format?: \"markdown\" | \"json\" | \"both\"; scope?: string };\n const format = typed.format ?? \"both\";\n let scoreRoot = config.pluginRoot;\n if (typed.scope && projectMap) {\n const project = projectMap.projects.find((p) => p.name === typed.scope);\n if (project) {\n const { join } = await import(\"node:path\");\n scoreRoot = join(config.pluginRoot, project.path);\n }\n }\n try {\n const workspace = await estimateWorkspaceLoc(scoreRoot, { exclude: userExclusions });\n const score: ProjectScore = computeProjectScore({\n workspaceRoot: scoreRoot, minutesPerLoc: config.minutesPerLoc, tdrMaxRating: config.tdrMaxRating,\n workspace: { physicalLoc: workspace.physicalLoc, fileCount: workspace.fileCount },\n sarifStore, dashboardUrl: dashboard?.url ?? null, sarifReportPath: sarifStore.consolidatedReportPath,\n });\n const blocks: Array<{ type: \"text\"; text: string }> = [];\n if (format === \"markdown\" || format === \"both\") blocks.push({ type: \"text\", text: renderProjectScoreMarkdown(score) });\n if (format === \"json\" || format === \"both\") blocks.push({ type: \"text\", text: JSON.stringify(score, null, 2) });\n const strictness = safeLoadStrictness(config.pluginRoot, logger);\n return { content: blocks, isError: strictness === \"strict\" && !score.overall.passes };\n } catch (err) {\n logger.error({ err }, \"score_project failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"score_project\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleRequireTestHarness(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { filePath: string };\n const absolutePath = resolveWithinWorkspace(config.pluginRoot, typed.filePath);\n try {\n const resolution = await findTestFile(config.pluginRoot, absolutePath);\n const hasTest = resolution.testFile !== null;\n return {\n content: [{ type: \"text\", text: JSON.stringify({\n tool: \"require_test_harness\", filePath: typed.filePath, hasTest, isTestFile: resolution.isTestFile,\n testFile: resolution.testFile, candidates: resolution.candidates,\n ...(hasTest ? {} : { corrective: \"No test file found. Per the CLAUDE.md Golden Rule, create a characterization test at one of the candidate paths before writing any functional code for this file.\" }),\n }, null, 2) }],\n isError: !hasTest,\n };\n } catch (err) {\n logger.error({ err, filePath: absolutePath }, \"require_test_harness failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"require_test_harness\", status: \"error\", message: (err as Error).message, filePath: typed.filePath }, null, 2) }], isError: true };\n }\n }\n\n async function handleIngestScannerOutput(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { scanner: KnownScanner; rawOutput: unknown };\n try {\n const adapted = adaptScannerOutput(typed.scanner, typed.rawOutput);\n validateSarifDocument(adapted.document);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n await sarifStore.persist();\n return { content: [{ type: \"text\", text: JSON.stringify({\n tool: \"ingest_scanner_output\", status: \"accepted\", scanner: typed.scanner,\n findingsParsed: adapted.findingCount, totalEffortMinutes: adapted.totalEffortMinutes,\n accepted: stats.accepted, duplicates: stats.duplicates, total: stats.total,\n storeSize: sarifStore.size(), reportPath: sarifStore.consolidatedReportPath,\n }, null, 2) }] };\n } catch (err) {\n logger.error({ err, scanner: typed.scanner }, \"ingest_scanner_output failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"ingest_scanner_output\", status: \"error\", scanner: typed.scanner, message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleIngestSarif(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { sarifDocument: PersistedSarif; sourceTool: string };\n try {\n validateSarifDocument(typed.sarifDocument);\n const stats = sarifStore.ingestRun(typed.sarifDocument, typed.sourceTool);\n await sarifStore.persist();\n return { content: [{ type: \"text\", text: JSON.stringify({\n tool: \"ingest_sarif\", status: \"accepted\", sourceTool: typed.sourceTool,\n accepted: stats.accepted, duplicates: stats.duplicates, total: stats.total,\n storeSize: sarifStore.size(), reportPath: sarifStore.consolidatedReportPath,\n }, null, 2) }] };\n } catch (err) {\n logger.error({ err, sourceTool: typed.sourceTool }, \"ingest_sarif failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"ingest_sarif\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleBootstrapScanner(): Promise<ToolResult> {\n try {\n const result = await bootstrapScanner(config.pluginRoot, sarifStore, logger);\n return { content: [{ type: \"text\", text: renderBootstrapMarkdown(result) }, { type: \"text\", text: JSON.stringify(result, null, 2) }], isError: !result.success };\n } catch (err) {\n logger.error({ err }, \"bootstrap_scanner failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"bootstrap_scanner\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleAutoScan(): Promise<ToolResult> {\n try {\n const result = await autoScan(config.pluginRoot, sarifStore, logger, { engine: astEngine, cyclomaticMax: config.cyclomaticMax, exclude: userExclusions });\n return { content: [{ type: \"text\", text: renderAutoScanMarkdown(result) }, { type: \"text\", text: JSON.stringify(result, null, 2) }] };\n } catch (err) {\n logger.error({ err }, \"auto_scan failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"auto_scan\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n function handleListProjects(): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"list_projects\", isMonorepo: projectMap?.isMonorepo ?? false, projects: projectMap?.projects ?? [] }, null, 2) }] };\n }\n\n // ------------------------------------------------------------------\n // Resources \u2014 topology and reports\n // ------------------------------------------------------------------\n server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n resources: [\n {\n uri: \"sonar://metrics/current\",\n name: \"Current project metrics\",\n mimeType: \"application/json\",\n description: \"Snapshot of CRAP, TDR, and Reliability / Security ratings.\",\n },\n {\n uri: \"sonar://reports/latest.sarif\",\n name: \"Latest consolidated SARIF 2.1.0 report\",\n mimeType: \"application/sarif+json\",\n description: \"Unified SARIF document produced by the most recent Stop quality-gate run.\",\n },\n ],\n }));\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n if (uri === \"sonar://reports/latest.sarif\") {\n const doc = sarifStore.toSarifDocument();\n return {\n contents: [\n {\n uri,\n mimeType: \"application/sarif+json\",\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n if (uri === \"sonar://metrics/current\") {\n const snapshot = await buildMetricsSnapshot(config, sarifStore);\n return {\n contents: [\n {\n uri,\n mimeType: \"application/json\",\n text: JSON.stringify(snapshot, null, 2),\n },\n ],\n };\n }\n throw new Error(`[claude-crap] Unknown resource URI: ${uri}`);\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n logger.info(\"claude-crap MCP server ready (stdio)\");\n\n // Fire-and-forget: auto-scan runs in background, doesn't block tool calls.\n // If the agent calls score_project before scanning finishes, it gets\n // whatever is in the SARIF store so far. The next call after completion\n // reflects all findings.\n autoScan(config.pluginRoot, sarifStore, logger, {\n engine: astEngine,\n cyclomaticMax: config.cyclomaticMax,\n exclude: userExclusions,\n })\n .then((result) => {\n const scanners = result.results\n .filter((r) => r.success)\n .map((r) => r.scanner);\n logger.info(\n {\n scannersRun: scanners,\n totalFindings: result.totalFindings,\n durationMs: result.totalDurationMs,\n },\n \"auto-scan completed\",\n );\n })\n .catch((err) => {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan failed \u2014 continuing without it\",\n );\n });\n}\n\n/**\n * Render a human-readable Markdown summary of a bootstrap result.\n */\nfunction renderBootstrapMarkdown(result: import(\"./scanner/bootstrap.js\").BootstrapResult): string {\n const lines: string[] = [\"## claude-crap :: bootstrap scanner\\n\"];\n\n lines.push(`**Project type:** ${result.projectType}`);\n\n if (result.alreadyConfigured) {\n lines.push(`**Status:** Scanner(s) already configured: ${result.existingScanners.join(\", \")}`);\n lines.push(\"\\nNo installation needed. Run `auto_scan` to ingest findings.\");\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n\n if (result.steps.length > 0) {\n lines.push(\"### Steps\\n\");\n lines.push(\"| Action | Status | Detail |\");\n lines.push(\"| ------ | :----: | ------ |\");\n for (const s of result.steps) {\n const status = s.success ? \"ok\" : \"failed\";\n lines.push(`| ${s.action} | ${status} | ${s.detail} |`);\n }\n lines.push(\"\");\n }\n\n if (result.autoScanResult) {\n const r = result.autoScanResult;\n const scanners = r.results.filter((s) => s.success).map((s) => s.scanner);\n lines.push(\n `**Auto-scan:** ${r.totalFindings} finding(s) ingested from ${scanners.join(\", \") || \"no scanners\"} in ${(r.totalDurationMs / 1000).toFixed(1)}s`,\n );\n lines.push(\"\");\n }\n\n lines.push(`**Summary:** ${result.summary}`);\n return lines.join(\"\\n\");\n}\n\n/**\n * Render a human-readable Markdown summary of an auto-scan result.\n */\nfunction renderAutoScanMarkdown(result: import(\"./scanner/auto-scan.js\").AutoScanResult): string {\n const lines: string[] = [\"## claude-crap :: auto-scan results\\n\"];\n\n // Detection summary\n lines.push(\"### Detected scanners\\n\");\n lines.push(\"| Scanner | Available | Reason |\");\n lines.push(\"| ------- | :-------: | ------ |\");\n for (const d of result.detected) {\n lines.push(`| ${d.scanner} | ${d.available ? \"yes\" : \"no\"} | ${d.reason} |`);\n }\n lines.push(\"\");\n\n // Execution results\n if (result.results.length > 0) {\n lines.push(\"### Execution results\\n\");\n lines.push(\"| Scanner | Status | Findings | Duration |\");\n lines.push(\"| ------- | :----: | :------: | -------: |\");\n for (const r of result.results) {\n const status = r.success ? \"ok\" : \"failed\";\n const duration = `${(r.durationMs / 1000).toFixed(1)}s`;\n lines.push(`| ${r.scanner} | ${status} | ${r.findingsIngested} | ${duration} |`);\n }\n lines.push(\"\");\n }\n\n // Complexity scan\n if (result.complexityScan) {\n const cs = result.complexityScan;\n lines.push(\"### Cyclomatic complexity scan\\n\");\n lines.push(`- Files scanned: **${cs.filesScanned}**`);\n lines.push(`- Functions analyzed: **${cs.functionsAnalyzed}**`);\n lines.push(`- Violations: **${cs.violations}**`);\n lines.push(`- Duration: ${(cs.durationMs / 1000).toFixed(1)}s`);\n lines.push(\"\");\n }\n\n // Summary\n lines.push(\n `**Total findings ingested:** ${result.totalFindings} in ${(result.totalDurationMs / 1000).toFixed(1)}s`,\n );\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Load the workspace strictness without letting a busted config\n * file take down the `score_project` tool. On any loader error we\n * log to stderr via pino and fall back to `\"strict\"` so the tool\n * stays useful. This is the MCP-server-side counterpart to the\n * `resolveStrictness` helper in `hooks/stop-quality-gate.mjs`.\n *\n * @param workspaceRoot Absolute path the loader should probe for\n * `.claude-crap.json`.\n * @param logger Pino logger used to surface recoverable\n * config errors.\n * @returns The resolved strictness, or `\"strict\"` on\n * error.\n */\nfunction safeLoadStrictness(\n workspaceRoot: string,\n logger: import(\"pino\").Logger,\n): \"strict\" | \"warn\" | \"advisory\" {\n try {\n return loadCrapConfig({ workspaceRoot }).strictness;\n } catch (err) {\n if (err instanceof CrapConfigError) {\n logger.warn(\n { err: err.message },\n \"score_project: invalid sonar config, falling back to strict\",\n );\n return \"strict\";\n }\n throw err;\n }\n}\n\n/**\n * Build a lightweight metrics snapshot that the LLM can read through\n * the `sonar://metrics/current` resource. This is intentionally thin\n * and side-effect free: it derives everything from the in-memory\n * SARIF store without walking the workspace. Callers that need a\n * full scoring payload (with a real LOC walk and the A..E grades per\n * dimension) should invoke the `score_project` tool, which uses the\n * bounded workspace walker and the `metrics/score.ts` engine.\n *\n * @param config Fully resolved server configuration.\n * @param sarifStore Live SARIF store used to read the latest findings.\n */\nasync function buildMetricsSnapshot(\n config: CrapConfig,\n sarifStore: SarifStore,\n): Promise<Record<string, unknown>> {\n const findings = sarifStore.list();\n const totalRemediationMinutes = findings.reduce((sum, f) => {\n const effort = f.properties?.[\"effortMinutes\"];\n return typeof effort === \"number\" ? sum + effort : sum;\n }, 0);\n\n // Cheap LOC approximation derived from the SARIF report: assume\n // ~100 physical lines per file we have at least one finding in.\n // This keeps the resource read lock-free and synchronous-feeling;\n // the `score_project` tool is the authoritative path when a real\n // workspace walk is required.\n const uniqueFiles = new Set(findings.map((f) => f.location.uri));\n const approxLoc = Math.max(uniqueFiles.size * 100, 1);\n\n const tdrPercent =\n totalRemediationMinutes / (config.minutesPerLoc * approxLoc) * 100;\n const rating = classifyTdr(Number.isFinite(tdrPercent) ? tdrPercent : 0);\n\n return {\n generatedAt: new Date().toISOString(),\n config: {\n crapThreshold: config.crapThreshold,\n tdrMaxRating: config.tdrMaxRating,\n minutesPerLoc: config.minutesPerLoc,\n },\n sarif: {\n reportPath: sarifStore.consolidatedReportPath,\n findings: findings.length,\n files: uniqueFiles.size,\n tools: Array.from(new Set(findings.map((f) => f.sourceTool))),\n },\n tdrApprox: {\n percent: Number(tdrPercent.toFixed(4)),\n rating,\n remediationMinutes: totalRemediationMinutes,\n approxLinesOfCode: approxLoc,\n },\n };\n}\n\n// Top-level await would be cleaner, but we keep main() + .catch() so\n// any error during async bootstrap (engine init, store load) surfaces as\n// a non-zero exit code visible to Claude Code's MCP diagnostics.\nmain().catch((err) => {\n // Fatal errors go to stderr to avoid corrupting the JSON-RPC channel\n // on stdout. We use `process.stderr.write` rather than `console.error`\n // so that no lint suppression is needed and so that no buffering layer\n // can swallow the message. A non-zero exit code causes Claude Code to\n // surface the failure in its MCP-server diagnostics.\n process.stderr.write(`[claude-crap] fatal error during startup: ${String(err)}\\n`);\n if (err instanceof Error && err.stack) {\n process.stderr.write(err.stack + \"\\n\");\n }\n process.exit(1);\n});\n", "/**\n * Shared types and helpers for per-scanner SARIF adapters.\n *\n * Every adapter in this directory converts a scanner's native output\n * into a `PersistedSarif` 2.1.0 document that the `SarifStore` can\n * ingest directly. The adapters also enrich the finding `properties`\n * bag with a stable `effortMinutes` field so the Stop quality gate and\n * the Technical Debt Ratio computation can treat every source tool\n * uniformly.\n *\n * Rule-level effort estimates live in `DEFAULT_EFFORT_BY_SEVERITY`.\n * Individual adapters may override the default per rule id when the\n * scanner attaches a more specific hint.\n *\n * @module adapters/common\n */\n\nimport type { PersistedSarif } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n/**\n * The canonical list of scanners claude-crap understands. The\n * `ingest_scanner_output` MCP tool uses this as its `enum` constraint,\n * so keeping it narrow prevents drift.\n */\nexport const KNOWN_SCANNERS = [\"semgrep\", \"eslint\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"] as const;\n\n/**\n * Union of supported scanner identifiers.\n */\nexport type KnownScanner = (typeof KNOWN_SCANNERS)[number];\n\n/**\n * Default remediation effort in minutes per SARIF severity level. These\n * numbers are deliberately conservative \u2014 real projects should override\n * them per rule via adapter-specific rule maps or via SARIF properties.\n *\n * The mapping follows the common-sense rule that every bug takes at\n * least a test plus a patch, so even a note-level finding costs time.\n */\nexport const DEFAULT_EFFORT_BY_SEVERITY: Readonly<Record<SarifLevel, number>> = Object.freeze({\n error: 60,\n warning: 30,\n note: 10,\n none: 5,\n});\n\n/**\n * Envelope common to every adapter output. Adapters return a\n * `PersistedSarif` document and a small stats block describing what\n * they saw, so the MCP tool handler can echo those stats back to the\n * LLM even when the SarifStore rejects duplicates.\n */\nexport interface AdapterResult {\n /** Normalized SARIF 2.1.0 document ready for `SarifStore.ingestRun`. */\n readonly document: PersistedSarif;\n /** Scanner identifier, propagated into every finding's `properties.sourceTool`. */\n readonly sourceTool: KnownScanner;\n /** Raw number of findings the adapter read from the scanner's native output. */\n readonly findingCount: number;\n /** Total estimated remediation effort across all findings, in minutes. */\n readonly totalEffortMinutes: number;\n}\n\n/**\n * Build a `PersistedSarif` document from a flat list of already-mapped\n * result entries. Every adapter produces its results with the same\n * shape and then calls this helper to wrap them in a valid 2.1.0 envelope.\n *\n * @param sourceTool Stable scanner identifier (e.g. `\"semgrep\"`).\n * @param version Adapter version string stored in `tool.driver.version`.\n * @param results Pre-built SARIF `result` entries.\n */\nexport function wrapResultsInSarif(\n sourceTool: KnownScanner,\n version: string,\n results: ReadonlyArray<object>,\n): PersistedSarif {\n return {\n $schema: \"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\",\n version: \"2.1.0\",\n runs: [\n {\n tool: {\n driver: {\n name: sourceTool,\n version,\n },\n },\n results: results as ReadonlyArray<SarifResultShape>,\n },\n ],\n } as PersistedSarif;\n}\n\n/**\n * Narrow structural contract of a SARIF `result` object. We type it\n * loosely so adapters can emit the minimum required fields without\n * importing the full SARIF spec types from `sarif-store.ts`.\n */\ninterface SarifResultShape {\n readonly ruleId: string;\n readonly level?: SarifLevel;\n readonly message: { readonly text: string };\n readonly locations?: ReadonlyArray<{\n readonly physicalLocation?: {\n readonly artifactLocation?: { readonly uri?: string };\n readonly region?: {\n readonly startLine?: number;\n readonly startColumn?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n };\n };\n }>;\n readonly properties?: Record<string, unknown>;\n}\n\n/**\n * Estimate remediation effort for a single finding given its severity\n * and an optional rule-specific override. Returns `minutes` clamped to\n * a non-negative integer.\n *\n * @param level SARIF severity level (`\"error\"`, `\"warning\"`, ...).\n * @param override Optional rule-specific effort in minutes.\n */\nexport function estimateEffortMinutes(level: SarifLevel | undefined, override?: number): number {\n if (typeof override === \"number\" && Number.isFinite(override) && override >= 0) {\n return Math.round(override);\n }\n const base = DEFAULT_EFFORT_BY_SEVERITY[level ?? \"warning\"];\n return Math.max(0, Math.round(base ?? 30));\n}\n", "/**\n * Semgrep adapter.\n *\n * Semgrep already emits SARIF 2.1.0 natively when invoked with\n * `--sarif`, so this adapter's job is not translation but\n * **enrichment**: we walk every `result` entry and stamp a\n * `properties.effortMinutes` value so the Stop quality gate can\n * compute a Technical Debt Ratio, plus we normalize the\n * `properties.sourceTool` field so downstream consumers always know\n * the finding came from Semgrep.\n *\n * If the caller passes a string, we parse it as JSON. If they pass an\n * object that already matches the SARIF 2.1.0 envelope, we use it\n * directly. Anything else throws a descriptive error that the MCP\n * tool handler surfaces back to the LLM.\n *\n * @module adapters/semgrep\n */\n\nimport type { PersistedSarif } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst SEMGREP: KnownScanner = \"semgrep\";\n\n/**\n * Rule-id effort overrides. Semgrep emits lots of stylistic rules\n * that take less than a minute to fix and a handful of deep security\n * rules that deserve more budget than the default warning tier. The\n * list below is intentionally short \u2014 teams should extend it.\n */\nconst SEMGREP_EFFORT_OVERRIDES: ReadonlyMap<RegExp, number> = new Map([\n [/security\\./i, 90],\n [/sqli|xss|ssrf|rce|deserial|crypto/i, 120],\n [/style\\./i, 5],\n [/formatting\\./i, 3],\n]);\n\n/**\n * Accept a Semgrep SARIF document (as a string or object) and return\n * an enriched `PersistedSarif` with effort estimates and a normalized\n * `sourceTool` field.\n *\n * @param input Raw SARIF document from Semgrep (`JSON.stringify`ed or parsed).\n * @returns The enriched document plus per-run stats.\n * @throws When the input is not a SARIF 2.1.0 document.\n */\nexport function adaptSemgrep(input: unknown): AdapterResult {\n const doc = coerceToSarif(input);\n\n let findingCount = 0;\n let totalEffortMinutes = 0;\n\n // We deep-clone the document so callers don't observe a mutation on\n // the value they passed us. JSON round-trip is cheap here; a\n // typical Semgrep SARIF report is well under 1 MB.\n //\n // We operate on the cloned value through a loose `Record`-based view\n // to keep the adapter agnostic to the full SARIF schema \u2014 the\n // canonical types live in `sarif-store.ts` and we only care about a\n // handful of fields here. The final return casts through `unknown`\n // because the JSON round-trip is shape-preserving by construction.\n const cloned = JSON.parse(JSON.stringify(doc)) as {\n runs?: Array<Record<string, unknown>>;\n };\n const runs = Array.isArray(cloned.runs) ? cloned.runs : [];\n\n for (const run of runs) {\n const rawResults = run[\"results\"];\n const results = Array.isArray(rawResults) ? (rawResults as Array<Record<string, unknown>>) : [];\n for (const result of results) {\n findingCount += 1;\n const ruleId = typeof result[\"ruleId\"] === \"string\" ? (result[\"ruleId\"] as string) : \"\";\n const level = result[\"level\"] as SarifLevel | undefined;\n const override = matchOverride(ruleId);\n const effort = estimateEffortMinutes(level, override);\n totalEffortMinutes += effort;\n const existingProps =\n result[\"properties\"] && typeof result[\"properties\"] === \"object\"\n ? (result[\"properties\"] as Record<string, unknown>)\n : {};\n result[\"properties\"] = {\n ...existingProps,\n sourceTool: SEMGREP,\n effortMinutes: effort,\n };\n }\n\n // Overwrite tool.driver.name so store-level filters always match\n // `\"semgrep\"` regardless of the label Semgrep reported. Preserve\n // the existing version and rules[] array when present.\n const existingTool = (run[\"tool\"] as Record<string, unknown> | undefined) ?? {};\n const existingDriver = (existingTool[\"driver\"] as Record<string, unknown> | undefined) ?? {};\n const driverOut: Record<string, unknown> = {\n name: SEMGREP,\n version: typeof existingDriver[\"version\"] === \"string\" ? existingDriver[\"version\"] : \"unknown\",\n };\n if (Array.isArray(existingDriver[\"rules\"])) {\n driverOut[\"rules\"] = existingDriver[\"rules\"];\n }\n run[\"tool\"] = { driver: driverOut };\n }\n\n return {\n document: cloned as unknown as PersistedSarif,\n sourceTool: SEMGREP,\n findingCount,\n totalEffortMinutes,\n };\n}\n\n/**\n * Accept either a pre-parsed SARIF object or a JSON string and return\n * a strongly-typed `PersistedSarif`. Throws on malformed input.\n *\n * @param input Raw caller-provided value.\n */\nfunction coerceToSarif(input: unknown): PersistedSarif {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:semgrep] input is not a SARIF object`);\n }\n const doc = parsed as { version?: unknown; runs?: unknown };\n if (doc.version !== \"2.1.0\") {\n throw new Error(\n `[adapter:semgrep] expected SARIF version 2.1.0, got ${String(doc.version)}`,\n );\n }\n if (!Array.isArray(doc.runs)) {\n throw new Error(`[adapter:semgrep] document is missing a runs[] array`);\n }\n return parsed as PersistedSarif;\n}\n\n/**\n * Return the effort override (in minutes) matching the first pattern\n * that matches the given rule id, or `undefined` when none match.\n *\n * @param ruleId Semgrep rule identifier.\n */\nfunction matchOverride(ruleId: string): number | undefined {\n for (const [pattern, minutes] of SEMGREP_EFFORT_OVERRIDES) {\n if (pattern.test(ruleId)) return minutes;\n }\n return undefined;\n}\n", "/**\n * ESLint adapter.\n *\n * ESLint's default JSON output (`eslint -f json .`) is NOT SARIF.\n * This adapter converts it into a SARIF 2.1.0 document with one\n * `result` per ESLint `messages[]` entry, mapping ESLint's numeric\n * severity to SARIF levels:\n *\n * severity 0 \u2192 \"note\" (parser info / disabled)\n * severity 1 \u2192 \"warning\"\n * severity 2 \u2192 \"error\"\n *\n * ESLint's JSON shape:\n *\n * [\n * {\n * \"filePath\": \"/abs/path/to/foo.js\",\n * \"messages\": [\n * {\n * \"ruleId\": \"no-unused-vars\",\n * \"severity\": 1,\n * \"message\": \"'foo' is defined but never used.\",\n * \"line\": 10,\n * \"column\": 5,\n * \"endLine\": 10,\n * \"endColumn\": 8\n * }\n * ],\n * \"errorCount\": 0,\n * \"warningCount\": 1,\n * \"fatalErrorCount\": 0,\n * \"source\": \"...\",\n * \"usedDeprecatedRules\": []\n * }\n * ]\n *\n * We preserve the full `line`/`column` range when ESLint provides one\n * so the dashboard's hot-spot table can show a precise location.\n *\n * @module adapters/eslint\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst ESLINT: KnownScanner = \"eslint\";\n\n/**\n * ESLint JSON file entry as produced by `eslint -f json`. We type it\n * permissively because many ESLint fields are optional depending on\n * version and plugin.\n */\ninterface EslintFileReport {\n readonly filePath?: string;\n readonly messages?: ReadonlyArray<EslintMessage>;\n}\n\ninterface EslintMessage {\n readonly ruleId?: string | null;\n readonly severity?: number;\n readonly message?: string;\n readonly line?: number;\n readonly column?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n readonly fatal?: boolean;\n}\n\n/**\n * Accept ESLint native JSON output and return a normalized\n * `PersistedSarif` document plus counts.\n *\n * @param input Raw ESLint JSON (string or parsed array).\n * @returns Adapter result.\n * @throws When the input is not a valid ESLint report.\n */\nexport function adaptEslint(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!Array.isArray(parsed)) {\n throw new Error(`[adapter:eslint] expected an array of file reports`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const fileReport of parsed as ReadonlyArray<EslintFileReport>) {\n const filePath = fileReport?.filePath;\n if (typeof filePath !== \"string\" || !filePath) continue;\n const messages = Array.isArray(fileReport.messages) ? fileReport.messages : [];\n for (const msg of messages) {\n const level = mapSeverity(msg.severity);\n const ruleId = typeof msg.ruleId === \"string\" ? msg.ruleId : \"eslint.unknown\";\n const line = typeof msg.line === \"number\" && msg.line > 0 ? msg.line : 1;\n const column = typeof msg.column === \"number\" && msg.column > 0 ? msg.column : 1;\n const effort = estimateEffortMinutes(level);\n totalEffortMinutes += effort;\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message: msg.message ?? ruleId,\n uri: filePath,\n startLine: line,\n startColumn: column,\n endLine: typeof msg.endLine === \"number\" ? msg.endLine : undefined,\n endColumn: typeof msg.endColumn === \"number\" ? msg.endColumn : undefined,\n effortMinutes: effort,\n }),\n );\n }\n }\n\n return {\n document: wrapResultsInSarif(ESLINT, \"unknown\", results),\n sourceTool: ESLINT,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Translate ESLint's numeric severity to a SARIF level. ESLint uses:\n *\n * 0 = off / disabled \u2192 `\"note\"` (informational)\n * 1 = warn \u2192 `\"warning\"`\n * 2 = error \u2192 `\"error\"`\n *\n * Unknown values default to `\"warning\"` so the finding is still\n * visible without being treated as a blocker.\n */\nfunction mapSeverity(severity: number | undefined): SarifLevel {\n switch (severity) {\n case 2:\n return \"error\";\n case 1:\n return \"warning\";\n case 0:\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n/**\n * Assemble a SARIF `result` object from the narrow set of fields an\n * ESLint message provides. The shape matches what the SarifStore\n * expects when hydrating a finding from a persisted document.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n endLine?: number | undefined;\n endColumn?: number | undefined;\n effortMinutes: number;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n ...(opts.endLine !== undefined ? { endLine: opts.endLine } : {}),\n ...(opts.endColumn !== undefined ? { endColumn: opts.endColumn } : {}),\n },\n },\n },\n ],\n properties: {\n sourceTool: ESLINT,\n effortMinutes: opts.effortMinutes,\n },\n };\n}\n", "/**\n * Bandit adapter.\n *\n * Bandit is a Python security linter. When run with `-f json` it\n * emits a JSON report shaped like this (abbreviated):\n *\n * {\n * \"results\": [\n * {\n * \"filename\": \"app.py\",\n * \"line_number\": 42,\n * \"col_offset\": 5,\n * \"test_id\": \"B608\",\n * \"test_name\": \"hardcoded_sql_expressions\",\n * \"issue_severity\": \"HIGH\", // LOW | MEDIUM | HIGH\n * \"issue_confidence\": \"HIGH\", // LOW | MEDIUM | HIGH\n * \"issue_text\": \"Possible SQL injection via string-based query construction.\",\n * \"issue_cwe\": { \"id\": 89 }\n * }\n * ],\n * \"metrics\": { ... },\n * \"errors\": [ ... ]\n * }\n *\n * This adapter converts each `results[]` entry into a SARIF 2.1.0\n * `result`, mapping Bandit severity levels to SARIF levels:\n *\n * LOW \u2192 \"note\"\n * MEDIUM \u2192 \"warning\"\n * HIGH \u2192 \"error\"\n *\n * Every finding gets a rule id of `bandit.<test_id>` (e.g.\n * `bandit.B608`) so it is trivial to correlate with Bandit's own docs\n * from inside the claude-crap dashboard.\n *\n * @module adapters/bandit\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst BANDIT: KnownScanner = \"bandit\";\n\ninterface BanditReport {\n readonly results?: ReadonlyArray<BanditFinding>;\n}\n\ninterface BanditFinding {\n readonly filename?: string;\n readonly line_number?: number;\n readonly col_offset?: number;\n readonly test_id?: string;\n readonly test_name?: string;\n readonly issue_severity?: string;\n readonly issue_confidence?: string;\n readonly issue_text?: string;\n readonly issue_cwe?: { readonly id?: number };\n}\n\n/**\n * Accept a Bandit JSON report and return a normalized\n * `PersistedSarif` document.\n *\n * @param input Raw Bandit JSON (string or parsed object).\n * @returns Adapter result.\n * @throws When the input does not look like a Bandit report.\n */\nexport function adaptBandit(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:bandit] expected a JSON object`);\n }\n const report = parsed as BanditReport;\n if (!Array.isArray(report.results)) {\n throw new Error(`[adapter:bandit] report is missing a results[] array`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const finding of report.results) {\n const filename = finding.filename;\n if (typeof filename !== \"string\" || !filename) continue;\n const level = mapSeverity(finding.issue_severity);\n // High-severity security findings cost more to fix than the\n // generic default, so we bias the budget toward reality. Bandit\n // is always security-focused, so every finding is treated as a\n // security issue for TDR accounting downstream.\n const effortOverride = level === \"error\" ? 120 : level === \"warning\" ? 60 : 20;\n const effort = estimateEffortMinutes(level, effortOverride);\n totalEffortMinutes += effort;\n\n const testId = finding.test_id ?? \"unknown\";\n const ruleId = `bandit.${testId}`;\n const messageText =\n finding.issue_text ??\n `${finding.test_name ?? \"Bandit finding\"} (${finding.issue_severity ?? \"UNKNOWN\"})`;\n\n const startLine =\n typeof finding.line_number === \"number\" && finding.line_number > 0\n ? finding.line_number\n : 1;\n const startColumn =\n typeof finding.col_offset === \"number\" && finding.col_offset >= 0\n ? finding.col_offset + 1\n : 1;\n\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message: messageText,\n uri: filename,\n startLine,\n startColumn,\n effortMinutes: effort,\n cwe: finding.issue_cwe?.id,\n confidence: finding.issue_confidence,\n }),\n );\n }\n\n return {\n document: wrapResultsInSarif(BANDIT, \"unknown\", results),\n sourceTool: BANDIT,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Map Bandit's `issue_severity` string to a SARIF level. Unknown\n * values default to `\"warning\"` so findings are still surfaced.\n */\nfunction mapSeverity(severity: string | undefined): SarifLevel {\n switch ((severity ?? \"\").toUpperCase()) {\n case \"HIGH\":\n return \"error\";\n case \"MEDIUM\":\n return \"warning\";\n case \"LOW\":\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n/**\n * Build the SARIF `result` object for a single Bandit finding. We\n * stash the CWE id and Bandit confidence in the `properties` bag so\n * consumers can surface them in the dashboard hot-spot view.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n effortMinutes: number;\n cwe?: number | undefined;\n confidence?: string | undefined;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n },\n },\n },\n ],\n properties: {\n sourceTool: BANDIT,\n effortMinutes: opts.effortMinutes,\n ...(typeof opts.cwe === \"number\" ? { cwe: opts.cwe } : {}),\n ...(typeof opts.confidence === \"string\" ? { confidence: opts.confidence } : {}),\n },\n };\n}\n", "/**\n * Stryker (JavaScript mutation testing) adapter.\n *\n * Stryker emits a JSON report under `reports/mutation/mutation.json`.\n * The report shape is documented at\n * https://stryker-mutator.io/docs/mutation-testing-elements/mutant-result-schema/ :\n *\n * {\n * \"schemaVersion\": \"1.0\",\n * \"thresholds\": { ... },\n * \"files\": {\n * \"src/foo.ts\": {\n * \"language\": \"typescript\",\n * \"source\": \"...\",\n * \"mutants\": [\n * {\n * \"id\": \"1\",\n * \"mutatorName\": \"ConditionalExpression\",\n * \"replacement\": \"false\",\n * \"location\": {\n * \"start\": { \"line\": 10, \"column\": 5 },\n * \"end\": { \"line\": 10, \"column\": 15 }\n * },\n * \"status\": \"Survived\", // Killed | Survived | Timeout | NoCoverage | RuntimeError | CompileError | Ignored\n * \"statusReason\": \"...\"\n * }\n * ]\n * }\n * }\n * }\n *\n * This adapter treats every **surviving mutant** as a SARIF\n * `error`-level finding \u2014 surviving mutants are exactly the ones the\n * Golden Rule forbids, because they prove the test suite does not\n * pin the code's behavior tightly enough to notice a change.\n *\n * Mutants with status `NoCoverage` become `warning`-level findings\n * (not blocking the Stop gate by themselves, but still ingested so\n * the dashboard can surface uncovered lines). All other statuses are\n * ignored \u2014 they do not represent defects.\n *\n * @module adapters/stryker\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst STRYKER: KnownScanner = \"stryker\";\n\ninterface StrykerReport {\n readonly schemaVersion?: string;\n readonly files?: Record<string, StrykerFileReport>;\n}\n\ninterface StrykerFileReport {\n readonly language?: string;\n readonly mutants?: ReadonlyArray<StrykerMutant>;\n}\n\ninterface StrykerMutant {\n readonly id?: string;\n readonly mutatorName?: string;\n readonly replacement?: string;\n readonly location?: {\n readonly start?: { readonly line?: number; readonly column?: number };\n readonly end?: { readonly line?: number; readonly column?: number };\n };\n readonly status?: string;\n readonly statusReason?: string;\n}\n\n/**\n * Accept a Stryker JSON mutation report and return a normalized\n * `PersistedSarif` document with one finding per surviving mutant\n * and per uncovered mutant.\n *\n * @param input Raw Stryker report (string or parsed object).\n * @returns Adapter result.\n * @throws When the input is not a Stryker mutation report.\n */\nexport function adaptStryker(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:stryker] expected a JSON object`);\n }\n const report = parsed as StrykerReport;\n if (!report.files || typeof report.files !== \"object\") {\n throw new Error(`[adapter:stryker] report is missing a files{} map`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const [filename, fileReport] of Object.entries(report.files)) {\n const mutants = Array.isArray(fileReport?.mutants) ? fileReport.mutants : [];\n for (const mutant of mutants) {\n const level = classifyMutant(mutant.status);\n if (level === null) continue; // Killed / Ignored / CompileError \u2014 not a defect\n const startLine = mutant.location?.start?.line ?? 1;\n const startColumn = mutant.location?.start?.column ?? 1;\n const endLine = mutant.location?.end?.line;\n const endColumn = mutant.location?.end?.column;\n\n // Surviving mutants cost more to fix than the default error\n // budget because the agent has to first write a killing test,\n // THEN possibly rewrite the code.\n const effortOverride = level === \"error\" ? 45 : 15;\n const effort = estimateEffortMinutes(level, effortOverride);\n totalEffortMinutes += effort;\n\n const mutator = mutant.mutatorName ?? \"Unknown\";\n const ruleId = `stryker.${mutator}`;\n const statusText = mutant.status ?? \"Unknown\";\n const message =\n `${statusText}: ${mutator} mutant on '${mutant.replacement ?? \"?\"}'` +\n (mutant.statusReason ? ` \u2014 ${mutant.statusReason}` : \"\");\n\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message,\n uri: filename,\n startLine,\n startColumn,\n endLine: typeof endLine === \"number\" ? endLine : undefined,\n endColumn: typeof endColumn === \"number\" ? endColumn : undefined,\n effortMinutes: effort,\n mutantId: mutant.id,\n mutator,\n mutantStatus: statusText,\n }),\n );\n }\n }\n\n return {\n document: wrapResultsInSarif(STRYKER, String(report.schemaVersion ?? \"unknown\"), results),\n sourceTool: STRYKER,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Classify a Stryker mutant status into a SARIF level, or `null` when\n * the status represents a mutant that was correctly handled by the\n * test suite and should not produce a finding.\n */\nfunction classifyMutant(status: string | undefined): SarifLevel | null {\n switch ((status ?? \"\").toLowerCase()) {\n case \"survived\":\n return \"error\";\n case \"nocoverage\":\n return \"warning\";\n case \"timeout\":\n // Timeout mutants are suspicious but not proof of defect \u2014\n // they deserve a note so the dashboard highlights them.\n return \"note\";\n case \"killed\":\n case \"ignored\":\n case \"compileerror\":\n case \"runtimeerror\":\n default:\n return null;\n }\n}\n\n/**\n * Build the SARIF `result` object for a single Stryker mutant. We\n * propagate the mutant id, mutator name, and raw status into\n * `properties` so the dashboard can display them as tags.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n endLine?: number | undefined;\n endColumn?: number | undefined;\n effortMinutes: number;\n mutantId?: string | undefined;\n mutator?: string | undefined;\n mutantStatus?: string | undefined;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n ...(opts.endLine !== undefined ? { endLine: opts.endLine } : {}),\n ...(opts.endColumn !== undefined ? { endColumn: opts.endColumn } : {}),\n },\n },\n },\n ],\n properties: {\n sourceTool: STRYKER,\n effortMinutes: opts.effortMinutes,\n ...(opts.mutantId ? { mutantId: opts.mutantId } : {}),\n ...(opts.mutator ? { mutator: opts.mutator } : {}),\n ...(opts.mutantStatus ? { mutantStatus: opts.mutantStatus } : {}),\n },\n };\n}\n", "/**\n * Adapter: `dart analyze --format=json` \u2192 SARIF 2.1.0.\n *\n * The Dart analyzer emits JSON with this shape:\n *\n * {\n * \"version\": 1,\n * \"diagnostics\": [\n * {\n * \"code\": \"unused_import\",\n * \"severity\": \"WARNING\",\n * \"type\": \"STATIC_WARNING\",\n * \"location\": {\n * \"file\": \"/absolute/path/to/file.dart\",\n * \"range\": {\n * \"start\": { \"offset\": 7, \"line\": 1, \"column\": 8 },\n * \"end\": { \"offset\": 16, \"line\": 1, \"column\": 17 }\n * }\n * },\n * \"problemMessage\": \"Unused import: 'dart:io'.\",\n * \"correctionMessage\": \"Try removing the import directive.\",\n * \"documentation\": \"https://dart.dev/diagnostics/unused_import\"\n * }\n * ]\n * }\n *\n * Severity mapping:\n * - \"ERROR\" \u2192 SARIF \"error\" (30 min effort)\n * - \"WARNING\" \u2192 SARIF \"warning\" (15 min effort)\n * - \"INFO\" \u2192 SARIF \"note\" (5 min effort)\n *\n * @module adapters/dart-analyzer\n */\n\nimport {\n type AdapterResult,\n wrapResultsInSarif,\n estimateEffortMinutes,\n} from \"./common.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface DartDiagnosticLocation {\n file: string;\n range: {\n start: { offset: number; line: number; column: number };\n end: { offset: number; line: number; column: number };\n };\n}\n\ninterface DartDiagnostic {\n code: string;\n severity: string;\n type: string;\n location: DartDiagnosticLocation;\n problemMessage: string;\n correctionMessage?: string;\n documentation?: string;\n}\n\ninterface DartAnalyzeOutput {\n version: number;\n diagnostics: DartDiagnostic[];\n}\n\n// \u2500\u2500 Severity mapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction mapSeverity(dartSeverity: string): SarifLevel {\n switch (dartSeverity.toUpperCase()) {\n case \"ERROR\":\n return \"error\";\n case \"WARNING\":\n return \"warning\";\n case \"INFO\":\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n// \u2500\u2500 Effort estimates per severity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst EFFORT_BY_SEVERITY: Record<SarifLevel, number> = {\n error: 30,\n warning: 15,\n note: 5,\n none: 0,\n};\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Convert `dart analyze --format=json` output to SARIF 2.1.0.\n *\n * @param rawOutput The JSON string or pre-parsed object from `dart analyze`.\n */\nexport function adaptDartAnalyzer(rawOutput: unknown): AdapterResult {\n let parsed: DartAnalyzeOutput;\n\n if (typeof rawOutput === \"string\") {\n try {\n parsed = JSON.parse(rawOutput) as DartAnalyzeOutput;\n } catch {\n throw new Error(\"[dart-analyzer adapter] rawOutput is not valid JSON\");\n }\n } else if (rawOutput && typeof rawOutput === \"object\" && \"diagnostics\" in rawOutput) {\n parsed = rawOutput as DartAnalyzeOutput;\n } else {\n throw new Error(\n \"[dart-analyzer adapter] rawOutput must be a JSON string or an object with a 'diagnostics' array\",\n );\n }\n\n if (!Array.isArray(parsed.diagnostics)) {\n throw new Error(\"[dart-analyzer adapter] 'diagnostics' must be an array\");\n }\n\n const results: object[] = [];\n let totalEffortMinutes = 0;\n\n for (const diag of parsed.diagnostics) {\n const level = mapSeverity(diag.severity);\n const effort = EFFORT_BY_SEVERITY[level] ?? estimateEffortMinutes(level);\n totalEffortMinutes += effort;\n\n results.push({\n ruleId: diag.code,\n level,\n message: {\n text: diag.problemMessage + (diag.correctionMessage ? ` ${diag.correctionMessage}` : \"\"),\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: diag.location.file,\n },\n region: {\n startLine: diag.location.range.start.line,\n startColumn: diag.location.range.start.column,\n endLine: diag.location.range.end.line,\n endColumn: diag.location.range.end.column,\n },\n },\n },\n ],\n properties: {\n effortMinutes: effort,\n ...(diag.documentation ? { helpUri: diag.documentation } : {}),\n },\n });\n }\n\n return {\n document: wrapResultsInSarif(\"dart_analyze\", \"1.0.0\", results),\n sourceTool: \"dart_analyze\",\n findingCount: parsed.diagnostics.length,\n totalEffortMinutes,\n };\n}\n", "/**\n * Adapter: `dotnet format --report <path>` JSON output \u2192 SARIF 2.1.0.\n *\n * The dotnet format tool emits a JSON array with this shape:\n *\n * [\n * {\n * \"DocumentId\": { \"ProjectId\": { \"Id\": \"...\" }, \"Id\": \"...\" },\n * \"FileName\": \"AuthController.cs\",\n * \"FilePath\": \"/absolute/path/to/AuthController.cs\",\n * \"FileChanges\": [\n * {\n * \"LineNumber\": 84,\n * \"CharNumber\": 16,\n * \"DiagnosticId\": \"WHITESPACE\",\n * \"FormatDescription\": \"Fix whitespace formatting. Delete 5 characters.\"\n * }\n * ]\n * }\n * ]\n *\n * All dotnet format findings are style/formatting issues, so they\n * map uniformly to SARIF \"warning\" level with a 5-minute effort\n * estimate (formatting fixes are quick, mechanical changes).\n *\n * @module adapters/dotnet-format\n */\n\nimport {\n type AdapterResult,\n wrapResultsInSarif,\n} from \"./common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface DotnetFileChange {\n LineNumber: number;\n CharNumber: number;\n DiagnosticId: string;\n FormatDescription: string;\n}\n\ninterface DotnetFormatDocument {\n DocumentId: {\n ProjectId: { Id: string };\n Id: string;\n };\n FileName: string;\n FilePath: string;\n FileChanges: DotnetFileChange[];\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Convert `dotnet format --report <path>` JSON output to SARIF 2.1.0.\n *\n * @param rawOutput The JSON string or pre-parsed array from `dotnet format`.\n */\nexport function adaptDotnetFormat(rawOutput: unknown): AdapterResult {\n let parsed: DotnetFormatDocument[];\n\n if (typeof rawOutput === \"string\") {\n try {\n parsed = JSON.parse(rawOutput) as DotnetFormatDocument[];\n } catch {\n throw new Error(\"[dotnet-format adapter] rawOutput is not valid JSON\");\n }\n } else if (Array.isArray(rawOutput)) {\n parsed = rawOutput as DotnetFormatDocument[];\n } else {\n throw new Error(\n \"[dotnet-format adapter] rawOutput must be a JSON string or an array of document entries\",\n );\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(\"[dotnet-format adapter] parsed output must be an array\");\n }\n\n const EFFORT_MINUTES = 5;\n const results: object[] = [];\n let findingCount = 0;\n let totalEffortMinutes = 0;\n\n for (const doc of parsed) {\n if (!Array.isArray(doc.FileChanges)) continue;\n\n for (const change of doc.FileChanges) {\n findingCount++;\n totalEffortMinutes += EFFORT_MINUTES;\n\n results.push({\n ruleId: change.DiagnosticId,\n level: \"warning\",\n message: {\n text: change.FormatDescription,\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: doc.FilePath,\n },\n region: {\n startLine: change.LineNumber,\n startColumn: change.CharNumber,\n },\n },\n },\n ],\n properties: {\n effortMinutes: EFFORT_MINUTES,\n },\n });\n }\n }\n\n return {\n document: wrapResultsInSarif(\"dotnet_format\", \"1.0.0\", results),\n sourceTool: \"dotnet_format\",\n findingCount,\n totalEffortMinutes,\n };\n}\n", "/**\n * Public SDK entry point for the per-scanner SARIF adapters.\n *\n * Adapters convert a scanner's native output (SARIF, JSON, or some\n * other structured format) into a normalized `PersistedSarif`\n * document that the `SarifStore` can ingest directly. Every adapter\n * enriches its findings with a stable `effortMinutes` value on the\n * `properties` bag so the Stop quality gate and the project score\n * engine can compute a Technical Debt Ratio.\n *\n * Usage:\n *\n * ```ts\n * import {\n * adaptScannerOutput,\n * adaptSemgrep,\n * adaptEslint,\n * adaptBandit,\n * adaptStryker,\n * } from \"claude-crap/adapters\";\n *\n * const result = adaptScannerOutput(\"eslint\", rawJsonFromEslint);\n * sarifStore.ingestRun(result.document, result.sourceTool);\n * ```\n *\n * @module adapters\n */\n\nexport { adaptSemgrep } from \"./semgrep.js\";\nexport { adaptEslint } from \"./eslint.js\";\nexport { adaptBandit } from \"./bandit.js\";\nexport { adaptStryker } from \"./stryker.js\";\nexport { adaptDartAnalyzer } from \"./dart-analyzer.js\";\nexport { adaptDotnetFormat } from \"./dotnet-format.js\";\n\nexport {\n DEFAULT_EFFORT_BY_SEVERITY,\n KNOWN_SCANNERS,\n estimateEffortMinutes,\n wrapResultsInSarif,\n} from \"./common.js\";\n\nexport type { AdapterResult, KnownScanner } from \"./common.js\";\n\nimport { adaptSemgrep } from \"./semgrep.js\";\nimport { adaptEslint } from \"./eslint.js\";\nimport { adaptBandit } from \"./bandit.js\";\nimport { adaptStryker } from \"./stryker.js\";\nimport { adaptDartAnalyzer } from \"./dart-analyzer.js\";\nimport { adaptDotnetFormat } from \"./dotnet-format.js\";\nimport type { AdapterResult, KnownScanner } from \"./common.js\";\n\n/**\n * Route a raw scanner output to the correct adapter based on its\n * name. Preferred entry point for the `ingest_scanner_output` MCP\n * tool \u2014 the dispatch is a single switch so the compiler can verify\n * every case with `never` exhaustiveness.\n *\n * @param scanner One of the known scanner identifiers.\n * @param rawOutput The scanner's native output (string or parsed).\n * @returns A normalized `AdapterResult`.\n * @throws When `scanner` is unknown or the raw output is malformed.\n */\nexport function adaptScannerOutput(\n scanner: KnownScanner,\n rawOutput: unknown,\n): AdapterResult {\n switch (scanner) {\n case \"semgrep\":\n return adaptSemgrep(rawOutput);\n case \"eslint\":\n return adaptEslint(rawOutput);\n case \"bandit\":\n return adaptBandit(rawOutput);\n case \"stryker\":\n return adaptStryker(rawOutput);\n case \"dart_analyze\":\n return adaptDartAnalyzer(rawOutput);\n case \"dotnet_format\":\n return adaptDotnetFormat(rawOutput);\n default: {\n const exhaustive: never = scanner;\n throw new Error(`[adapters] Unknown scanner: ${String(exhaustive)}`);\n }\n }\n}\n", "/**\n * Tree-sitter based AST analysis engine.\n *\n * This module wraps `web-tree-sitter` (the WASM build of tree-sitter) to\n * parse source files and extract deterministic per-function metrics. The\n * WASM variant is used instead of the native bindings so that `npm install`\n * never has to invoke a C compiler \u2014 matching the plugin's \"zero install\n * friction\" promise.\n *\n * The engine is lazy:\n *\n * - `web-tree-sitter` is initialized only on first use.\n * - Grammar WASM files are loaded on demand and cached per language.\n *\n * This keeps MCP server startup fast (crucial because Claude Code will\n * spin the server up and tear it down across sessions).\n *\n * Usage:\n *\n * ```ts\n * const engine = new TreeSitterEngine();\n * const result = await engine.analyzeFile({\n * filePath: \"src/foo.ts\",\n * language: \"typescript\",\n * });\n * console.log(result.functions);\n * ```\n *\n * @module ast/tree-sitter-engine\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { computeCyclomaticComplexity, type AstNode } from \"./cyclomatic.js\";\nimport { LANGUAGE_TABLE, type LanguageConfig, type SupportedLanguage } from \"./language-config.js\";\n\n/**\n * Minimal typed view of the `web-tree-sitter` Parser class and its\n * static helpers. The npm package uses `export = Parser` (a CommonJS\n * default export), so under ESM interop `await import('web-tree-sitter')`\n * returns `{ default: Parser }` where `Parser`:\n *\n * - is a constructable class (`new Parser()`)\n * - exposes `static init(moduleOptions)` to bootstrap the WASM runtime\n * - exposes the nested `Parser.Language.load(pathOrBytes)` static\n * to load a grammar from a `.wasm` file or a raw byte buffer\n *\n * We model that surface here so downstream consumers of this engine are\n * not forced to import `web-tree-sitter` types directly.\n */\ninterface ParserInstance {\n setLanguage(language: unknown): void;\n parse(source: string): { rootNode: AstNode };\n}\n\ninterface ParserCtor {\n new (): ParserInstance;\n init(options?: { locateFile?: (name: string) => string }): Promise<void>;\n Language: { load(path: string | Uint8Array): Promise<unknown> };\n}\n\n/**\n * Per-function metrics returned by the engine.\n */\nexport interface FunctionMetrics {\n /** Human-readable function name, or `\"<anonymous>\"` when not available. */\n readonly name: string;\n /** 1-based line where the function body starts. */\n readonly startLine: number;\n /** 1-based line where the function body ends. */\n readonly endLine: number;\n /** McCabe cyclomatic complexity (always \u2265 1). */\n readonly cyclomaticComplexity: number;\n /** Physical lines of code covered by the function (endLine - startLine + 1). */\n readonly lineCount: number;\n}\n\n/**\n * File-level metrics returned by the engine.\n */\nexport interface FileMetrics {\n /** File path that was analyzed, echoed from the request for traceability. */\n readonly filePath: string;\n /** Language the file was parsed as. */\n readonly language: SupportedLanguage;\n /** Total physical lines in the file, including blanks and comments. */\n readonly physicalLoc: number;\n /** Physical lines that contain at least one non-whitespace character. */\n readonly logicalLoc: number;\n /** Per-function metrics sorted by starting line. */\n readonly functions: ReadonlyArray<FunctionMetrics>;\n}\n\n/**\n * Request accepted by {@link TreeSitterEngine.analyzeFile}.\n */\nexport interface AnalyzeFileRequest {\n readonly filePath: string;\n readonly language: SupportedLanguage;\n}\n\n/**\n * Options accepted by the engine constructor. All fields are optional and\n * safe defaults are used when omitted.\n */\nexport interface TreeSitterEngineOptions {\n /**\n * Directory where the language grammar WASM files live (one per\n * language, e.g. `tree-sitter-typescript.wasm`). Defaults to the\n * `tree-sitter-wasms/out` directory inside `node_modules`.\n */\n readonly grammarsDir?: string;\n /**\n * Directory where the `web-tree-sitter` runtime WASM (`tree-sitter.wasm`)\n * lives. This is a different package from the grammars \u2014 the runtime\n * ships with `web-tree-sitter` itself. Defaults to that package's\n * install directory inside `node_modules`.\n */\n readonly runtimeDir?: string;\n /**\n * Override the WASM loader for tests. Receives the grammar filename\n * and must return the raw bytes.\n */\n readonly loadGrammar?: (wasmPath: string) => Promise<Uint8Array>;\n}\n\n/**\n * High-level AST engine. Instances are meant to be long-lived \u2014 create\n * one at server startup and reuse it for every analysis request.\n */\nexport class TreeSitterEngine {\n private parserCtor: ParserCtor | null = null;\n private readonly loadedLanguages = new Map<SupportedLanguage, unknown>();\n private readonly grammarsDir: string;\n private readonly runtimeDir: string;\n private readonly loadGrammar: (wasmPath: string) => Promise<Uint8Array>;\n private initPromise: Promise<void> | null = null;\n\n constructor(options: TreeSitterEngineOptions = {}) {\n this.grammarsDir = options.grammarsDir ?? resolveDefaultGrammarsDir();\n this.runtimeDir = options.runtimeDir ?? resolveDefaultRuntimeDir();\n this.loadGrammar = options.loadGrammar ?? ((path) => fs.readFile(path));\n }\n\n /**\n * Analyze a source file and return per-function and file-level metrics.\n *\n * @param req The analysis request.\n * @returns A {@link FileMetrics} snapshot ready to be serialized.\n * @throws When the file cannot be read or the grammar cannot be loaded.\n */\n async analyzeFile(req: AnalyzeFileRequest): Promise<FileMetrics> {\n const languageConfig = LANGUAGE_TABLE[req.language];\n if (!languageConfig) {\n throw new Error(`[tree-sitter-engine] Unsupported language: ${req.language}`);\n }\n\n const source = await fs.readFile(req.filePath, \"utf8\");\n const parser = await this.ensureParserFor(languageConfig);\n const tree = parser.parse(source);\n\n const functions = collectFunctionMetrics(tree.rootNode, languageConfig);\n const { physicalLoc, logicalLoc } = countLines(source);\n\n return {\n filePath: req.filePath,\n language: languageConfig.id,\n physicalLoc,\n logicalLoc,\n functions,\n };\n }\n\n /**\n * Ensure a parser with the requested language grammar bound is ready.\n * Both the Parser class and the grammar are initialized lazily and\n * cached on first use.\n *\n * @param config Language configuration for the requested grammar.\n * @returns A fresh parser instance configured for the language.\n */\n private async ensureParserFor(config: LanguageConfig): Promise<ParserInstance> {\n if (!this.parserCtor) {\n if (!this.initPromise) {\n this.initPromise = this.initParserModule();\n }\n await this.initPromise;\n }\n const Parser = this.parserCtor;\n if (!Parser) {\n throw new Error(\"[tree-sitter-engine] Parser class failed to initialize\");\n }\n\n let language = this.loadedLanguages.get(config.id);\n if (!language) {\n const wasmPath = join(this.grammarsDir, config.wasmName);\n const bytes = await this.loadGrammar(wasmPath);\n language = await Parser.Language.load(bytes);\n this.loadedLanguages.set(config.id, language);\n }\n\n const parser = new Parser();\n parser.setLanguage(language);\n return parser;\n }\n\n /**\n * Import and initialize `web-tree-sitter`. Isolated in its own method\n * so the dynamic import runs exactly once per engine instance.\n *\n * `web-tree-sitter` uses `export = Parser` so under ESM interop the\n * Parser class arrives on the `default` property of the imported\n * namespace. `Parser.init()` is a STATIC method on the class, not a\n * top-level module function.\n */\n private async initParserModule(): Promise<void> {\n const imported = (await import(\"web-tree-sitter\")) as { default: ParserCtor };\n const Parser = imported.default;\n if (!Parser || typeof Parser.init !== \"function\") {\n throw new Error(\n \"[tree-sitter-engine] web-tree-sitter did not expose the expected Parser class\",\n );\n }\n // Emscripten calls `locateFile` to resolve the runtime WASM during\n // `Parser.init()`. The runtime file (`tree-sitter.wasm`) lives inside\n // the `web-tree-sitter` package itself, NOT alongside the grammars,\n // so we route requests for that exact filename to `runtimeDir`.\n // Anything else falls back to `grammarsDir` for the per-language\n // grammar files loaded later by `Parser.Language.load()`.\n await Parser.init({\n locateFile: (name: string) =>\n name === \"tree-sitter.wasm\"\n ? join(this.runtimeDir, name)\n : join(this.grammarsDir, name),\n });\n this.parserCtor = Parser;\n }\n}\n\n/**\n * Resolve the default grammar directory to `tree-sitter-wasms/out` inside\n * `node_modules`. Uses `createRequire` so the lookup works regardless of\n * whether the caller is running from source (`tsx`) or from the built\n * `dist/` directory.\n */\nfunction resolveDefaultGrammarsDir(): string {\n try {\n const requireFromHere = createRequire(import.meta.url);\n // `tree-sitter-wasms` exposes its grammar files under `out/`.\n const pkgJsonPath = requireFromHere.resolve(\"tree-sitter-wasms/package.json\");\n return join(dirname(pkgJsonPath), \"out\");\n } catch {\n // Fall back to a sibling `grammars/` directory if the npm package\n // is not installed \u2014 useful for repo-local grammars.\n const here = dirname(fileURLToPath(import.meta.url));\n return resolve(here, \"..\", \"..\", \"grammars\");\n }\n}\n\n/**\n * Resolve the default runtime directory to the `web-tree-sitter` package\n * root inside `node_modules`. The runtime WASM (`tree-sitter.wasm`) ships\n * with the `web-tree-sitter` package itself rather than with the grammar\n * package, so we have to look it up separately from the grammars.\n */\nfunction resolveDefaultRuntimeDir(): string {\n try {\n const requireFromHere = createRequire(import.meta.url);\n const pkgJsonPath = requireFromHere.resolve(\"web-tree-sitter/package.json\");\n return dirname(pkgJsonPath);\n } catch {\n // Fall back to the grammars directory \u2014 better than nothing if\n // someone is running with a custom layout.\n return resolveDefaultGrammarsDir();\n }\n}\n\n/**\n * Walk the top-level AST and collect metrics for every function node,\n * including nested functions. The caller gets a flat, line-sorted list.\n *\n * @param root AST root node returned by tree-sitter.\n * @param languageConfig Language tables to classify nodes.\n * @returns Flat list of function metrics sorted by start line.\n */\nfunction collectFunctionMetrics(\n root: AstNode,\n languageConfig: LanguageConfig,\n): ReadonlyArray<FunctionMetrics> {\n const out: FunctionMetrics[] = [];\n\n function visit(node: AstNode): void {\n if (languageConfig.functionNodeTypes.has(node.type)) {\n out.push(buildFunctionMetrics(node, languageConfig));\n // Intentionally continue the walk so nested functions are also\n // reported. Each nested function's complexity is computed against\n // its own subtree; cyclomatic.ts skips nested functions during\n // the walk so the parent's score is not inflated.\n }\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (child) visit(child);\n }\n }\n\n visit(root);\n out.sort((a, b) => a.startLine - b.startLine);\n return out;\n}\n\n/**\n * Build a {@link FunctionMetrics} record for a single function node.\n */\nfunction buildFunctionMetrics(node: AstNode, languageConfig: LanguageConfig): FunctionMetrics {\n const name = extractFunctionName(node, languageConfig);\n const position = extractPosition(node);\n const complexity = computeCyclomaticComplexity(node, languageConfig);\n return {\n name,\n startLine: position.startLine,\n endLine: position.endLine,\n cyclomaticComplexity: complexity,\n lineCount: position.endLine - position.startLine + 1,\n };\n}\n\n/**\n * Pull the function name out of a function node. Tree-sitter exposes a\n * `childForFieldName` accessor on its real nodes; we feature-detect it\n * because our minimal {@link AstNode} contract does not require it.\n */\nfunction extractFunctionName(node: AstNode, languageConfig: LanguageConfig): string {\n const anyNode = node as AstNode & {\n childForFieldName?: (field: string) => AstNode | null;\n };\n if (typeof anyNode.childForFieldName === \"function\") {\n for (const field of languageConfig.nameFieldCandidates) {\n const nameNode = anyNode.childForFieldName(field);\n if (nameNode && nameNode.text) return nameNode.text;\n }\n }\n return \"<anonymous>\";\n}\n\n/**\n * Extract 1-based start/end line numbers for a node. Tree-sitter nodes\n * expose `startPosition` and `endPosition` with zero-based rows.\n */\nfunction extractPosition(node: AstNode): { startLine: number; endLine: number } {\n const anyNode = node as AstNode & {\n startPosition?: { row: number };\n endPosition?: { row: number };\n };\n const startRow = anyNode.startPosition?.row ?? 0;\n const endRow = anyNode.endPosition?.row ?? startRow;\n return { startLine: startRow + 1, endLine: endRow + 1 };\n}\n\n/**\n * Count physical and logical lines of code in a raw source string.\n *\n * - **Physical LOC**: number of newline-separated lines, matching how\n * most IDEs report file length.\n * - **Logical LOC**: number of lines that contain at least one\n * non-whitespace character.\n *\n * Comment detection is intentionally NOT done here; comment stripping\n * requires language-aware parsing and the caller can derive a comment\n * ratio from the AST node list if needed.\n *\n * @param source Raw source text.\n * @returns An object with `physicalLoc` and `logicalLoc`.\n */\nfunction countLines(source: string): { physicalLoc: number; logicalLoc: number } {\n if (source.length === 0) return { physicalLoc: 0, logicalLoc: 0 };\n const lines = source.split(/\\r?\\n/);\n let logical = 0;\n for (const line of lines) {\n if (line.trim().length > 0) logical += 1;\n }\n return { physicalLoc: lines.length, logicalLoc: logical };\n}\n", "/**\n * Deterministic cyclomatic complexity walker.\n *\n * Given a tree-sitter subtree rooted at a function node, this module walks\n * the tree and returns the McCabe cyclomatic complexity number. The\n * algorithm is the standard \"1 + (branching nodes + short-circuit operators)\"\n * formulation:\n *\n * CC = 1\n * + count of branching-statement nodes (if, while, for, case, catch, ...)\n * + count of short-circuit operators (&&, ||, ??, `and`, `or`)\n * + count of ternary expressions (counted as branching nodes)\n *\n * The baseline of 1 represents the straight-line path through the function.\n * Every additional branching point multiplies the set of reachable paths.\n *\n * The walker is deliberately language-agnostic: it consults the\n * {@link LanguageConfig} passed in to decide which node types to count.\n * Nested functions inside the subtree are **skipped** \u2014 each function's\n * complexity is reported independently by {@link TreeSitterEngine}.\n *\n * @module ast/cyclomatic\n */\n\nimport type { LanguageConfig } from \"./language-config.js\";\n\n/**\n * Minimal structural contract of a tree-sitter node. We intentionally\n * avoid importing `web-tree-sitter` types here so this module stays\n * unit-testable with a hand-rolled mock tree.\n */\nexport interface AstNode {\n /** Node type name from the grammar (e.g. `\"if_statement\"`). */\n readonly type: string;\n /** Raw source text for operator detection. May be large \u2014 do not log. */\n readonly text: string;\n /** Zero-based child count. */\n readonly childCount: number;\n /** Retrieve a child by index. Returns `null` if out of range. */\n child(index: number): AstNode | null;\n}\n\n/**\n * Compute the cyclomatic complexity of a function subtree.\n *\n * @param root Node rooted at the function (method, arrow, lambda, ...).\n * @param languageConfig Language classification tables for node types.\n * @returns The McCabe cyclomatic complexity (always \u2265 1).\n */\nexport function computeCyclomaticComplexity(root: AstNode, languageConfig: LanguageConfig): number {\n let complexity = 1;\n walk(root, languageConfig, true, (node) => {\n if (languageConfig.branchingNodeTypes.has(node.type)) {\n complexity += 1;\n return;\n }\n // Boolean / short-circuit operators are usually represented as\n // \"binary_expression\" nodes with an operator token child. To avoid\n // coupling to a specific grammar's node shape, we inspect the raw\n // text of the node's direct operator child.\n if (isBooleanExpression(node, languageConfig)) {\n complexity += 1;\n return;\n }\n });\n return complexity;\n}\n\n/**\n * Depth-first walk that skips any nested function subtree so that its\n * complexity is not attributed to the enclosing function.\n *\n * @param node Current node being visited.\n * @param languageConfig Language tables used to detect nested functions.\n * @param isRoot `true` for the starting node (we do not skip it).\n * @param visit Callback invoked for every non-function descendant.\n */\nfunction walk(\n node: AstNode,\n languageConfig: LanguageConfig,\n isRoot: boolean,\n visit: (n: AstNode) => void,\n): void {\n if (!isRoot && languageConfig.functionNodeTypes.has(node.type)) {\n // Nested function \u2014 stop the walk here. Its complexity is reported\n // separately when the engine iterates the top-level function list.\n return;\n }\n visit(node);\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (child) walk(child, languageConfig, false, visit);\n }\n}\n\n/**\n * Return `true` when `node` is a boolean / short-circuit expression that\n * should add one to the cyclomatic complexity. We inspect the node's\n * immediate children for an operator token whose text matches one of the\n * language's short-circuit operators.\n *\n * This is a heuristic \u2014 grammars differ in how they represent operators\n * \u2014 but it is stable enough for the five supported languages because:\n *\n * - JavaScript / TypeScript / Java: binary expression with `\"&&\"` or `\"||\"` token child.\n * - Python: `boolean_operator` node with `\"and\"` / `\"or\"` token child.\n * - C#: binary expression with `\"&&\"`, `\"||\"`, or `\"??\"` token child.\n *\n * @param node Candidate node.\n * @param languageConfig Tables with the language's boolean operator set.\n * @returns `true` when the node is a counted boolean expression.\n */\nfunction isBooleanExpression(node: AstNode, languageConfig: LanguageConfig): boolean {\n // Common type names across supported grammars. We check the type first\n // to avoid scanning text for every node in the tree.\n if (\n node.type !== \"binary_expression\" &&\n node.type !== \"boolean_operator\" &&\n node.type !== \"logical_expression\"\n ) {\n return false;\n }\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (!child) continue;\n if (languageConfig.booleanOperators.includes(child.text)) {\n return true;\n }\n }\n return false;\n}\n", "/**\n * Per-language tree-sitter node classification tables.\n *\n * Every language grammar exposes a different set of node type names. To\n * keep the AST engine language-agnostic we encode, for each supported\n * language, three sets:\n *\n * - `functionNodeTypes` \u2014 nodes that represent a function/method/lambda.\n * These are the units we report metrics for.\n * - `branchingNodeTypes` \u2014 nodes that add one independent path through\n * the function. Used to compute cyclomatic\n * complexity by counting occurrences.\n * - `nameField` \u2014 the tree-sitter field name that holds the\n * function's identifier, used to extract the\n * function name for reporting.\n *\n * We also define which WASM grammar file to load per language. The paths\n * are resolved at runtime against the `tree-sitter-wasms` package, but\n * can be overridden via the engine constructor if you want to ship your\n * own grammars.\n *\n * @module ast/language-config\n */\n\n/**\n * Languages currently supported by the AST engine. This is the same\n * `enum` that appears in the `analyze_file_ast` tool schema \u2014 keep them\n * in sync when adding a new language.\n */\nexport type SupportedLanguage = \"csharp\" | \"javascript\" | \"typescript\" | \"python\" | \"java\";\n\n/**\n * Per-language classification record. Immutable by convention.\n */\nexport interface LanguageConfig {\n /** Canonical language identifier (stable across releases). */\n readonly id: SupportedLanguage;\n /** WASM grammar filename inside `tree-sitter-wasms/out/`. */\n readonly wasmName: string;\n /** File extensions that should map to this language. */\n readonly extensions: ReadonlyArray<string>;\n /** Tree-sitter node types that represent callable units. */\n readonly functionNodeTypes: ReadonlySet<string>;\n /** Tree-sitter node types that add +1 to cyclomatic complexity. */\n readonly branchingNodeTypes: ReadonlySet<string>;\n /**\n * Boolean / short-circuit operator node types. These are counted only\n * when the node is an `\"&&\"`, `\"||\"`, `\"??\"` (etc.) operator, so the\n * walker inspects the operator text on top of the node type.\n */\n readonly booleanOperators: ReadonlyArray<string>;\n /**\n * Child-field names we try in order to extract the function name. The\n * walker reads the first non-empty match.\n */\n readonly nameFieldCandidates: ReadonlyArray<string>;\n}\n\n// -----------------------------------------------------------------------------\n// C#\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-c-sharp\nconst CSHARP: LanguageConfig = {\n id: \"csharp\",\n wasmName: \"tree-sitter-c_sharp.wasm\",\n extensions: [\".cs\"],\n functionNodeTypes: new Set([\n \"method_declaration\",\n \"local_function_statement\",\n \"lambda_expression\",\n \"anonymous_method_expression\",\n \"constructor_declaration\",\n \"destructor_declaration\",\n \"operator_declaration\",\n \"conversion_operator_declaration\",\n \"accessor_declaration\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"else_clause\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"for_each_statement\",\n \"case_switch_label\",\n \"case_pattern_switch_label\",\n \"switch_expression_arm\",\n \"catch_clause\",\n \"conditional_expression\",\n \"conditional_access_expression\",\n \"when_clause\",\n ]),\n booleanOperators: [\"&&\", \"||\", \"??\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// JavaScript\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-javascript\nconst JAVASCRIPT: LanguageConfig = {\n id: \"javascript\",\n wasmName: \"tree-sitter-javascript.wasm\",\n extensions: [\".js\", \".jsx\", \".mjs\", \".cjs\"],\n functionNodeTypes: new Set([\n \"function_declaration\",\n \"function_expression\",\n \"arrow_function\",\n \"method_definition\",\n \"generator_function\",\n \"generator_function_declaration\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"else_clause\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"for_in_statement\",\n \"for_of_statement\",\n \"switch_case\",\n \"catch_clause\",\n \"ternary_expression\",\n ]),\n booleanOperators: [\"&&\", \"||\", \"??\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// TypeScript\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-typescript\n// The TypeScript grammar inherits most node types from JavaScript, so we\n// extend the JS tables rather than re-declaring them from scratch.\nconst TYPESCRIPT: LanguageConfig = {\n id: \"typescript\",\n wasmName: \"tree-sitter-typescript.wasm\",\n extensions: [\".ts\", \".tsx\", \".mts\", \".cts\"],\n functionNodeTypes: new Set([\n ...JAVASCRIPT.functionNodeTypes,\n \"function_signature\",\n \"method_signature\",\n \"abstract_method_signature\",\n ]),\n branchingNodeTypes: new Set([...JAVASCRIPT.branchingNodeTypes]),\n booleanOperators: [...JAVASCRIPT.booleanOperators],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// Python\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-python\nconst PYTHON: LanguageConfig = {\n id: \"python\",\n wasmName: \"tree-sitter-python.wasm\",\n extensions: [\".py\", \".pyi\"],\n functionNodeTypes: new Set([\"function_definition\", \"lambda\"]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"elif_clause\",\n \"else_clause\",\n \"while_statement\",\n \"for_statement\",\n \"try_statement\",\n \"except_clause\",\n \"conditional_expression\",\n \"match_statement\",\n \"case_clause\",\n ]),\n booleanOperators: [\"and\", \"or\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// Java\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-java\nconst JAVA: LanguageConfig = {\n id: \"java\",\n wasmName: \"tree-sitter-java.wasm\",\n extensions: [\".java\"],\n functionNodeTypes: new Set([\n \"method_declaration\",\n \"constructor_declaration\",\n \"lambda_expression\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"enhanced_for_statement\",\n \"switch_label\",\n \"switch_rule\",\n \"catch_clause\",\n \"ternary_expression\",\n ]),\n booleanOperators: [\"&&\", \"||\"],\n nameFieldCandidates: [\"name\"],\n};\n\n/**\n * Complete language table. Look up by {@link SupportedLanguage} identifier.\n */\nexport const LANGUAGE_TABLE: Readonly<Record<SupportedLanguage, LanguageConfig>> = {\n csharp: CSHARP,\n javascript: JAVASCRIPT,\n typescript: TYPESCRIPT,\n python: PYTHON,\n java: JAVA,\n};\n\n/**\n * Infer a {@link SupportedLanguage} from a file path by matching its\n * extension. Returns `null` when no known language matches. Useful when\n * the caller does not already know the language and wants the engine to\n * pick one automatically.\n *\n * @param filePath File path (absolute or relative).\n * @returns The detected language or `null`.\n */\nexport function detectLanguageFromPath(filePath: string): SupportedLanguage | null {\n const lower = filePath.toLowerCase();\n for (const config of Object.values(LANGUAGE_TABLE)) {\n for (const ext of config.extensions) {\n if (lower.endsWith(ext)) return config.id;\n }\n }\n return null;\n}\n", "/**\n * Deterministic configuration loader for the claude-crap MCP server.\n *\n * Every tunable knob is read from environment variables that are injected\n * by `.mcp.json` at server startup. Those variables are themselves derived\n * from the `CLAUDE_PLUGIN_OPTION_*` values defined in the plugin manifest,\n * which means the configuration chain is:\n *\n * user settings \u2192 plugin.json \"options\" \u2192 .mcp.json \"env\" \u2192 this file\n *\n * If any environment variable is missing or empty, a safe default is used,\n * but the loader NEVER invents stochastic values and NEVER performs I/O.\n * This module is the single source of truth for runtime configuration.\n *\n * @module config\n */\n\n/**\n * Maintainability rating letter grades used throughout claude-crap.\n *\n * The ordering is strict: A is best, E is worst. Callers that need to\n * compare two ratings should use {@link ratingToRank} from `metrics/tdr.ts`\n * rather than comparing the letters directly.\n */\nexport type MaintainabilityRating = \"A\" | \"B\" | \"C\" | \"D\" | \"E\";\n\n/**\n * Fully resolved configuration object consumed by every subsystem of the\n * MCP server. Fields are `readonly` so that downstream code cannot mutate\n * configuration at runtime \u2014 any change must go through a server restart.\n */\nexport interface CrapConfig {\n /** Absolute path to the plugin root on disk. Defaults to `process.cwd()`. */\n readonly pluginRoot: string;\n /** Directory (relative to the workspace) where consolidated SARIF reports are written. */\n readonly sarifOutputDir: string;\n /** Hard block threshold for the CRAP index. Functions above this fail the Stop quality gate. */\n readonly crapThreshold: number;\n /** Maximum cyclomatic complexity allowed per function before warnings fire. */\n readonly cyclomaticMax: number;\n /** Highest (worst) maintainability rating the project is allowed to hold. */\n readonly tdrMaxRating: MaintainabilityRating;\n /** Assumed development cost per line of code, in minutes. Used as the TDR denominator. */\n readonly minutesPerLoc: number;\n /** Local TCP port the Vue.js dashboard will bind to. */\n readonly dashboardPort: number;\n}\n\n/**\n * Parse a numeric environment variable, falling back to `fallback` when the\n * variable is undefined or empty. Throws if the value is present but not a\n * finite number \u2014 we prefer a loud startup failure over silently using a\n * wrong threshold.\n *\n * @param name Environment variable name, used only for the error message.\n * @param raw Raw value read from `process.env`.\n * @param fallback Default value used when `raw` is undefined/empty.\n * @returns The parsed number.\n * @throws When `raw` is present but not a finite number.\n */\nfunction parseNumber(name: string, raw: string | undefined, fallback: number): number {\n if (raw === undefined || raw === \"\") return fallback;\n const value = Number(raw);\n if (!Number.isFinite(value)) {\n throw new Error(`[claude-crap] Env ${name}=\"${raw}\" is not a finite number`);\n }\n return value;\n}\n\n/**\n * Parse a maintainability rating from an environment variable. Accepts any\n * casing (`a`, `A`, ` a ` all become `\"A\"`). Throws on invalid letters so\n * the server refuses to start rather than running with an unknown policy.\n *\n * @param raw Raw value read from `process.env`.\n * @param fallback Default rating used when `raw` is undefined.\n * @returns A validated {@link MaintainabilityRating}.\n * @throws When `raw` is a non-empty string that is not A..E.\n */\nfunction parseRating(raw: string | undefined, fallback: MaintainabilityRating): MaintainabilityRating {\n if (!raw) return fallback;\n const normalized = raw.trim().toUpperCase();\n if (![\"A\", \"B\", \"C\", \"D\", \"E\"].includes(normalized)) {\n throw new Error(`[claude-crap] TDR_MAX_RATING=\"${raw}\" must be one of A, B, C, D, E`);\n }\n return normalized as MaintainabilityRating;\n}\n\n/**\n * Build the complete {@link CrapConfig} from the current process environment.\n *\n * This should be called exactly once at server startup. Subsequent callers\n * that need configuration should accept a `CrapConfig` parameter instead\n * of re-reading from `process.env`, so that tests can inject custom values.\n *\n * @returns A fully validated, immutable configuration object.\n * @throws When any environment variable is present but malformed.\n */\nexport function loadConfig(): CrapConfig {\n return {\n pluginRoot: process.env.CLAUDE_CRAP_PLUGIN_ROOT ?? process.cwd(),\n sarifOutputDir: process.env.CLAUDE_CRAP_SARIF_OUTPUT_DIR ?? \".claude-crap/reports\",\n crapThreshold: parseNumber(\"CLAUDE_CRAP_CRAP_THRESHOLD\", process.env.CLAUDE_CRAP_CRAP_THRESHOLD, 30),\n cyclomaticMax: parseNumber(\"CLAUDE_CRAP_CYCLOMATIC_MAX\", process.env.CLAUDE_CRAP_CYCLOMATIC_MAX, 15),\n tdrMaxRating: parseRating(process.env.CLAUDE_CRAP_TDR_MAX_RATING, \"C\"),\n minutesPerLoc: parseNumber(\"CLAUDE_CRAP_MINUTES_PER_LOC\", process.env.CLAUDE_CRAP_MINUTES_PER_LOC, 30),\n dashboardPort: parseNumber(\"CLAUDE_CRAP_DASHBOARD_PORT\", process.env.CLAUDE_CRAP_DASHBOARD_PORT, 5117),\n };\n}\n", "/**\n * Local Vue.js dashboard for claude-crap \u2014 Fastify HTTP server.\n *\n * The dashboard runs in the same Node.js process as the MCP server,\n * but on a separate TCP port (default 5117). It exposes:\n *\n * GET / \u2192 static index.html (Vue 3 SPA from CDN)\n * GET /api/score \u2192 live ProjectScore JSON from the score engine\n * GET /api/sarif \u2192 consolidated SARIF 2.1.0 document\n * GET /api/health \u2192 simple {status:\"ok\"} liveness probe\n *\n * The server binds to `127.0.0.1` only \u2014 never to `0.0.0.0` \u2014 so the\n * dashboard cannot be reached from outside the developer's machine.\n *\n * If the configured port is already in use (or the bind otherwise\n * fails), `startDashboard()` rejects gracefully and the caller falls\n * back to \"no dashboard\". The MCP server will keep running.\n *\n * IMPORTANT: this module never writes to stdout. The MCP stdio\n * transport reserves stdout for JSON-RPC framing, so all logs and\n * errors here go through the same pino-on-stderr instance the rest of\n * the server uses.\n *\n * @module dashboard/server\n */\n\nimport { promises as fs, existsSync, readFileSync, writeFileSync, unlinkSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport Fastify, { type FastifyInstance } from \"fastify\";\nimport fastifyStatic from \"@fastify/static\";\nimport type { Logger } from \"pino\";\n\nimport type { CrapConfig } from \"../config.js\";\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\nimport {\n computeProjectScore,\n type ProjectScore,\n type WorkspaceStats,\n} from \"../metrics/score.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport type { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport { detectLanguageFromPath } from \"../ast/language-config.js\";\nimport { buildFileDetail } from \"./file-detail.js\";\n\n/**\n * Callback used by the dashboard to refresh workspace LOC stats on\n * every score request. The MCP server provides this so the dashboard\n * does not have to know how to walk the disk itself.\n */\nexport type WorkspaceStatsProvider = () => Promise<WorkspaceStats>;\n\n/**\n * Inputs accepted by {@link startDashboard}.\n */\nexport interface StartDashboardOptions {\n /** Fully resolved server configuration. */\n readonly config: CrapConfig;\n /** Live SARIF store the dashboard reads findings from. */\n readonly sarifStore: SarifStore;\n /** Function that returns up-to-date LOC + file count for the workspace. */\n readonly workspaceStatsProvider: WorkspaceStatsProvider;\n /** Pino logger from the MCP server (writes to stderr). */\n readonly logger: Logger;\n /** Tree-sitter engine for the /api/complexity endpoint. */\n readonly astEngine?: TreeSitterEngine;\n /** User-defined exclusion patterns from .claude-crap.json. */\n readonly exclude?: ReadonlyArray<string>;\n}\n\n/**\n * Handle returned by {@link startDashboard}. Use `url` to build the\n * link the user clicks; call `close()` during shutdown.\n */\nexport interface DashboardHandle {\n readonly url: string;\n close(): Promise<void>;\n}\n\n/**\n * Boot the Fastify dashboard server. Resolves with a {@link DashboardHandle}\n * once the server is listening, or rejects when the bind fails (caller\n * should treat that as a non-fatal degradation).\n *\n * @param options Configuration, store, and provider callback.\n */\nexport async function startDashboard(options: StartDashboardOptions): Promise<DashboardHandle> {\n const { config, sarifStore, workspaceStatsProvider, logger } = options;\n\n // Resolve the public/ directory. After `npm run build` the compiled\n // server lives in `dist/dashboard/server.js`, but we keep the static\n // SPA assets in `src/dashboard/public/` so we don't need a postbuild\n // copy step. We probe both candidate locations in priority order.\n const publicRoot = await resolvePublicRoot(logger);\n\n const fastify: FastifyInstance = Fastify({\n logger: false, // we route everything through pino-on-stderr ourselves\n disableRequestLogging: true,\n });\n\n await fastify.register(fastifyStatic, {\n root: publicRoot,\n prefix: \"/\",\n });\n\n // ------------------------------------------------------------------\n // /api/health \u2014 liveness probe\n // ------------------------------------------------------------------\n fastify.get(\"/api/health\", async () => ({ status: \"ok\", server: \"claude-crap\", version: \"0.4.0\" }));\n\n // ------------------------------------------------------------------\n // /api/score \u2014 live project score\n // ------------------------------------------------------------------\n fastify.get(\"/api/score\", async () => {\n const stats = await workspaceStatsProvider();\n const score = await buildScore(config, sarifStore, stats, urlOf(fastify, config));\n return score;\n });\n\n // ------------------------------------------------------------------\n // /api/sarif \u2014 consolidated SARIF 2.1.0 document\n // ------------------------------------------------------------------\n fastify.get(\"/api/sarif\", async () => sarifStore.toSarifDocument());\n\n // ------------------------------------------------------------------\n // /api/complexity \u2014 top complex functions across the workspace\n // ------------------------------------------------------------------\n fastify.get(\"/api/complexity\", async () => {\n if (!options.astEngine) {\n return { threshold: config.cyclomaticMax, totalFunctions: 0, violationCount: 0, topFunctions: [] };\n }\n return buildComplexityReport(config, options.astEngine, logger, options.exclude);\n });\n\n // ------------------------------------------------------------------\n // /api/file-detail \u2014 per-file source, metrics, and findings\n // ------------------------------------------------------------------\n fastify.get(\"/api/file-detail\", async (request, reply) => {\n const { path: filePath } = request.query as { path?: string };\n if (!filePath) {\n return reply.status(400).send({ error: \"Missing required query parameter: path\" });\n }\n try {\n const detail = await buildFileDetail({\n relativePath: filePath,\n workspaceRoot: config.pluginRoot,\n astEngine: options.astEngine,\n sarifStore,\n cyclomaticMax: config.cyclomaticMax,\n });\n return detail;\n } catch (err) {\n const msg = (err as Error).message;\n if (msg.includes(\"ENOENT\") || msg.includes(\"not found\")) {\n return reply.status(404).send({ error: `File not found: ${filePath}` });\n }\n if (msg.includes(\"escapes the workspace\")) {\n return reply.status(400).send({ error: msg });\n }\n logger.error({ err: msg, filePath }, \"file-detail endpoint error\");\n return reply.status(500).send({ error: \"Internal server error\" });\n }\n });\n\n // ------------------------------------------------------------------\n // / \u2014 explicit SPA fallback for index.html\n // ------------------------------------------------------------------\n // @fastify/static sometimes doesn't serve index.html on GET / when\n // API routes are registered on the same prefix. Explicit fallback\n // ensures the dashboard always loads.\n fastify.get(\"/\", async (_request, reply) => {\n return reply.sendFile(\"index.html\");\n });\n\n // Kill any stale dashboard from a previous session so we always\n // bind to the configured port. This mirrors claude-mem's PID file\n // pattern: write a PID file when alive, check + kill on next boot.\n const pidFilePath = resolvePidFilePath(config);\n await killStaleDashboard(pidFilePath, config.dashboardPort, logger);\n\n await fastify.listen({ port: config.dashboardPort, host: \"127.0.0.1\" });\n\n const url = `http://127.0.0.1:${config.dashboardPort}`;\n logger.info({ url, publicRoot }, \"claude-crap dashboard listening\");\n\n // Write PID file so the next session can find and kill us.\n writePidFile(pidFilePath, config.dashboardPort);\n\n return {\n url,\n async close() {\n removePidFile(pidFilePath);\n await fastify.close();\n },\n };\n}\n\n/**\n * Probe the candidate public/ directories in priority order and return\n * the first one that contains an `index.html`. Throws when none of the\n * candidates exist \u2014 that points at a packaging mistake the developer\n * should fix immediately.\n *\n * @param logger Pino instance for diagnostics.\n */\nasync function resolvePublicRoot(logger: Logger): Promise<string> {\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // 0. Bundled layout: plugin/bundle/mcp-server.mjs \u2192 ./dashboard/public\n resolve(here, \"dashboard\", \"public\"),\n // 1. Compiled layout: dist/dashboard/server.js \u2192 ./public next to it\n // (only present if a build step copies the assets \u2014 not used\n // today, but accepted so a future copy step does not break us).\n resolve(here, \"public\"),\n // 2. Source-relative layout: dist/dashboard/server.js \u2192 ../../src/dashboard/public\n // This is the default \u2014 no copy step required because we resolve\n // upward from `dist/` into `src/` at runtime.\n resolve(here, \"..\", \"..\", \"src\", \"dashboard\", \"public\"),\n ];\n for (const candidate of candidates) {\n try {\n await fs.access(resolve(candidate, \"index.html\"));\n return candidate;\n } catch {\n // probe next\n }\n }\n logger.error({ candidates }, \"dashboard public/ directory not found\");\n throw new Error(\n `[claude-crap] dashboard: index.html not found in any of ${candidates.join(\", \")}`,\n );\n}\n\n/**\n * Resolve the canonical dashboard URL using the live Fastify address\n * info. Falls back to the configured port when the address info is\n * not yet available (e.g. on the very first request during startup).\n */\nfunction urlOf(fastify: FastifyInstance, config: CrapConfig): string {\n const addresses = fastify.addresses?.() ?? [];\n const first = addresses[0];\n if (first) {\n const host = first.address === \"::\" || first.address === \"0.0.0.0\" ? \"127.0.0.1\" : first.address;\n return `http://${host}:${first.port}`;\n }\n return `http://127.0.0.1:${config.dashboardPort}`;\n}\n\n// ------------------------------------------------------------------\n// PID file management \u2014 mirrors claude-mem's worker.pid pattern\n// ------------------------------------------------------------------\n\n/**\n * Shape of the PID file written by the dashboard process.\n */\ninterface DashboardPidFile {\n pid: number;\n port: number;\n startedAt: string;\n}\n\n/**\n * Resolve the path to the PID file. Stored under\n * `.claude-crap/dashboard.pid` in the workspace so it survives\n * across sessions but is gitignored with the rest of `.claude-crap/`.\n */\nfunction resolvePidFilePath(config: CrapConfig): string {\n return join(config.pluginRoot, \".claude-crap\", \"dashboard.pid\");\n}\n\n/**\n * Write the PID file atomically after the dashboard has started.\n */\nfunction writePidFile(path: string, port: number): void {\n const data: DashboardPidFile = {\n pid: process.pid,\n port,\n startedAt: new Date().toISOString(),\n };\n try {\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\");\n } catch {\n /* best effort \u2014 dashboard still works without a PID file */\n }\n}\n\n/**\n * Remove the PID file during graceful shutdown.\n */\nfunction removePidFile(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n /* already gone or never written */\n }\n}\n\n/**\n * Check whether a process is alive using the signal-0 probe.\n * Returns `true` when the process exists and is reachable.\n */\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Read the PID file, kill any stale dashboard process, and free the\n * port so the current session can bind to it. This is the key\n * difference from the port-fallback approach: instead of drifting to\n * 5118, 5119, etc., we reclaim the configured port every time.\n *\n * @param pidFilePath Absolute path to `dashboard.pid`.\n * @param port The configured dashboard port.\n * @param logger Pino logger for diagnostics.\n */\nasync function killStaleDashboard(\n pidFilePath: string,\n port: number,\n logger: Logger,\n): Promise<void> {\n if (!existsSync(pidFilePath)) return;\n\n let stale: DashboardPidFile;\n try {\n stale = JSON.parse(readFileSync(pidFilePath, \"utf8\"));\n } catch {\n // Corrupted PID file \u2014 remove it and move on.\n removePidFile(pidFilePath);\n return;\n }\n\n if (!isPidAlive(stale.pid)) {\n logger.info({ stalePid: stale.pid }, \"stale dashboard PID file found (process dead), removing\");\n removePidFile(pidFilePath);\n return;\n }\n\n // Process is alive \u2014 kill it so we can reclaim the port.\n logger.info(\n { stalePid: stale.pid, port: stale.port, startedAt: stale.startedAt },\n \"killing stale dashboard process from previous session\",\n );\n\n try {\n process.kill(stale.pid, \"SIGTERM\");\n } catch {\n // Permission denied or already gone \u2014 remove PID file either way.\n removePidFile(pidFilePath);\n return;\n }\n\n // Wait up to 3 seconds for the process to exit.\n for (let i = 0; i < 30; i++) {\n if (!isPidAlive(stale.pid)) break;\n await new Promise((r) => setTimeout(r, 100));\n }\n\n // If still alive after 3s, escalate to SIGKILL.\n if (isPidAlive(stale.pid)) {\n try {\n process.kill(stale.pid, \"SIGKILL\");\n } catch {\n /* best effort */\n }\n await new Promise((r) => setTimeout(r, 200));\n }\n\n removePidFile(pidFilePath);\n\n // Give the OS a moment to release the TCP port after the process dies.\n await new Promise((r) => setTimeout(r, 300));\n}\n\n// \u2500\u2500 Complexity report builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Entry in the complexity report's top-functions list. */\ninterface ComplexityEntry {\n filePath: string;\n name: string;\n cyclomaticComplexity: number;\n startLine: number;\n endLine: number;\n lineCount: number;\n}\n\n/** Shape returned by GET /api/complexity. */\ninterface ComplexityReport {\n threshold: number;\n totalFunctions: number;\n violationCount: number;\n topFunctions: ComplexityEntry[];\n}\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n\n/**\n * Walk the workspace and collect per-function complexity metrics,\n * returning the top 20 most complex functions. This runs on demand\n * when the dashboard requests /api/complexity.\n */\nasync function buildComplexityReport(\n config: CrapConfig,\n engine: TreeSitterEngine,\n logger: Logger,\n exclude?: ReadonlyArray<string>,\n): Promise<ComplexityReport> {\n const threshold = config.cyclomaticMax;\n const filter = createExclusionFilter(exclude);\n const allFunctions: ComplexityEntry[] = [];\n let totalFunctions = 0;\n\n async function walk(dir: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n const language = detectLanguageFromPath(entry.name);\n if (!language) continue;\n try {\n const metrics = await engine.analyzeFile({ filePath: full, language });\n for (const fn of metrics.functions) {\n totalFunctions += 1;\n allFunctions.push({\n filePath: full.startsWith(config.pluginRoot)\n ? full.substring(config.pluginRoot.length + 1)\n : full,\n name: fn.name,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n startLine: fn.startLine,\n endLine: fn.endLine,\n lineCount: fn.lineCount,\n });\n }\n } catch (err) {\n logger.warn(\n { filePath: full, err: (err as Error).message },\n \"complexity-report: failed to analyze file\",\n );\n }\n }\n }\n\n await walk(config.pluginRoot);\n\n // Sort by complexity descending and take top 20\n allFunctions.sort((a, b) => b.cyclomaticComplexity - a.cyclomaticComplexity);\n const topFunctions = allFunctions.slice(0, 20);\n const violationCount = allFunctions.filter(\n (f) => f.cyclomaticComplexity > threshold,\n ).length;\n\n return { threshold, totalFunctions, violationCount, topFunctions };\n}\n\n/**\n * Wrap {@link computeProjectScore} so the dashboard endpoint can call\n * it with the live store and provide consistent location metadata.\n */\nasync function buildScore(\n config: CrapConfig,\n sarifStore: SarifStore,\n workspace: WorkspaceStats,\n dashboardUrl: string | null,\n): Promise<ProjectScore> {\n return computeProjectScore({\n workspaceRoot: config.pluginRoot,\n minutesPerLoc: config.minutesPerLoc,\n tdrMaxRating: config.tdrMaxRating,\n workspace,\n sarifStore,\n dashboardUrl,\n sarifReportPath: sarifStore.consolidatedReportPath,\n });\n}\n", "/**\n * Centralized file and directory exclusion system.\n *\n * Every filesystem walker in the codebase (workspace-walker,\n * complexity-scanner, dashboard file-detail) imports from this module\n * instead of maintaining its own `SKIP_DIRS` constant. This\n * guarantees all subsystems agree on what to exclude.\n *\n * User-configurable exclusions from `.claude-crap.json` are layered\n * on top of the defaults via {@link createExclusionFilter}.\n *\n * @module shared/exclusions\n */\n\nimport picomatch from \"picomatch\";\n\n// \u2500\u2500 Default exclusions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Directories excluded by name at any depth. A walker that encounters\n * a directory entry whose name is in this set should skip the entire\n * subtree. The set covers package managers, VCS, build outputs for\n * all major frameworks, language-specific caches, and plugin state.\n */\nexport const DEFAULT_SKIP_DIRS: ReadonlySet<string> = new Set([\n // Package managers / vendored deps\n \"node_modules\",\n \"vendor\",\n\n // Version control\n \".git\",\n\n // Build outputs (general)\n \"dist\",\n \"build\",\n \"bundle\",\n \"out\",\n \"target\",\n \"coverage\",\n\n // Framework build outputs\n \".next\", // Next.js\n \".nuxt\", // Nuxt 2\n \".output\", // Nuxt 3\n \".vercel\", // Vercel\n \".svelte-kit\", // SvelteKit\n \".astro\", // Astro\n \".angular\", // Angular\n \".turbo\", // Turborepo\n \".parcel-cache\",// Parcel\n \".expo\", // Expo / React Native\n\n // Language-specific caches\n \".venv\",\n \"venv\",\n \"__pycache__\",\n \".cache\",\n \".dart_tool\", // Dart / Flutter\n \".gradle\", // Gradle\n\n // IDE state\n \".idea\",\n\n // Plugin infrastructure (excluded so the plugin's own hook/bundle\n // files don't pollute workspace metrics when developing the plugin\n // itself, and don't appear in scans of any project)\n \"plugin\",\n \"hooks\",\n \"skills\",\n\n // Plugin state\n \".claude-crap\",\n \".claude-plugin\",\n \".claude-sonar\",\n \".codesight\",\n]);\n\n/**\n * Filename-level glob patterns that match generated or minified files\n * regardless of which directory they live in. Matched against the\n * bare filename (not the full path).\n */\nexport const DEFAULT_SKIP_PATTERNS: ReadonlyArray<string> = [\n \"*.min.js\",\n \"*.min.css\",\n \"*.min.mjs\",\n \"*.min.cjs\",\n \"*.bundle.js\",\n \"*.chunk.js\",\n];\n\n// \u2500\u2500 Exclusion filter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Stateless, pre-compiled filter that every filesystem walker uses\n * to decide whether to skip a directory or file.\n */\nexport interface ExclusionFilter {\n /** Returns `true` when the directory should be skipped entirely. */\n shouldSkipDir(dirName: string): boolean;\n /** Returns `true` when the file should be excluded from analysis. */\n shouldSkipFile(relativePath: string, fileName: string): boolean;\n}\n\n/**\n * Create an {@link ExclusionFilter} that combines the built-in\n * defaults with optional user-defined patterns from `.claude-crap.json`.\n *\n * User patterns follow `.gitignore`-style conventions:\n * - `apps/legacy/` \u2192 trailing `/` means directory exclusion\n * - `*.proto.ts` \u2192 glob matched against workspace-relative path\n * - `src/generated/**` \u2192 path-prefix glob\n *\n * Picomatch matchers are compiled once at construction, so per-file\n * checks are O(1) set lookups plus O(n) matcher calls where n is\n * the small number of user patterns (typically < 20).\n *\n * @param userExclusions Optional patterns from `.claude-crap.json`.\n */\nexport function createExclusionFilter(\n userExclusions?: ReadonlyArray<string>,\n): ExclusionFilter {\n // Split user patterns into directory exclusions and file globs\n const extraDirs = new Set<string>();\n const fileGlobs: string[] = [];\n\n for (const pattern of userExclusions ?? []) {\n if (pattern.endsWith(\"/\")) {\n // Directory exclusion \u2014 strip trailing slash\n extraDirs.add(pattern.slice(0, -1));\n } else {\n fileGlobs.push(pattern);\n }\n }\n\n // Compile filename-level matchers once\n const defaultFileMatchers = DEFAULT_SKIP_PATTERNS.map((p) =>\n picomatch(p, { dot: true }),\n );\n const userFileMatchers = fileGlobs.map((p) =>\n picomatch(p, { dot: true }),\n );\n\n return {\n shouldSkipDir(dirName: string): boolean {\n // Hidden directories are always skipped except .claude-plugin\n if (dirName.startsWith(\".\") && dirName !== \".claude-plugin\") {\n return DEFAULT_SKIP_DIRS.has(dirName) || true;\n }\n return DEFAULT_SKIP_DIRS.has(dirName) || extraDirs.has(dirName);\n },\n\n shouldSkipFile(relativePath: string, fileName: string): boolean {\n // Check filename against default minified/bundled patterns\n for (const matcher of defaultFileMatchers) {\n if (matcher(fileName)) return true;\n }\n // Check against user-defined globs (matched on relative path)\n for (const matcher of userFileMatchers) {\n if (matcher(relativePath) || matcher(fileName)) return true;\n }\n return false;\n },\n };\n}\n", "/**\n * Technical Debt Ratio (TDR) \u2014 deterministic computation and rating.\n *\n * The Technical Debt Ratio expresses how expensive it would be to remediate\n * all known issues in a scope, relative to how much it would have cost to\n * write the code in the first place. Formally (see docs/quality-gate.md):\n *\n * TDR = remediationCost / (costPerLine \u00D7 totalLinesOfCode)\n *\n * Where the remediation cost is the sum (in minutes) of every linter /\n * scanner / mutator finding's individual estimated effort, and the per-line\n * cost is assumed to be a constant `minutesPerLoc` (industry default: 30\n * minutes per line of code, including design, writing and review).\n *\n * The resulting ratio is converted to a percentage and mapped to a letter\n * grade A..E. The thresholds are strict and non-negotiable:\n *\n * | Rating | TDR % | Meaning |\n * |--------|--------------|-------------------------------------------|\n * | A | 0..5% | Excellent \u2014 remediation cost is noise |\n * | B | >5..10% | Low risk |\n * | C | >10..20% | Moderate, watch closely |\n * | D | >20..50% | Critical, remediation plan required |\n * | E | >50% | Unmaintainable \u2014 halt feature work |\n *\n * Rating E always halts the workflow at the Stop quality gate, regardless\n * of the configured `TDR_MAX_RATING` tolerance.\n *\n * @module metrics/tdr\n */\n\nimport type { MaintainabilityRating } from \"../config.js\";\n\n/**\n * Inputs required to compute a Technical Debt Ratio over any scope\n * (project, module, or file).\n */\nexport interface TdrInput {\n /** Sum of all finding remediation estimates, in minutes. Must be \u2265 0. */\n readonly remediationMinutes: number;\n /** Total lines of code in the scope. Must be > 0 (division denominator). */\n readonly totalLinesOfCode: number;\n /** Assumed development cost per LOC, in minutes. Must be > 0. */\n readonly minutesPerLoc: number;\n}\n\n/**\n * Result of a TDR computation with both the raw ratio and the letter grade.\n */\nexport interface TdrResult {\n /** Raw ratio (remediation / development), rounded to 6 decimals. */\n readonly ratio: number;\n /** Same ratio expressed as a percentage, rounded to 4 decimals. */\n readonly percent: number;\n /** Letter grade derived from `percent` via {@link classifyTdr}. */\n readonly rating: MaintainabilityRating;\n /** Remediation input, echoed for traceability. */\n readonly remediationMinutes: number;\n /** LOC input, echoed for traceability. */\n readonly totalLinesOfCode: number;\n /** Computed `minutesPerLoc \u00D7 totalLinesOfCode`, useful for the dashboard. */\n readonly developmentCostMinutes: number;\n}\n\n/** Canonical ordering used by {@link ratingToRank}. */\nconst RATING_ORDER: ReadonlyArray<MaintainabilityRating> = [\"A\", \"B\", \"C\", \"D\", \"E\"];\n\n/**\n * Convert a letter rating to its numeric rank (A=0, E=4). Useful when\n * comparing two ratings without relying on lexical order.\n *\n * @param rating The rating letter.\n * @returns Its rank in `[0, 4]`.\n */\nexport function ratingToRank(rating: MaintainabilityRating): number {\n return RATING_ORDER.indexOf(rating);\n}\n\n/**\n * Return `true` when `actual` is strictly worse than `limit`, false otherwise.\n * Used by the Stop quality gate to decide whether to block task completion.\n *\n * @param actual Rating currently achieved by the project.\n * @param limit Maximum tolerated rating (worst allowed).\n * @returns `true` if `actual` should trigger a block.\n *\n * @example\n * ratingIsWorseThan(\"D\", \"C\") // \u2192 true\n * ratingIsWorseThan(\"B\", \"C\") // \u2192 false\n * ratingIsWorseThan(\"C\", \"C\") // \u2192 false (equal, not worse)\n */\nexport function ratingIsWorseThan(\n actual: MaintainabilityRating,\n limit: MaintainabilityRating,\n): boolean {\n return ratingToRank(actual) > ratingToRank(limit);\n}\n\n/**\n * Map a TDR percentage to its letter rating. The boundaries are inclusive\n * on the upper end (5% is still an A, 10% is still a B, etc.).\n *\n * @param percent TDR expressed as a percentage. Must be \u2265 0.\n * @returns Letter rating A..E.\n * @throws When `percent` is negative or not finite.\n */\nexport function classifyTdr(percent: number): MaintainabilityRating {\n if (!Number.isFinite(percent) || percent < 0) {\n throw new Error(`[tdr] percent is invalid: ${percent}`);\n }\n if (percent <= 5) return \"A\";\n if (percent <= 10) return \"B\";\n if (percent <= 20) return \"C\";\n if (percent <= 50) return \"D\";\n return \"E\";\n}\n\n/**\n * Compute the Technical Debt Ratio for a scope and return the full result.\n * This function is pure and deterministic.\n *\n * @param input Remediation minutes, total LOC and the cost-per-line assumption.\n * @returns A {@link TdrResult} ready to be serialized to SARIF properties.\n * @throws When any numeric input is out of range.\n *\n * @example\n * // 240 minutes of remediation across 500 LOC at 30 min/LOC\n * computeTdr({ remediationMinutes: 240, totalLinesOfCode: 500, minutesPerLoc: 30 })\n * // \u2192 { ratio: 0.016, percent: 1.6, rating: \"A\", ... }\n */\nexport function computeTdr(input: TdrInput): TdrResult {\n if (input.totalLinesOfCode <= 0) {\n throw new Error(`[tdr] totalLinesOfCode must be > 0, got ${input.totalLinesOfCode}`);\n }\n if (input.minutesPerLoc <= 0) {\n throw new Error(`[tdr] minutesPerLoc must be > 0, got ${input.minutesPerLoc}`);\n }\n if (input.remediationMinutes < 0) {\n throw new Error(`[tdr] remediationMinutes must be \u2265 0, got ${input.remediationMinutes}`);\n }\n\n const developmentCostMinutes = input.minutesPerLoc * input.totalLinesOfCode;\n const ratio = input.remediationMinutes / developmentCostMinutes;\n const percent = ratio * 100;\n const rating = classifyTdr(percent);\n\n return {\n ratio: Number(ratio.toFixed(6)),\n percent: Number(percent.toFixed(4)),\n rating,\n remediationMinutes: input.remediationMinutes,\n totalLinesOfCode: input.totalLinesOfCode,\n developmentCostMinutes,\n };\n}\n", "/**\n * Aggregate project score engine.\n *\n * Given a fully resolved configuration, the live SARIF store, and a\n * workspace LOC walker, this module produces a single immutable\n * `ProjectScore` snapshot describing the entire project's quality\n * posture across three dimensions:\n *\n * - **Maintainability** \u2014 derived from the Technical Debt Ratio (TDR)\n * using the existing `metrics/tdr.ts` engine.\n * - **Reliability** \u2014 derived from the worst non-security finding.\n * - **Security** \u2014 derived from the worst security finding.\n *\n * Each dimension produces a letter grade A..E and the `overall` field\n * collapses them by taking the worst grade. The `passes` field tells\n * the caller whether the overall grade is within the configured\n * `tdrMaxRating` tolerance \u2014 handy for the Stop quality gate and the\n * `score_project` MCP tool.\n *\n * Security vs reliability is determined by a heuristic on the `ruleId`:\n * any rule whose identifier matches a security keyword (`sec`, `sql`,\n * `xss`, `csrf`, `injection`, `crypt`, `auth`, `secret`, `password`,\n * `cve`, `vuln`) is treated as security. Everything else is reliability.\n * This is intentionally coarse: adapters that stamp a richer SARIF\n * taxonomy (e.g. `properties.tags = [\"security\"]`) could replace this\n * classifier with an exact match, but the regex is sufficient for the\n * scanners this plugin ships with.\n *\n * The score engine is pure: it does no I/O, takes a `WorkspaceStats`\n * value (which the caller produces from the bounded LOC walker), and\n * returns a brand new score object on every call. Tests can construct\n * a `SarifStore` in memory and verify the boundaries directly.\n *\n * @module metrics/score\n */\n\nimport type { MaintainabilityRating } from \"../config.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport { classifyTdr, ratingIsWorseThan } from \"./tdr.js\";\n\n/**\n * Letter rating shared by every dimension. The same A..E scale used by\n * SonarQube's reliability and security ratings, where A is best and E\n * is unmaintainable / blocker-class.\n */\nexport type SeverityRating = MaintainabilityRating;\n\n/**\n * Workspace size statistics produced by an external bounded walker.\n * The score engine does not walk the disk itself \u2014 pass these in.\n */\nexport interface WorkspaceStats {\n /** Total physical lines of code under the workspace root. */\n readonly physicalLoc: number;\n /** Number of files visited by the walker. */\n readonly fileCount: number;\n}\n\n/**\n * Per-dimension breakdown.\n */\nexport interface DimensionScore {\n readonly rating: SeverityRating;\n readonly findings: number;\n readonly errorFindings: number;\n readonly warningFindings: number;\n readonly noteFindings: number;\n}\n\n/**\n * Per-finding-level summary plus per-tool counts.\n */\nexport interface FindingsSummary {\n readonly total: number;\n readonly error: number;\n readonly warning: number;\n readonly note: number;\n readonly byTool: Readonly<Record<string, number>>;\n readonly byFile: Readonly<Record<string, number>>;\n}\n\n/**\n * Maintainability dimension expressed as a TDR percentage.\n */\nexport interface MaintainabilityScore {\n readonly rating: MaintainabilityRating;\n readonly tdrPercent: number;\n readonly remediationMinutes: number;\n readonly developmentCostMinutes: number;\n}\n\n/**\n * Pointer to where the consolidated report can be found.\n */\nexport interface ScoreLocation {\n /** Local dashboard URL when the HTTP server is running, otherwise `null`. */\n readonly dashboardUrl: string | null;\n /** Absolute path to the consolidated SARIF document on disk. */\n readonly sarifReportPath: string;\n}\n\n/**\n * The full project score snapshot. Returned from {@link computeProjectScore}.\n */\nexport interface ProjectScore {\n readonly generatedAt: string;\n readonly workspaceRoot: string;\n readonly loc: { readonly physical: number; readonly files: number };\n readonly findings: FindingsSummary;\n readonly maintainability: MaintainabilityScore;\n readonly reliability: DimensionScore;\n readonly security: DimensionScore;\n readonly overall: {\n readonly rating: SeverityRating;\n /** True when `overall.rating` is no worse than `policyRating`. */\n readonly passes: boolean;\n /** Echoed from the configured policy. */\n readonly policyRating: MaintainabilityRating;\n };\n readonly location: ScoreLocation;\n}\n\n/**\n * Inputs accepted by {@link computeProjectScore}.\n */\nexport interface ComputeProjectScoreInput {\n readonly workspaceRoot: string;\n readonly minutesPerLoc: number;\n readonly tdrMaxRating: MaintainabilityRating;\n readonly workspace: WorkspaceStats;\n readonly sarifStore: SarifStore;\n readonly dashboardUrl: string | null;\n readonly sarifReportPath: string;\n}\n\n/**\n * Pattern that classifies a rule identifier as security-relevant.\n * Matches case-insensitively against the rule id text. Intentionally\n * permissive \u2014 false positives in classification are recoverable, but\n * a missed security finding being graded as reliability is not.\n */\nconst SECURITY_RULE_PATTERN =\n /(sec|sql|xss|csrf|ssrf|injection|crypt|auth|secret|password|token|cve|vuln|jwt|cors|rce|deserial|prototype-pollution)/i;\n\n/**\n * Compute the full project score. Pure function \u2014 no side effects.\n *\n * @param input Aggregated inputs.\n * @returns A {@link ProjectScore} ready to be serialized.\n */\nexport function computeProjectScore(input: ComputeProjectScoreInput): ProjectScore {\n const findingsList = input.sarifStore.list();\n\n // ---- Findings summary ----\n /** @type {Record<string, number>} */\n const byTool: Record<string, number> = {};\n const byFile: Record<string, number> = {};\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n let remediationMinutes = 0;\n\n /** Findings split by classification. */\n const securityFindings: Array<{ level: string }> = [];\n const reliabilityFindings: Array<{ level: string }> = [];\n\n for (const finding of findingsList) {\n if (finding.level === \"error\") errorCount += 1;\n else if (finding.level === \"warning\") warningCount += 1;\n else if (finding.level === \"note\") noteCount += 1;\n\n byTool[finding.sourceTool] = (byTool[finding.sourceTool] ?? 0) + 1;\n byFile[finding.location.uri] = (byFile[finding.location.uri] ?? 0) + 1;\n\n const effort =\n typeof finding.properties?.effortMinutes === \"number\"\n ? finding.properties.effortMinutes\n : 0;\n remediationMinutes += effort;\n\n if (SECURITY_RULE_PATTERN.test(finding.ruleId)) {\n securityFindings.push({ level: finding.level });\n } else {\n reliabilityFindings.push({ level: finding.level });\n }\n }\n\n const findings: FindingsSummary = {\n total: findingsList.length,\n error: errorCount,\n warning: warningCount,\n note: noteCount,\n byTool,\n byFile,\n };\n\n // ---- Maintainability (TDR) ----\n // Guard against an empty workspace; the TDR formula divides by LOC.\n const safeLoc = Math.max(input.workspace.physicalLoc, 1);\n const developmentCostMinutes = input.minutesPerLoc * safeLoc;\n const tdrPercent = (remediationMinutes / developmentCostMinutes) * 100;\n const tdrRating = classifyTdr(tdrPercent);\n\n const maintainability: MaintainabilityScore = {\n rating: tdrRating,\n tdrPercent: Number(tdrPercent.toFixed(4)),\n remediationMinutes,\n developmentCostMinutes,\n };\n\n // ---- Reliability and security dimensions ----\n const reliability = scoreDimension(reliabilityFindings);\n const security = scoreDimension(securityFindings);\n\n // ---- Overall = the worst of the three ----\n const overallRating = worstOf(maintainability.rating, reliability.rating, security.rating);\n const passes = !ratingIsWorseThan(overallRating, input.tdrMaxRating);\n\n return {\n generatedAt: new Date().toISOString(),\n workspaceRoot: input.workspaceRoot,\n loc: { physical: input.workspace.physicalLoc, files: input.workspace.fileCount },\n findings,\n maintainability,\n reliability,\n security,\n overall: {\n rating: overallRating,\n passes,\n policyRating: input.tdrMaxRating,\n },\n location: {\n dashboardUrl: input.dashboardUrl,\n sarifReportPath: input.sarifReportPath,\n },\n };\n}\n\n/**\n * Score a single dimension (reliability or security) from its findings.\n *\n * The mapping is intentionally coarse and maps directly from SARIF\n * levels to letter ratings:\n *\n * - 0 findings \u2192 A\n * - only `note` findings \u2192 B\n * - 1+ `warning`, 0 `error` \u2192 C\n * - 1\u20132 `error` \u2192 D\n * - 3+ `error` \u2192 E\n *\n * Projects that stamp explicit blocker / major / minor categories on\n * their SARIF properties can wrap this function with their own\n * taxonomy-aware classifier.\n *\n * @param findings Findings classified into this dimension.\n */\nfunction scoreDimension(findings: ReadonlyArray<{ level: string }>): DimensionScore {\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n for (const f of findings) {\n if (f.level === \"error\") errorCount += 1;\n else if (f.level === \"warning\") warningCount += 1;\n else if (f.level === \"note\") noteCount += 1;\n }\n let rating: SeverityRating;\n if (errorCount >= 3) rating = \"E\";\n else if (errorCount >= 1) rating = \"D\";\n else if (warningCount >= 1) rating = \"C\";\n else if (noteCount >= 1) rating = \"B\";\n else rating = \"A\";\n\n return {\n rating,\n findings: findings.length,\n errorFindings: errorCount,\n warningFindings: warningCount,\n noteFindings: noteCount,\n };\n}\n\n/**\n * Return the worst (alphabetically highest) of an arbitrary number of\n * letter ratings. Used to collapse the three dimension ratings into the\n * overall project rating.\n *\n * @param ratings Two or more letter ratings.\n * @returns The worst rating.\n */\nfunction worstOf(...ratings: ReadonlyArray<SeverityRating>): SeverityRating {\n let worst: SeverityRating = \"A\";\n for (const r of ratings) {\n if (ratingIsWorseThan(r, worst)) worst = r;\n }\n return worst;\n}\n\n/**\n * Render a project score as a compact Markdown summary suitable for\n * display directly in a chat session. Keep it under ~30 lines so it\n * does not dominate the conversation context.\n *\n * @param score The score to render.\n */\nexport function renderProjectScoreMarkdown(score: ProjectScore): string {\n const verdict = score.overall.passes ? \"\u2705 passes policy\" : \"\u274C FAILS policy\";\n const dashboardLine = score.location.dashboardUrl\n ? `\uD83D\uDCCA Dashboard: ${score.location.dashboardUrl}`\n : `\uD83D\uDCCA Dashboard: <not running \u2014 start the MCP server to enable>`;\n\n return [\n `## claude-crap :: project score`,\n ``,\n `**Overall: ${score.overall.rating}** (${verdict}, policy ceiling = ${score.overall.policyRating})`,\n ``,\n `| Dimension | Rating | Detail |`,\n `| --------------- | :----: | --------------------------------------------------- |`,\n `| Maintainability | ${score.maintainability.rating} | TDR ${score.maintainability.tdrPercent}% (${score.maintainability.remediationMinutes} min over ${score.loc.physical} LOC) |`,\n `| Reliability | ${score.reliability.rating} | ${score.reliability.errorFindings} error \u00B7 ${score.reliability.warningFindings} warning \u00B7 ${score.reliability.noteFindings} note |`,\n `| Security | ${score.security.rating} | ${score.security.errorFindings} error \u00B7 ${score.security.warningFindings} warning \u00B7 ${score.security.noteFindings} note |`,\n ``,\n `Workspace: **${score.loc.physical} LOC** across **${score.loc.files} files**`,\n `Findings: **${score.findings.total} total** (${score.findings.error} error \u00B7 ${score.findings.warning} warning \u00B7 ${score.findings.note} note)`,\n `Tools: ${Object.keys(score.findings.byTool).join(\", \") || \"<none ingested>\"}`,\n ``,\n dashboardLine,\n `\uD83D\uDCC4 Report: ${score.location.sarifReportPath}`,\n ].join(\"\\n\");\n}\n", "/**\n * File detail builder for the dashboard.\n *\n * Given a workspace-relative file path, this module produces a rich\n * detail payload combining source code, per-function AST metrics, and\n * SARIF findings filtered to that file. The dashboard uses this to\n * render a ReportGenerator-style annotated code view.\n *\n * The builder is extracted into its own module (rather than inlined in\n * `server.ts`) so that:\n * - The logic is unit-testable without booting the HTTP server.\n * - The types are importable by both the Fastify route and tests.\n *\n * @module dashboard/file-detail\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { resolveWithinWorkspace } from \"../workspace-guard.js\";\nimport { detectLanguageFromPath, type SupportedLanguage } from \"../ast/language-config.js\";\nimport type { TreeSitterEngine, FunctionMetrics } from \"../ast/tree-sitter-engine.js\";\nimport type { SarifStore, IngestedFinding } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Per-function entry in the detail response. */\nexport interface FileDetailFunction {\n readonly name: string;\n readonly startLine: number;\n readonly endLine: number;\n readonly cyclomaticComplexity: number;\n readonly lineCount: number;\n}\n\n/** Per-finding entry in the detail response. */\nexport interface FileDetailFinding {\n readonly ruleId: string;\n readonly level: string;\n readonly message: string;\n readonly sourceTool: string;\n readonly startLine: number;\n readonly startColumn: number;\n readonly endLine: number;\n readonly endColumn: number;\n readonly effortMinutes: number;\n}\n\n/** Summary statistics for the file. */\nexport interface FileDetailSummary {\n readonly totalFindings: number;\n readonly errorCount: number;\n readonly warningCount: number;\n readonly noteCount: number;\n readonly totalEffortMinutes: number;\n readonly avgComplexity: number;\n readonly maxComplexity: number;\n}\n\n/** Full response payload for the file detail endpoint. */\nexport interface FileDetailResponse {\n readonly filePath: string;\n readonly language: SupportedLanguage | null;\n readonly physicalLoc: number;\n readonly logicalLoc: number;\n readonly cyclomaticMax: number;\n readonly sourceLines: string[];\n readonly functions: FileDetailFunction[];\n readonly findings: FileDetailFinding[];\n readonly summary: FileDetailSummary;\n}\n\n/** Input accepted by {@link buildFileDetail}. */\nexport interface BuildFileDetailInput {\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly astEngine?: TreeSitterEngine | undefined;\n readonly sarifStore: SarifStore;\n readonly cyclomaticMax: number;\n}\n\n// \u2500\u2500 Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Build the file detail payload. Pure function aside from the file\n * read and the tree-sitter analysis (both deterministic for a given\n * file).\n *\n * @throws When the file does not exist or the path escapes the workspace.\n */\nexport async function buildFileDetail(\n input: BuildFileDetailInput,\n): Promise<FileDetailResponse> {\n const { relativePath, workspaceRoot, astEngine, sarifStore, cyclomaticMax } = input;\n\n // 1. Guard against path traversal\n const absolutePath = resolveWithinWorkspace(workspaceRoot, relativePath);\n\n // 2. Read source\n const source = await fs.readFile(absolutePath, \"utf8\");\n const sourceLines = source.split(/\\r?\\n/);\n // Remove trailing empty line from files ending with \\n\n if (sourceLines.length > 0 && sourceLines[sourceLines.length - 1] === \"\") {\n sourceLines.pop();\n }\n\n const physicalLoc = sourceLines.length;\n let logicalLoc = 0;\n for (const line of sourceLines) {\n if (line.trim().length > 0) logicalLoc += 1;\n }\n\n // 3. AST analysis (if language is supported)\n const language = detectLanguageFromPath(relativePath);\n let functions: FileDetailFunction[] = [];\n\n if (language && astEngine) {\n try {\n const metrics = await astEngine.analyzeFile({\n filePath: absolutePath,\n language,\n });\n functions = metrics.functions.map((fn: FunctionMetrics) => ({\n name: fn.name,\n startLine: fn.startLine,\n endLine: fn.endLine,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n lineCount: fn.lineCount,\n }));\n } catch {\n // Analysis failure is non-fatal \u2014 return empty functions\n }\n }\n\n // 4. Filter SARIF findings for this file\n const allFindings = sarifStore.list();\n const fileFindings = allFindings.filter(\n (f: IngestedFinding) => f.location.uri === relativePath,\n );\n\n const findings: FileDetailFinding[] = fileFindings.map((f: IngestedFinding) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: f.message,\n sourceTool: f.sourceTool,\n startLine: f.location.startLine,\n startColumn: f.location.startColumn,\n endLine: f.location.endLine ?? f.location.startLine,\n endColumn: f.location.endColumn ?? 0,\n effortMinutes:\n typeof f.properties?.effortMinutes === \"number\"\n ? f.properties.effortMinutes\n : 0,\n }));\n\n // 5. Build summary\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n let totalEffortMinutes = 0;\n\n for (const f of findings) {\n if (f.level === \"error\") errorCount += 1;\n else if (f.level === \"warning\") warningCount += 1;\n else if (f.level === \"note\") noteCount += 1;\n totalEffortMinutes += f.effortMinutes;\n }\n\n const complexities = functions.map((f) => f.cyclomaticComplexity);\n const maxComplexity = complexities.length > 0 ? Math.max(...complexities) : 0;\n const avgComplexity =\n complexities.length > 0\n ? Math.round(\n (complexities.reduce((a, b) => a + b, 0) / complexities.length) * 100,\n ) / 100\n : 0;\n\n return {\n filePath: relativePath,\n language,\n physicalLoc,\n logicalLoc,\n cyclomaticMax,\n sourceLines,\n functions,\n findings,\n summary: {\n totalFindings: findings.length,\n errorCount,\n warningCount,\n noteCount,\n totalEffortMinutes,\n avgComplexity,\n maxComplexity,\n },\n };\n}\n", "/**\n * Workspace path containment guard.\n *\n * Every MCP tool that accepts a user-supplied file path routes it\n * through {@link resolveWithinWorkspace} before touching the\n * filesystem. The guard rejects any resolved absolute path that is\n * outside the configured workspace root, so the agent cannot be\n * tricked (via prompt injection through scanner output, or via its\n * own confusion) into reading files that live next to the project\n * but outside it.\n *\n * F-A01-01: the original guard in `src/index.ts` used a naive\n * `candidate.startsWith(workspace)` check, which suffers from prefix\n * confusion \u2014 for a workspace like `/Users/x/claude-crap`, an\n * absolute input path such as `/Users/x/claude-crap-evil/secret.ts`\n * would pass the check because the two share the literal prefix up\n * to the final segment. This module replaces that check with a\n * separator-aware comparison: the candidate is only accepted if it\n * equals the workspace exactly OR begins with `workspace + sep`.\n *\n * This module is intentionally pure (no I/O, no global state) so it\n * can be unit-tested without any fixtures.\n *\n * @module workspace-guard\n */\n\nimport { isAbsolute, resolve, sep } from \"node:path\";\n\n/**\n * Resolve a user-supplied file path against a workspace root, returning\n * the absolute path only if it is contained inside the root. Throws a\n * descriptive error when the resolved candidate escapes the workspace.\n *\n * Rules enforced (must stay in sync with\n * `src/tests/workspace-guard.test.ts`):\n *\n * 1. Relative paths are resolved against `workspaceRoot`.\n * 2. Absolute paths are accepted as-is for resolution.\n * 3. The resolved candidate must equal `workspaceRoot` OR begin with\n * `workspaceRoot + sep`. Sibling directories that merely share a\n * prefix (e.g. `/tmp/workspace-evil` vs `/tmp/workspace`) are\n * rejected.\n * 4. The comparison uses the platform's native path separator, so\n * the guard works on both POSIX and Windows.\n *\n * @param workspaceRoot Absolute or relative path to the workspace root.\n * Non-absolute values are resolved against the\n * current working directory, which matches the\n * behavior of the previous in-lined guard.\n * @param filePath User-supplied path. May be absolute or relative\n * to the workspace root.\n * @returns The absolute, workspace-contained path.\n * @throws `Error` when the candidate escapes the workspace.\n */\nexport function resolveWithinWorkspace(workspaceRoot: string, filePath: string): string {\n const workspace = resolve(workspaceRoot);\n const candidate = isAbsolute(filePath) ? resolve(filePath) : resolve(workspace, filePath);\n if (candidate !== workspace && !candidate.startsWith(workspace + sep)) {\n throw new Error(\n `[claude-crap] Refusing to access '${filePath}' \u2014 path escapes the workspace root`,\n );\n }\n return candidate;\n}\n", "/**\n * CRAP (Change Risk Anti-Patterns) index \u2014 deterministic computation.\n *\n * The CRAP index is a single number that summarizes how dangerous it is\n * to change a given function. It combines two signals:\n *\n * 1. Cyclomatic complexity (`comp`) \u2014 how many independent paths the\n * function has. Tracks how easy it is to reason about the code.\n * 2. Test coverage percentage (`cov`) \u2014 empirical safety net provided\n * by the automated test suite.\n *\n * The formula (see docs/quality-gate.md) is:\n *\n * CRAP(m) = comp(m)\u00B2 \u00D7 (1 \u2212 cov(m)/100)\u00B3 + comp(m)\n *\n * The cubic uncovered-weight term makes CRAP punish uncovered, branchy\n * code extremely aggressively. A function with complexity 10 and 0%\n * coverage scores CRAP = 10\u00B2 \u00D7 1\u00B3 + 10 = 110, well above the 30 threshold.\n *\n * The additive `+ comp(m)` tail is intentional: it means that any function\n * with `comp \u2265 30` can NEVER reach a passing CRAP score, even with 100%\n * coverage (because the final term alone equals the threshold). This\n * encodes the policy \"functions above complexity 30 must be decomposed,\n * period\" \u2014 you cannot test your way out of structural complexity.\n *\n * @module metrics/crap\n */\n\n/**\n * Inputs required to compute CRAP for a single function.\n */\nexport interface CrapInput {\n /** Cyclomatic complexity of the function. Must be an integer \u2265 1. */\n readonly cyclomaticComplexity: number;\n /** Test coverage percentage for the function. Must be in `[0, 100]`. */\n readonly coveragePercent: number;\n}\n\n/**\n * Result of a CRAP computation, including the inputs used so callers can\n * echo the context back to the LLM or dump it to a SARIF result's\n * `properties` bag without re-reading the source data.\n */\nexport interface CrapResult {\n /** The CRAP score, rounded to 4 decimals for stable serialization. */\n readonly crap: number;\n /** Cyclomatic complexity echoed from the input. */\n readonly cyclomaticComplexity: number;\n /** Coverage percentage echoed from the input. */\n readonly coveragePercent: number;\n /** `true` when `crap > threshold` \u2014 caller should block on this. */\n readonly exceedsThreshold: boolean;\n /** The threshold used for the `exceedsThreshold` decision. */\n readonly threshold: number;\n}\n\n/**\n * Compute the CRAP index for a single function, against a configurable\n * block threshold. This function is pure, deterministic, and performs no\n * I/O \u2014 it can be called from any context (MCP tool handler, hook, unit\n * test) without side effects.\n *\n * @param input Cyclomatic complexity and coverage for the function.\n * @param threshold The CRAP score above which the caller should block.\n * @returns A {@link CrapResult} containing the score and decision.\n * @throws When any input is out of range or not finite.\n *\n * @example\n * // 12 branches, 60% coverage, threshold = 30\n * computeCrap({ cyclomaticComplexity: 12, coveragePercent: 60 }, 30)\n * // \u2192 { crap: 21.216, exceedsThreshold: false, ... }\n */\nexport function computeCrap(input: CrapInput, threshold: number): CrapResult {\n if (!Number.isFinite(input.cyclomaticComplexity) || input.cyclomaticComplexity < 1) {\n throw new Error(\n `[crap] cyclomaticComplexity must be \u2265 1, got ${input.cyclomaticComplexity}`,\n );\n }\n if (!Number.isFinite(input.coveragePercent) || input.coveragePercent < 0 || input.coveragePercent > 100) {\n throw new Error(\n `[crap] coveragePercent must be in [0, 100], got ${input.coveragePercent}`,\n );\n }\n if (!Number.isFinite(threshold) || threshold <= 0) {\n throw new Error(`[crap] threshold must be > 0, got ${threshold}`);\n }\n\n const comp = input.cyclomaticComplexity;\n const uncovered = 1 - input.coveragePercent / 100;\n const crap = comp * comp * Math.pow(uncovered, 3) + comp;\n\n return {\n // Round to 4 decimals so JSON serialization is stable across runs\n // (important for SARIF diffing and dashboard caching).\n crap: Number(crap.toFixed(4)),\n cyclomaticComplexity: comp,\n coveragePercent: input.coveragePercent,\n exceedsThreshold: crap > threshold,\n threshold,\n };\n}\n", "/**\n * Bounded workspace walker.\n *\n * Counts physical lines of code across a workspace, skipping directories\n * that should not contribute to the Technical Debt Ratio (dependency\n * caches, build artifacts, VCS metadata, etc.) and capping the file\n * count to keep the walk well under the Stop hook's 120-second budget\n * even on pathological repositories.\n *\n * This is the TypeScript twin of `hooks/lib/quality-gate.mjs#estimateWorkspaceLoc`.\n * The two are independent so neither side has to import files from outside\n * its own project tree.\n *\n * @module metrics/workspace-walker\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\n\n/**\n * Result returned by {@link estimateWorkspaceLoc}.\n */\nexport interface WorkspaceWalkResult {\n /** Total physical lines of code across every file the walker read. */\n readonly physicalLoc: number;\n /** Number of code files the walker visited. */\n readonly fileCount: number;\n /** `true` when the walker hit {@link MAX_FILES_WALKED} and stopped early. */\n readonly truncated: boolean;\n}\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n// The createExclusionFilter() factory is called once per walk with\n// optional user-defined patterns from .claude-crap.json.\n\n/**\n * Extensions the walker treats as \"code\". Anything else is ignored,\n * including markdown, JSON, YAML, lockfiles, and binaries.\n */\nconst CODE_EXTENSIONS: ReadonlySet<string> = new Set([\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".py\",\n \".java\",\n \".cs\",\n \".go\",\n \".rs\",\n \".rb\",\n \".php\",\n \".swift\",\n \".kt\",\n \".scala\",\n \".dart\",\n \".vue\",\n]);\n\n/**\n * Hard cap on the number of files the walker will read. Protects against\n * pathological repositories where the walk would otherwise dominate the\n * Stop hook's budget. When hit, the walker returns the partial count\n * with `truncated: true` and the caller may decide how to react.\n */\nexport const MAX_FILES_WALKED = 20_000;\n\n/**\n * Walk a workspace and return its physical LOC + file count. Never\n * follows symbolic links. Skips hidden directories except `.claude-plugin`\n * (which is tiny and contains the manifest).\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @param options Optional settings including user-defined exclusion patterns.\n * @returns A {@link WorkspaceWalkResult} snapshot.\n */\nexport async function estimateWorkspaceLoc(\n workspaceRoot: string,\n options?: { exclude?: ReadonlyArray<string> },\n): Promise<WorkspaceWalkResult> {\n const filter = createExclusionFilter(options?.exclude);\n let physicalLoc = 0;\n let fileCount = 0;\n let truncated = false;\n\n async function walk(dir: string): Promise<void> {\n if (truncated) return;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (truncated) return;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n const lower = entry.name.toLowerCase();\n const dot = lower.lastIndexOf(\".\");\n if (dot < 0) continue;\n const ext = lower.substring(dot);\n if (!CODE_EXTENSIONS.has(ext)) continue;\n const relPath = relative(workspaceRoot, full);\n if (filter.shouldSkipFile(relPath, entry.name)) continue;\n fileCount += 1;\n if (fileCount > MAX_FILES_WALKED) {\n truncated = true;\n return;\n }\n try {\n const content = await fs.readFile(full, \"utf8\");\n if (content.length > 0) {\n const lines = content.split(/\\r?\\n/).length;\n physicalLoc += content.endsWith(\"\\n\") ? lines - 1 : lines;\n }\n } catch {\n // Unreadable file (permissions, binary). Skip silently.\n }\n }\n }\n\n await walk(workspaceRoot);\n return { physicalLoc, fileCount, truncated };\n}\n", "/**\n * On-disk SARIF 2.1.0 store with finding deduplication.\n *\n * The Stop quality gate and the `ingest_sarif` MCP tool both need a\n * single, consolidated view of every finding produced across the current\n * session. This module provides:\n *\n * - `loadLatest()` \u2014 read the consolidated SARIF document from disk,\n * or return an empty seed when no report exists yet.\n * - `ingestRun()` \u2014 merge a new SARIF run from an external scanner\n * (Semgrep, ESLint, Bandit, Stryker, ...) into the\n * in-memory store, deduplicating by\n * `(ruleId, uri, startLine, startColumn)`.\n * - `persist()` \u2014 atomically write the consolidated document back\n * to disk so other processes (the dashboard) can\n * read it.\n *\n * The store is intentionally simple: it does NOT attempt to preserve\n * per-tool run separation inside the persisted file. Instead, every\n * ingested run is flattened into a single `runs[0]` entry whose `tool.driver`\n * is claude-crap itself, and the original scanner name is recorded on\n * each finding via the `properties.sourceTool` field. This keeps the\n * consolidated document easy to diff between sessions.\n *\n * @module sarif/sarif-store\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\nimport { buildSarifDocument, type SarifFinding, type SarifLevel } from \"./sarif-builder.js\";\n\n/**\n * The shape of a persisted SARIF 2.1.0 document, narrowed to the fields\n * we actually read and write. The full spec has many more optional\n * fields; we ignore them on read and do not emit them on write.\n */\nexport interface PersistedSarif {\n readonly $schema?: string;\n readonly version: \"2.1.0\";\n readonly runs: ReadonlyArray<SarifRun>;\n}\n\ninterface SarifRun {\n readonly tool: {\n readonly driver: {\n readonly name: string;\n readonly version: string;\n readonly informationUri?: string;\n readonly rules?: ReadonlyArray<unknown>;\n };\n };\n readonly results: ReadonlyArray<SarifResult>;\n}\n\ninterface SarifResult {\n readonly ruleId: string;\n readonly level?: SarifLevel;\n readonly message: { readonly text: string };\n readonly locations?: ReadonlyArray<SarifResultLocation>;\n readonly properties?: Record<string, unknown>;\n}\n\ninterface SarifResultLocation {\n readonly physicalLocation?: {\n readonly artifactLocation?: { readonly uri?: string };\n readonly region?: {\n readonly startLine?: number;\n readonly startColumn?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n };\n };\n}\n\n/**\n * Options accepted by the {@link SarifStore} constructor.\n */\nexport interface SarifStoreOptions {\n /** Workspace root. Used to resolve relative `outputDir`. */\n readonly workspaceRoot: string;\n /** Directory (absolute or workspace-relative) where reports are written. */\n readonly outputDir: string;\n /** Filename for the consolidated SARIF document. Defaults to `latest.sarif`. */\n readonly fileName?: string;\n}\n\n/**\n * A finding together with its deduplication key. Used internally and\n * returned by {@link SarifStore.ingestRun} so callers can see which\n * findings were accepted.\n */\nexport interface IngestedFinding extends SarifFinding {\n /** Stable deduplication key, shape: `ruleId|uri|line|col`. */\n readonly dedupKey: string;\n /** Name of the scanner that produced the finding (propagated from `sourceTool`). */\n readonly sourceTool: string;\n}\n\n/**\n * On-disk SARIF store.\n */\nexport class SarifStore {\n private readonly filePath: string;\n /** In-memory index of findings keyed by their dedup string. */\n private readonly findings = new Map<string, IngestedFinding>();\n /** Tool invocations we have already ingested, for telemetry. */\n private toolInvocations = 0;\n\n constructor(options: SarifStoreOptions) {\n const dir = isAbsolute(options.outputDir)\n ? options.outputDir\n : resolve(options.workspaceRoot, options.outputDir);\n this.filePath = join(dir, options.fileName ?? \"latest.sarif\");\n }\n\n /**\n * Absolute path to the consolidated SARIF file on disk.\n */\n get consolidatedReportPath(): string {\n return this.filePath;\n }\n\n /**\n * Load the consolidated document from disk into memory. If the file is\n * missing, the store is initialized empty. Top-level parsing errors\n * still throw (a file that is not valid JSON, or that declares a\n * different SARIF version, is a real safety signal). However, once\n * the document is parsed, malformed individual runs and results are\n * tolerated: F-A08-01 showed that a single bad entry in `latest.sarif`\n * could crash the MCP server on boot and persistently DoS the\n * developer. Each run / result is wrapped in its own try/catch so a\n * single bad entry logs to stderr and is dropped, but the rest of\n * the file still loads.\n *\n * @throws When the file exists but is not valid SARIF 2.1.0 JSON.\n */\n async loadLatest(): Promise<void> {\n try {\n const raw = await fs.readFile(this.filePath, \"utf8\");\n const parsed = JSON.parse(raw) as PersistedSarif;\n if (parsed.version !== \"2.1.0\") {\n throw new Error(`Expected SARIF 2.1.0, got ${parsed.version}`);\n }\n this.findings.clear();\n // Defensive against tampered / mis-generated files: `runs` must\n // be an array. Anything else is dropped with a stderr warning.\n if (!Array.isArray(parsed.runs)) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: 'runs' is not an array, dropping entire document\\n`,\n );\n return;\n }\n for (const run of parsed.runs) {\n try {\n if (!run || typeof run !== \"object\" || !Array.isArray(run.results)) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: skipping run with non-iterable 'results'\\n`,\n );\n continue;\n }\n for (const result of run.results) {\n try {\n const finding = hydrateFindingFromResult(result);\n if (finding) this.findings.set(finding.dedupKey, finding);\n } catch (entryErr) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: dropping malformed result: ${(entryErr as Error).message}\\n`,\n );\n }\n }\n } catch (runErr) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: dropping malformed run: ${(runErr as Error).message}\\n`,\n );\n }\n }\n } catch (err) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === \"ENOENT\") {\n // No report on disk yet \u2014 normal for a fresh workspace.\n this.findings.clear();\n return;\n }\n throw new Error(\n `[sarif-store] Failed to load consolidated report at ${this.filePath}: ${error.message}`,\n { cause: err },\n );\n }\n }\n\n /**\n * Merge a raw SARIF document (from any external scanner) into the\n * store, deduplicating by `(ruleId, uri, startLine, startColumn)`. The\n * last writer wins for the message and level fields \u2014 later ingestions\n * can refine earlier ones.\n *\n * @param sarifDocument The raw SARIF document as received from the tool.\n * @param sourceTool Stable identifier of the producing scanner.\n * @returns Stats describing what was accepted.\n */\n ingestRun(\n sarifDocument: PersistedSarif,\n sourceTool: string,\n ): { accepted: number; duplicates: number; total: number } {\n if (sarifDocument.version !== \"2.1.0\") {\n throw new Error(\n `[sarif-store] ingestRun received version ${sarifDocument.version}, expected 2.1.0`,\n );\n }\n\n this.toolInvocations += 1;\n let accepted = 0;\n let duplicates = 0;\n let total = 0;\n\n for (const run of sarifDocument.runs) {\n for (const result of run.results) {\n total += 1;\n const finding = hydrateFindingFromResult(result, sourceTool);\n if (!finding) continue;\n if (this.findings.has(finding.dedupKey)) {\n duplicates += 1;\n // Overwrite with the latest metadata so the consolidated view\n // reflects the most recent scanner output for this location.\n this.findings.set(finding.dedupKey, finding);\n continue;\n }\n this.findings.set(finding.dedupKey, finding);\n accepted += 1;\n }\n }\n\n return { accepted, duplicates, total };\n }\n\n /**\n * Snapshot all currently tracked findings as a plain array. Mostly\n * useful for tests and for the dashboard API.\n */\n list(): ReadonlyArray<IngestedFinding> {\n return Array.from(this.findings.values());\n }\n\n /**\n * Atomically write the consolidated document back to disk. Uses a\n * temporary file and `rename` so concurrent readers never observe\n * a half-written document.\n */\n async persist(): Promise<void> {\n const doc = this.toSarifDocument();\n await fs.mkdir(dirname(this.filePath), { recursive: true });\n const tmp = `${this.filePath}.${process.pid}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(doc, null, 2), \"utf8\");\n await fs.rename(tmp, this.filePath);\n }\n\n /**\n * Build the current consolidated SARIF document from the in-memory\n * findings without touching disk.\n */\n toSarifDocument() {\n // Strip the store-only `dedupKey` and `sourceTool` fields before\n // serializing, but keep `sourceTool` in the per-finding `properties`\n // bag so consumers can still trace origin.\n const findings: SarifFinding[] = Array.from(this.findings.values()).map((f) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: f.message,\n location: f.location,\n properties: {\n ...(f.properties ?? {}),\n sourceTool: f.sourceTool,\n },\n }));\n\n return buildSarifDocument(\n {\n name: \"claude-crap\",\n version: \"0.1.0\",\n informationUri: \"https://github.com/local/claude-crap\",\n },\n findings,\n );\n }\n\n /**\n * Number of unique findings currently tracked.\n */\n size(): number {\n return this.findings.size;\n }\n\n /**\n * Number of times `ingestRun` has been called on this instance.\n */\n get invocationsCount(): number {\n return this.toolInvocations;\n }\n}\n\n/**\n * Convert a raw SARIF `result` object into an {@link IngestedFinding}.\n * Returns `null` when the result is malformed (missing ruleId, message,\n * or physical location), since a finding without coordinates cannot be\n * deduplicated and is therefore useless.\n *\n * @param result Raw SARIF `result` object from the scanner's document.\n * @param sourceTool Optional scanner identifier. If omitted, we read it\n * from `result.properties.sourceTool` (used when\n * reloading a persisted report).\n * @returns The hydrated finding, or `null` when invalid.\n */\nfunction hydrateFindingFromResult(\n result: SarifResult,\n sourceTool?: string,\n): IngestedFinding | null {\n if (!result.ruleId || !result.message?.text) return null;\n const loc = result.locations?.[0]?.physicalLocation;\n const uri = loc?.artifactLocation?.uri;\n const region = loc?.region;\n if (!uri || region?.startLine === undefined || region.startColumn === undefined) return null;\n\n const resolvedSourceTool =\n sourceTool ??\n (typeof result.properties?.sourceTool === \"string\"\n ? (result.properties.sourceTool as string)\n : \"unknown\");\n\n const level: SarifLevel = result.level ?? \"warning\";\n const dedupKey = `${result.ruleId}|${uri}|${region.startLine}|${region.startColumn}`;\n\n return {\n ruleId: result.ruleId,\n level,\n message: result.message.text,\n location: {\n uri,\n startLine: region.startLine,\n startColumn: region.startColumn,\n ...(region.endLine !== undefined ? { endLine: region.endLine } : {}),\n ...(region.endColumn !== undefined ? { endColumn: region.endColumn } : {}),\n },\n ...(result.properties ? { properties: result.properties } : {}),\n dedupKey,\n sourceTool: resolvedSourceTool,\n };\n}\n", "/**\n * Minimal SARIF 2.1.0 document builder.\n *\n * Every report that leaves the MCP server on its way to the agent is\n * normalized to SARIF 2.1.0 first. This module provides the typed\n * helpers used to wrap raw findings in the canonical\n * `tool \u2192 runs \u2192 results` taxonomy with exact file coordinates.\n *\n * Per-scanner adapters (Semgrep, ESLint, Bandit, Stryker) live under\n * `src/adapters/` and call into `buildSarifDocument` through the\n * `wrapResultsInSarif` helper in `src/adapters/common.ts`. The\n * on-disk deduplication store lives in `./sarif-store.ts`.\n *\n * The SARIF 2.1.0 spec lives at:\n * https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html\n *\n * @module sarif/sarif-builder\n */\n\n/**\n * Severity levels supported by SARIF 2.1.0. They map 1:1 to the\n * `result.level` field. `\"error\"` is the strongest, `\"none\"` is informational.\n */\nexport type SarifLevel = \"none\" | \"note\" | \"warning\" | \"error\";\n\n/**\n * Physical location of a finding inside a source artifact. `startLine` and\n * `startColumn` are 1-based, matching the SARIF spec. `endLine` and\n * `endColumn` are optional \u2014 omit them for point-like findings.\n */\nexport interface SarifLocation {\n /** Artifact URI, typically a file path relative to the workspace root. */\n readonly uri: string;\n /** 1-based line number where the finding starts. */\n readonly startLine: number;\n /** 1-based column number where the finding starts. */\n readonly startColumn: number;\n /** Optional 1-based line number where the finding ends. */\n readonly endLine?: number;\n /** Optional 1-based column number where the finding ends. */\n readonly endColumn?: number;\n}\n\n/**\n * A single finding ready to be embedded in a SARIF run. This is the\n * internal shape used by claude-crap adapters; it is converted into the\n * official SARIF `result` object by {@link buildSarifDocument}.\n */\nexport interface SarifFinding {\n /** Stable rule identifier (e.g. `\"SONAR-CRAP-001\"`, `\"semgrep.python.sqli\"`). */\n readonly ruleId: string;\n /** Severity level for this finding. */\n readonly level: SarifLevel;\n /** Human-readable message describing the finding. */\n readonly message: string;\n /** Physical location where the finding was detected. */\n readonly location: SarifLocation;\n /** Optional extra metadata stored in the SARIF `properties` bag. */\n readonly properties?: Record<string, unknown>;\n}\n\n/**\n * Metadata describing the tool that produced a SARIF run. The `name` is\n * required by the spec; `version` is strongly recommended so that dashboard\n * diffs can distinguish between scanner releases.\n */\nexport interface SarifToolInfo {\n /** Tool display name (e.g. `\"claude-crap\"`, `\"semgrep\"`). */\n readonly name: string;\n /** Tool semantic version. */\n readonly version: string;\n /** Optional URL pointing to the tool's documentation or home page. */\n readonly informationUri?: string;\n}\n\n/**\n * Build a minimal but valid SARIF 2.1.0 document from a list of findings.\n *\n * The returned object conforms to the SARIF JSON schema hosted at:\n * https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\n *\n * Rules are deduplicated by `ruleId` and emitted in the `tool.driver.rules`\n * array so that downstream consumers (Claude Code, the dashboard, or any\n * third-party SARIF viewer) can render a rule index.\n *\n * @param tool Metadata about the producing tool.\n * @param findings Findings to include in the single run.\n * @returns A SARIF 2.1.0 document literal (frozen by `as const`).\n */\nexport function buildSarifDocument(tool: SarifToolInfo, findings: ReadonlyArray<SarifFinding>) {\n return {\n $schema: \"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\",\n version: \"2.1.0\",\n runs: [\n {\n tool: {\n driver: {\n name: tool.name,\n version: tool.version,\n informationUri: tool.informationUri ?? \"https://github.com/local/claude-crap\",\n // Deduplicate rules by id while preserving insertion order so\n // the emitted `rules` array matches the order findings appear.\n rules: Array.from(\n new Map(\n findings.map((f) => [\n f.ruleId,\n {\n id: f.ruleId,\n shortDescription: { text: f.ruleId },\n defaultConfiguration: { level: f.level },\n },\n ]),\n ).values(),\n ),\n },\n },\n results: findings.map((f) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: { text: f.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: f.location.uri },\n region: {\n startLine: f.location.startLine,\n startColumn: f.location.startColumn,\n ...(f.location.endLine !== undefined ? { endLine: f.location.endLine } : {}),\n ...(f.location.endColumn !== undefined ? { endColumn: f.location.endColumn } : {}),\n },\n },\n },\n ],\n ...(f.properties ? { properties: f.properties } : {}),\n })),\n },\n ],\n } as const;\n}\n", "/**\n * AJV-backed minimal SARIF 2.1.0 document validator.\n *\n * F-A05-01: the `ingest_sarif` MCP tool accepts a caller-supplied\n * `sarifDocument` object and, before this module existed, only\n * checked `version === \"2.1.0\"`. That was enough for tool-call\n * dispatch but not for the payload itself \u2014 a SARIF with a missing\n * `runs[]`, a `results` array of wrong-type entries, or a result\n * without a `ruleId` would still be accepted by the MCP tool and\n * flow through to the store, the dashboard, and any downstream\n * consumer that uploads claude-crap's SARIF to GitHub code-scanning\n * or an IDE viewer.\n *\n * This module uses the `ajv` dependency (already in package.json) to\n * compile a minimal JSON Schema that covers exactly the fields\n * claude-crap reads: `version`, `runs`, `runs[].tool.driver.name`,\n * and the per-result shape. Everything else (tool metadata, rule\n * definitions, snippets, etc.) is passthrough \u2014 we do not enforce\n * the full SARIF 2.1.0 spec because claude-crap does not consume\n * those fields.\n *\n * The compiled validator is cached so the ~5 ms AJV compile cost is\n * paid once per MCP server process, not once per ingestion.\n *\n * @module sarif/sarif-validator\n */\n\nimport { Ajv, type ValidateFunction } from \"ajv\";\n\n/**\n * Minimal JSON Schema covering every field claude-crap reads from a\n * SARIF 2.1.0 document. Passthrough fields are allowed because\n * `additionalProperties` is left at the default (`true`).\n *\n * Keep this schema in sync with `hydrateFindingFromResult` in\n * `src/sarif/sarif-store.ts` \u2014 anything the store reads MUST be\n * covered here, and nothing else should be enforced.\n */\nconst SARIF_MINIMAL_SCHEMA = {\n type: \"object\",\n properties: {\n version: { type: \"string\", enum: [\"2.1.0\"] },\n $schema: { type: \"string\" },\n runs: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n tool: {\n type: \"object\",\n properties: {\n driver: {\n type: \"object\",\n properties: {\n name: { type: \"string\", minLength: 1 },\n version: { type: \"string\" },\n },\n required: [\"name\"],\n },\n },\n required: [\"driver\"],\n },\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n ruleId: { type: \"string\", minLength: 1 },\n level: { type: \"string\", enum: [\"none\", \"note\", \"warning\", \"error\"] },\n message: {\n type: \"object\",\n properties: { text: { type: \"string\", minLength: 1 } },\n required: [\"text\"],\n },\n locations: { type: \"array\" },\n properties: { type: \"object\" },\n },\n required: [\"ruleId\", \"message\"],\n },\n },\n },\n required: [\"tool\", \"results\"],\n },\n },\n },\n required: [\"version\", \"runs\"],\n} as const;\n\n/**\n * Lazily-compiled validator instance. `null` until the first call to\n * {@link validateSarifDocument}, then reused for the lifetime of the\n * process.\n */\nlet cachedValidator: ValidateFunction | null = null;\n\n/**\n * Returned by {@link validateSarifDocument} when the document fails\n * schema validation. Includes the full AJV error array for callers\n * that want to surface structured diagnostics.\n */\nexport class SarifValidationError extends Error {\n public readonly errors: unknown;\n\n constructor(message: string, errors: unknown) {\n super(message);\n this.name = \"SarifValidationError\";\n this.errors = errors;\n }\n}\n\n/**\n * Obtain the compiled AJV validator, compiling on first use.\n *\n * The schema above intentionally allows passthrough fields on every\n * object (AJV's default `additionalProperties: true`). We disable\n * `strict` so AJV does not warn about benign constructs like the\n * `format`/`enum` combination.\n */\nfunction getValidator(): ValidateFunction {\n if (cachedValidator) return cachedValidator;\n const ajv = new Ajv({ allErrors: false, strict: false });\n const validator = ajv.compile(SARIF_MINIMAL_SCHEMA);\n cachedValidator = validator;\n return validator;\n}\n\n/**\n * Validate a SARIF 2.1.0 document against the minimal schema. Throws\n * {@link SarifValidationError} when the document does not match.\n *\n * @param doc Document to validate. May be any value \u2014 the validator\n * treats non-object inputs as a schema violation.\n * @throws {@link SarifValidationError} on any validation failure.\n */\nexport function validateSarifDocument(doc: unknown): void {\n const validator = getValidator();\n if (validator(doc)) return;\n const first = validator.errors?.[0];\n const path = first?.instancePath?.length ? first.instancePath : \"<root>\";\n const message = first?.message ?? \"unknown validation error\";\n throw new SarifValidationError(\n `[sarif-validator] SARIF document is not valid 2.1.0: ${path} ${message}`,\n validator.errors ?? null,\n );\n}\n", "/**\n * Workspace-level sonar configuration loader.\n *\n * Every subsystem that can be made stricter or looser (the Stop\n * quality gate, the `score_project` tool's `isError` flag) consults\n * this loader to decide how hard to push back when a policy fails.\n * Teams adopt claude-crap in stages:\n *\n * - `strict` (default) \u2014 the Stop hook exits 2 on any policy\n * failure and the `score_project` tool returns `isError: true`.\n * Matches the current, hard-coded behavior.\n * - `warn` \u2014 the Stop hook exits 0 but writes the\n * full verdict to stdout so the agent still sees every failing\n * rule in its hook transcript. `score_project.isError` stays\n * false even on a failing project.\n * - `advisory` \u2014 the Stop hook exits 0 and writes a\n * single-line summary. Minimal pressure on the agent.\n *\n * The loader resolves the `strictness` value in strict priority\n * order so a team's committed default can be overridden per-session\n * without editing the file:\n *\n * 1. `CLAUDE_CRAP_STRICTNESS` environment variable\n * 2. `.claude-crap.json` at the workspace root\n * 3. Hardcoded default `\"strict\"` (zero behavior change for\n * installs that never create the file)\n *\n * The loader is intentionally tiny \u2014 it does a single synchronous\n * file read, one optional env probe, and validates the string\n * against the enum. A hook script can call it from inside its\n * 15-second budget without breaking a sweat.\n *\n * @module crap-config\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Exhaustive list of valid strictness values. Keep this in sync with\n * the `Strictness` type below \u2014 the tuple is `as const` so TypeScript\n * derives the union from the same source of truth.\n */\nexport const STRICTNESS_VALUES = [\"strict\", \"warn\", \"advisory\"] as const;\n\n/**\n * Union of valid strictness values. Used by every consumer of\n * {@link CrapConfig} to branch on the mode without dealing with\n * arbitrary strings.\n */\nexport type Strictness = (typeof STRICTNESS_VALUES)[number];\n\n/**\n * Hardcoded default used when neither the environment variable nor\n * `.claude-crap.json` provides a value. Chosen as `\"strict\"` so the\n * plugin adopts gradually on existing codebases without blocking.\n * Teams that want hard enforcement can set `\"strict\"` in\n * `.claude-crap.json` or via `CLAUDE_CRAP_STRICTNESS=strict`.\n */\nexport const DEFAULT_STRICTNESS: Strictness = \"warn\";\n\n/**\n * Thrown by {@link loadCrapConfig} when the configuration is\n * rejected. Callers in the hook layer fall back to the default on a\n * throw so a busted config never deadlocks the user, while callers\n * in the MCP server surface the error verbatim.\n */\nexport class CrapConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CrapConfigError\";\n }\n}\n\n/**\n * Structure of the resolved sonar configuration returned by\n * {@link loadCrapConfig}. The shape is deliberately minimal for\n * v0.1.0; future releases may add threshold overrides under the\n * same `.claude-crap.json` file.\n */\nexport interface CrapConfig {\n /** Final strictness, after env override, file, and default fallback. */\n readonly strictness: Strictness;\n /** Where the strictness value actually came from. Useful for diagnostics. */\n readonly strictnessSource: \"env\" | \"file\" | \"default\";\n /** User-defined exclusion patterns (directories with trailing `/`, or file globs). */\n readonly exclude: ReadonlyArray<string>;\n /** Relative paths to directories containing sub-projects (e.g. `[\"apps\", \"packages\"]`). */\n readonly projectDirs: ReadonlyArray<string>;\n}\n\n/**\n * Options accepted by {@link loadCrapConfig}. The only required\n * field is the workspace root the loader should search for\n * `.claude-crap.json`.\n */\nexport interface LoadCrapConfigOptions {\n /**\n * Absolute path to the workspace root. The loader reads\n * `.claude-crap.json` from this directory only \u2014 it does not\n * walk parent directories.\n */\n readonly workspaceRoot: string;\n}\n\n/**\n * Resolve the effective sonar configuration for a given workspace\n * root. Pure function except for the one synchronous file read on\n * `<workspaceRoot>/.claude-crap.json` and the two env lookups.\n *\n * @param options Search options. Only `workspaceRoot` is required.\n * @returns The resolved {@link CrapConfig}.\n * @throws {@link CrapConfigError} on any invalid input.\n */\nexport function loadCrapConfig(options: LoadCrapConfigOptions): CrapConfig {\n // Always read the file to extract `exclude`, even when strictness\n // comes from the environment variable.\n const fileResult = readFromFile(options.workspaceRoot);\n const exclude = fileResult?.exclude ?? [];\n const projectDirs = fileResult?.projectDirs ?? [];\n\n const envRaw = process.env[\"CLAUDE_CRAP_STRICTNESS\"];\n if (typeof envRaw === \"string\" && envRaw.trim() !== \"\") {\n const normalized = envRaw.trim().toLowerCase();\n if (!isStrictness(normalized)) {\n throw new CrapConfigError(\n `[crap-config] CLAUDE_CRAP_STRICTNESS=\"${envRaw}\" is not a valid strictness. ` +\n `Expected one of: ${STRICTNESS_VALUES.join(\", \")}.`,\n );\n }\n return { strictness: normalized, strictnessSource: \"env\", exclude, projectDirs };\n }\n\n if (fileResult?.strictness) {\n return { strictness: fileResult.strictness, strictnessSource: \"file\", exclude, projectDirs };\n }\n\n return { strictness: DEFAULT_STRICTNESS, strictnessSource: \"default\", exclude, projectDirs };\n}\n\n/**\n * Attempt to read and validate `.claude-crap.json` at the\n * workspace root. Returns `null` when the file is missing (which\n * is the common case for fresh installs). Throws\n * {@link CrapConfigError} on any other failure mode \u2014 a malformed\n * JSON file, a non-object root, a missing or wrong-type\n * `strictness` field, or an unknown enum value \u2014 so the caller\n * cannot accidentally drop into the default on a typo.\n *\n * @param workspaceRoot Absolute workspace root.\n * @returns The validated strictness, or `null` when no\n * file is present.\n */\ninterface FileResult {\n strictness: Strictness | null;\n exclude: string[];\n projectDirs: string[];\n}\n\nfunction readFromFile(workspaceRoot: string): FileResult | null {\n const filePath = join(workspaceRoot, \".claude-crap.json\");\n let raw: string;\n try {\n raw = readFileSync(filePath, \"utf8\");\n } catch (err) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === \"ENOENT\") return null;\n throw new CrapConfigError(\n `[crap-config] Failed to read ${filePath}: ${error.message}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new CrapConfigError(\n `[crap-config] ${filePath} is not valid JSON: ${(err as Error).message}`,\n );\n }\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath} must be a JSON object at the top level`,\n );\n }\n const doc = parsed as Record<string, unknown>;\n\n // Parse strictness\n let strictness: Strictness | null = null;\n if (\"strictness\" in doc) {\n const value = doc[\"strictness\"];\n if (typeof value !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'strictness' must be a string, got ${typeof value}`,\n );\n }\n const normalized = value.trim().toLowerCase();\n if (!isStrictness(normalized)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'strictness' is \"${value}\"; ` +\n `expected one of ${STRICTNESS_VALUES.join(\", \")}.`,\n );\n }\n strictness = normalized;\n }\n\n // Parse exclude\n let exclude: string[] = [];\n if (\"exclude\" in doc) {\n const raw = doc[\"exclude\"];\n if (!Array.isArray(raw)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'exclude' must be an array of strings`,\n );\n }\n for (const item of raw) {\n if (typeof item !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: every entry in 'exclude' must be a string, got ${typeof item}`,\n );\n }\n }\n exclude = raw as string[];\n }\n\n // Parse projectDirs\n let projectDirs: string[] = [];\n if (\"projectDirs\" in doc) {\n const raw = doc[\"projectDirs\"];\n if (!Array.isArray(raw)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'projectDirs' must be an array of strings`,\n );\n }\n for (const item of raw) {\n if (typeof item !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: every entry in 'projectDirs' must be a string, got ${typeof item}`,\n );\n }\n }\n projectDirs = raw as string[];\n }\n\n return { strictness, exclude, projectDirs };\n}\n\n/**\n * Runtime type guard for the {@link Strictness} union. Lets callers\n * narrow an arbitrary string to the union without casting.\n *\n * @param value Arbitrary string.\n * @returns `true` when `value` is a recognized strictness.\n */\nfunction isStrictness(value: string): value is Strictness {\n return (STRICTNESS_VALUES as ReadonlyArray<string>).includes(value);\n}\n", "/**\n * Deterministic test-file resolver used by the `require_test_harness`\n * MCP tool.\n *\n * Given a production source file (for example `src/foo/bar.ts`), this\n * module enumerates the conventional locations where a matching test\n * file would live and returns the first existing match \u2014 or `null` when\n * none of the candidates exist.\n *\n * This is a TypeScript twin of `hooks/lib/test-harness.mjs`. The two\n * are intentionally independent so neither side has to import files\n * from outside its own project tree:\n *\n * - Hooks use the `.mjs` copy (vanilla JS, zero deps, runs everywhere).\n * - The MCP server uses this typed copy so its consumers get full\n * type safety and so the server stays a self-contained npm package.\n *\n * Both copies implement the same conventions and are validated against\n * the same unit tests \u2014 see `src/tests/test-harness.test.ts`.\n *\n * @module tools/test-harness\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\n\n/**\n * Result of probing the filesystem for a matching test file.\n */\nexport interface TestFileResolution {\n /** Absolute path of the first matching test file, or `null` when none exists. */\n readonly testFile: string | null;\n /** Absolute paths of every location the resolver tried. */\n readonly candidates: ReadonlyArray<string>;\n /** `true` when the input path itself is a test file. */\n readonly isTestFile: boolean;\n}\n\n/** Matches `.test.` and `.spec.` suffixes inside a file basename. */\nconst TEST_SUFFIX_PATTERN = /\\.(test|spec)\\./;\n\n/**\n * Return `true` when the given path is already a test file. Matching is\n * done against the basename (`foo.test.ts`, `test_foo.py`) and against\n * common test directory names in the path (`__tests__`, `tests`, `test`).\n *\n * @param filePath An absolute or relative source path.\n */\nexport function isTestFile(filePath: string): boolean {\n const base = basename(filePath);\n if (TEST_SUFFIX_PATTERN.test(base)) return true;\n if (base.startsWith(\"test_\") && base.endsWith(\".py\")) return true;\n const parts = filePath.split(sep);\n return parts.includes(\"__tests__\") || parts.includes(\"tests\") || parts.includes(\"test\");\n}\n\n/**\n * Enumerate every plausible test file path for a given production source\n * file. Does not touch the filesystem \u2014 the caller is expected to probe\n * existence separately (see {@link findTestFile}).\n *\n * Supported conventions, in the order they are probed:\n *\n * 1. Sibling `<base>.test.<ext>` / `<base>.spec.<ext>`\n * 2. Sibling `__tests__/<base>.test.<ext>`\n * 3. Mirror tree under `tests/`, `test/`, or `__tests__/` at the\n * workspace root (e.g. `tests/src/foo/bar.test.ts`)\n * 4. **Nearest-ancestor flat test directory**: walk up from the source\n * file's directory toward the workspace root, and at every ancestor\n * check for `tests/<base>.test.<ext>`. Matches layouts where tests\n * live in a single flat directory near the source (this project\n * uses it for `src/mcp-server/src/tests/`).\n * 5. Python-specific: sibling `test_<base>.py` and mirror-tree\n * `tests/.../test_<base>.py`.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param filePath Absolute path to the production file.\n * @returns Ordered list of absolute candidate paths.\n */\nexport function candidatePaths(workspaceRoot: string, filePath: string): ReadonlyArray<string> {\n const absSource = resolve(filePath);\n const ext = extname(absSource);\n const base = basename(absSource, ext);\n const dir = dirname(absSource);\n const absWorkspace = resolve(workspaceRoot);\n const relFromRoot = relative(absWorkspace, absSource);\n const relDir = dirname(relFromRoot);\n\n const candidates = new Set<string>();\n\n // 1. Sibling <base>.test.<ext> / <base>.spec.<ext>\n candidates.add(join(dir, `${base}.test${ext}`));\n candidates.add(join(dir, `${base}.spec${ext}`));\n\n // 2. Sibling __tests__/<base>.test.<ext>\n candidates.add(join(dir, \"__tests__\", `${base}.test${ext}`));\n candidates.add(join(dir, \"__tests__\", `${base}.spec${ext}`));\n\n // 3. Mirror tree under tests/, test/, or __tests__ at the workspace root.\n for (const testRoot of [\"tests\", \"test\", \"__tests__\"]) {\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}.test${ext}`));\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}.spec${ext}`));\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}${ext}`));\n }\n\n // 4. Nearest-ancestor flat test directory. Walk up from `dir` to\n // `absWorkspace`, and at each ancestor probe for a flat\n // `tests/<base>.test.<ext>` (or `test/`, `__tests__/`) layout.\n let current = dir;\n while (current.length >= absWorkspace.length) {\n for (const testRoot of [\"tests\", \"test\", \"__tests__\"]) {\n candidates.add(join(current, testRoot, `${base}.test${ext}`));\n candidates.add(join(current, testRoot, `${base}.spec${ext}`));\n candidates.add(join(current, testRoot, `${base}${ext}`));\n }\n if (current === absWorkspace) break;\n const parent = dirname(current);\n if (parent === current) break; // reached filesystem root, stop\n current = parent;\n }\n\n // 5. Python-specific variants.\n if (ext === \".py\") {\n candidates.add(join(dir, `test_${base}.py`));\n candidates.add(join(absWorkspace, \"tests\", `test_${base}.py`));\n candidates.add(join(absWorkspace, \"tests\", relDir, `test_${base}.py`));\n }\n\n return Array.from(candidates);\n}\n\n/**\n * Probe the filesystem and return the first candidate that exists, or\n * `null` when none of them do. Returns early with `isTestFile: true`\n * when the input is already a test file.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param filePath Absolute or relative path to the production file.\n */\nexport async function findTestFile(\n workspaceRoot: string,\n filePath: string,\n): Promise<TestFileResolution> {\n const absolute = isAbsolute(filePath) ? filePath : resolve(workspaceRoot, filePath);\n if (isTestFile(absolute)) {\n return { testFile: absolute, candidates: [absolute], isTestFile: true };\n }\n const candidates = candidatePaths(workspaceRoot, absolute);\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n return { testFile: candidate, candidates, isTestFile: false };\n } catch {\n // Probe next candidate.\n }\n }\n return { testFile: null, candidates, isTestFile: false };\n}\n", "/**\n * Orchestrator: detect available scanners, run them, and ingest results.\n *\n * This module ties together the detector, runner, and adapter pipeline\n * into a single `autoScan()` function that:\n *\n * 1. Probes the workspace for available scanners\n * 2. Executes detected scanners in parallel\n * 3. Routes each scanner's output through its adapter\n * 4. Ingests the normalized SARIF into the store\n *\n * The function is designed to be called:\n * - At MCP server boot (fire-and-forget, non-blocking)\n * - On demand via the `auto_scan` MCP tool\n *\n * Failures in individual scanners are logged and skipped \u2014 a broken\n * Semgrep install should not prevent ESLint from running.\n *\n * @module scanner/auto-scan\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Logger } from \"pino\";\nimport { detectScanners, detectMonorepoScanners, type ScannerDetection } from \"./detector.js\";\nimport { runScanner, type ScannerRunResult } from \"./runner.js\";\nimport { bootstrapScanner } from \"./bootstrap.js\";\nimport { scanComplexity, type ComplexityScanResult } from \"./complexity-scanner.js\";\nimport { adaptScannerOutput, type KnownScanner } from \"../adapters/index.js\";\nimport type { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-scanner result within the auto-scan summary.\n */\nexport interface ScannerResult {\n scanner: KnownScanner;\n success: boolean;\n findingsIngested: number;\n durationMs: number;\n error?: string;\n}\n\n/**\n * Complete result of an auto-scan run.\n */\nexport interface AutoScanResult {\n /** Detection results for all four scanners. */\n detected: ScannerDetection[];\n /** Execution + ingestion results for scanners that were available. */\n results: ScannerResult[];\n /** Total findings ingested across all scanners. */\n totalFindings: number;\n /** Wall-clock time for the entire auto-scan. */\n totalDurationMs: number;\n /** Result of the built-in cyclomatic complexity scan, when enabled. */\n complexityScan?: ComplexityScanResult;\n}\n\n// \u2500\u2500 Orchestrator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Ingest a single scanner's raw output through its adapter and into\n * the SARIF store. Returns the number of accepted findings.\n */\nfunction ingestScannerRun(\n scanner: KnownScanner,\n rawOutput: string,\n sarifStore: SarifStore,\n): { accepted: number } {\n // Parse the raw output \u2014 adapters accept string or object\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawOutput);\n } catch {\n // Semgrep outputs SARIF as a string, others are JSON.\n // If parsing fails, pass the raw string to the adapter.\n parsed = rawOutput;\n }\n\n const adapted = adaptScannerOutput(scanner, parsed);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n return { accepted: stats.accepted };\n}\n\n/**\n * Auto-detect, run, and ingest all available scanners.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @param sarifStore Live SARIF store to ingest findings into.\n * @param logger Pino logger for progress and error reporting.\n * @returns Summary of what was detected, run, and ingested.\n */\nexport async function autoScan(\n workspaceRoot: string,\n sarifStore: SarifStore,\n logger: Logger,\n options?: { engine?: TreeSitterEngine; cyclomaticMax?: number; exclude?: ReadonlyArray<string> },\n): Promise<AutoScanResult> {\n const start = Date.now();\n\n // 1. Detect available scanners (root + monorepo subdirs)\n const detected = await detectScanners(workspaceRoot);\n const monorepoDetected = await detectMonorepoScanners(workspaceRoot);\n\n // Merge monorepo detections \u2014 skip duplicates (same scanner already found at root)\n const rootScannerSet = new Set(detected.filter((d) => d.available).map((d) => d.scanner));\n for (const md of monorepoDetected) {\n if (!rootScannerSet.has(md.scanner)) {\n detected.push(md);\n }\n }\n\n const available = detected.filter((d) => d.available);\n\n logger.info(\n {\n detected: detected.map((d) => `${d.scanner}:${d.available}`),\n monorepo: monorepoDetected.length,\n available: available.length,\n },\n \"auto-scan: detection complete\",\n );\n\n // If ESLint is detected (e.g. in package.json) but has no config file,\n // bootstrap will create one before we try to scan.\n const eslintConfigFiles = [\n \"eslint.config.js\", \"eslint.config.mjs\", \"eslint.config.cjs\",\n \"eslint.config.ts\", \"eslint.config.mts\", \"eslint.config.cts\",\n \".eslintrc.js\", \".eslintrc.cjs\", \".eslintrc.yaml\",\n \".eslintrc.yml\", \".eslintrc.json\",\n ];\n const eslintDetected = available.some((d) => d.scanner === \"eslint\");\n const hasEslintConfig = eslintConfigFiles.some((f) => existsSync(join(workspaceRoot, f)));\n\n if (eslintDetected && !hasEslintConfig) {\n logger.info(\"auto-scan: ESLint detected but no config \u2014 running bootstrap\");\n try {\n const bootstrapResult = await bootstrapScanner(workspaceRoot, sarifStore, logger);\n if (bootstrapResult.autoScanResult) {\n return bootstrapResult.autoScanResult;\n }\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: bootstrap config creation failed\",\n );\n }\n }\n\n if (available.length === 0) {\n // No scanners configured \u2014 try to bootstrap one automatically.\n logger.info(\"auto-scan: no scanners found, attempting bootstrap\");\n try {\n const bootstrapResult = await bootstrapScanner(workspaceRoot, sarifStore, logger);\n if (bootstrapResult.autoScanResult) {\n return bootstrapResult.autoScanResult;\n }\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: bootstrap failed \u2014 continuing with empty results\",\n );\n }\n\n return {\n detected,\n results: [],\n totalFindings: 0,\n totalDurationMs: Date.now() - start,\n };\n }\n\n // 2. Run all available scanners in parallel (each from its detected workingDir)\n const runResults = await Promise.allSettled(\n available.map((d) => runScanner(d.scanner, workspaceRoot, d.workingDir ? { workingDir: d.workingDir } : undefined)),\n );\n\n // 3. Ingest results\n const results: ScannerResult[] = [];\n let totalFindings = 0;\n let persistNeeded = false;\n\n for (let i = 0; i < available.length; i++) {\n const detection = available[i]!;\n const settled = runResults[i]!;\n\n if (settled.status === \"rejected\") {\n const error = String(settled.reason);\n logger.warn(\n { scanner: detection.scanner, error },\n \"auto-scan: scanner execution rejected\",\n );\n results.push({\n scanner: detection.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: 0,\n error,\n });\n continue;\n }\n\n const runResult: ScannerRunResult = settled.value;\n\n if (!runResult.success) {\n logger.warn(\n { scanner: runResult.scanner, error: runResult.error },\n \"auto-scan: scanner returned failure\",\n );\n results.push({\n scanner: runResult.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: runResult.durationMs,\n error: runResult.error ?? \"unknown error\",\n });\n continue;\n }\n\n // Ingest through adapter pipeline\n try {\n const { accepted } = ingestScannerRun(\n runResult.scanner,\n runResult.rawOutput,\n sarifStore,\n );\n totalFindings += accepted;\n persistNeeded = true;\n\n logger.info(\n { scanner: runResult.scanner, accepted, durationMs: runResult.durationMs },\n \"auto-scan: scanner ingested\",\n );\n\n results.push({\n scanner: runResult.scanner,\n success: true,\n findingsIngested: accepted,\n durationMs: runResult.durationMs,\n });\n } catch (err) {\n const error = (err as Error).message;\n logger.warn(\n { scanner: runResult.scanner, error },\n \"auto-scan: adapter/ingestion failed\",\n );\n results.push({\n scanner: runResult.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: runResult.durationMs,\n error,\n });\n }\n }\n\n // 4. Persist consolidated SARIF if anything was ingested\n if (persistNeeded) {\n await sarifStore.persist();\n }\n\n // 5. Run built-in cyclomatic complexity scanner\n let complexityScan: ComplexityScanResult | undefined;\n if (options?.engine) {\n try {\n complexityScan = await scanComplexity(\n workspaceRoot,\n options.engine,\n sarifStore,\n { cyclomaticMax: options.cyclomaticMax ?? 15, ...(options.exclude ? { exclude: options.exclude } : {}) },\n logger,\n );\n totalFindings += complexityScan.violations;\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: complexity scanner failed \u2014 continuing without it\",\n );\n }\n }\n\n return {\n detected,\n results,\n totalFindings,\n totalDurationMs: Date.now() - start,\n ...(complexityScan ? { complexityScan } : {}),\n };\n}\n", "/**\n * Auto-detect which scanners are available in the current workspace.\n *\n * For each of the four supported scanners (ESLint, Semgrep, Bandit,\n * Stryker) the detector probes three signal layers in order:\n *\n * 1. Config file existence (fastest \u2014 a single `fs.stat`)\n * 2. Package.json dependency (for JS-ecosystem scanners)\n * 3. Binary availability via `which` (slowest \u2014 spawns a child process)\n *\n * Detection short-circuits on the first hit, so a project that has an\n * `eslint.config.mjs` will never shell out to `which eslint`.\n *\n * The module is side-effect-free beyond filesystem reads and one\n * `child_process.execFile` per binary probe.\n *\n * @module scanner/detector\n */\n\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport type { KnownScanner } from \"../adapters/common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Result of probing a single scanner's availability.\n */\nexport interface ScannerDetection {\n /** Which scanner was probed. */\n scanner: KnownScanner;\n /** Whether the scanner is available and can be executed. */\n available: boolean;\n /** Human-readable reason for the verdict. */\n reason: string;\n /** Path to the config file that triggered detection, if any. */\n configPath?: string;\n /** Working directory to run the scanner from (defaults to workspace root). */\n workingDir?: string;\n}\n\n// \u2500\u2500 Detection signals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Config file globs and package.json keys per scanner. Order matters:\n * the first matching config file short-circuits further probes.\n */\ninterface ScannerSignals {\n configFiles: string[];\n packageJsonKeys: string[];\n binaryNames: string[];\n}\n\nconst SCANNER_SIGNALS: Record<KnownScanner, ScannerSignals> = {\n eslint: {\n configFiles: [\n \"eslint.config.js\",\n \"eslint.config.mjs\",\n \"eslint.config.cjs\",\n \"eslint.config.ts\",\n \"eslint.config.mts\",\n \"eslint.config.cts\",\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \".eslintrc.yaml\",\n \".eslintrc.yml\",\n \".eslintrc.json\",\n ],\n packageJsonKeys: [\"eslint\"],\n binaryNames: [\"eslint\"],\n },\n semgrep: {\n configFiles: [\n \".semgrep.yml\",\n \".semgrep.yaml\",\n \".semgrep.json\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"semgrep\"],\n },\n bandit: {\n configFiles: [\n \".bandit\",\n \"bandit.yaml\",\n \"bandit.yml\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"bandit\"],\n },\n stryker: {\n configFiles: [\n \"stryker.conf.js\",\n \"stryker.conf.mjs\",\n \"stryker.conf.cjs\",\n \"stryker.conf.json\",\n \".strykerrc\",\n \".strykerrc.json\",\n ],\n packageJsonKeys: [\"@stryker-mutator/core\"],\n binaryNames: [\"stryker\"],\n },\n dart_analyze: {\n configFiles: [\n \"analysis_options.yaml\",\n \"pubspec.yaml\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"dart\"],\n },\n dotnet_format: {\n configFiles: [],\n packageJsonKeys: [],\n binaryNames: [\"dotnet\"],\n },\n};\n\n// \u2500\u2500 Probes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Check if any of the scanner's config files exist in the workspace.\n */\nfunction probeConfigFiles(\n workspaceRoot: string,\n scanner: KnownScanner,\n): { found: boolean; path?: string } {\n const signals = SCANNER_SIGNALS[scanner];\n for (const file of signals.configFiles) {\n const fullPath = join(workspaceRoot, file);\n if (existsSync(fullPath)) {\n return { found: true, path: fullPath };\n }\n }\n return { found: false };\n}\n\n/**\n * Check if the scanner appears in package.json deps or devDeps.\n */\nfunction probePackageJson(\n workspaceRoot: string,\n scanner: KnownScanner,\n): boolean {\n const signals = SCANNER_SIGNALS[scanner];\n if (signals.packageJsonKeys.length === 0) return false;\n\n const pkgPath = join(workspaceRoot, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n const deps = {\n ...(typeof pkg.dependencies === \"object\" && pkg.dependencies !== null\n ? (pkg.dependencies as Record<string, string>)\n : {}),\n ...(typeof pkg.devDependencies === \"object\" && pkg.devDependencies !== null\n ? (pkg.devDependencies as Record<string, string>)\n : {}),\n };\n return signals.packageJsonKeys.some((key) => key in deps);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a binary is available on PATH via `which`.\n */\nfunction probeBinary(binaryName: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\"which\", [binaryName], { timeout: 5_000 }, (err) => {\n resolve(err === null);\n });\n });\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect which supported scanners are available in the given workspace.\n * Probes config files, package.json, and binary availability in order,\n * short-circuiting on first match.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @returns One {@link ScannerDetection} per known scanner.\n */\nexport async function detectScanners(\n workspaceRoot: string,\n): Promise<ScannerDetection[]> {\n const scanners: KnownScanner[] = [\"eslint\", \"semgrep\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"];\n\n const results = await Promise.all(\n scanners.map(async (scanner): Promise<ScannerDetection> => {\n // 1. Config file probe (fastest)\n const configProbe = probeConfigFiles(workspaceRoot, scanner);\n if (configProbe.found && configProbe.path) {\n return {\n scanner,\n available: true,\n reason: `config file found: ${configProbe.path.replace(workspaceRoot + \"/\", \"\")}`,\n configPath: configProbe.path,\n };\n }\n\n // 2. Package.json probe \u2014 declared in deps/devDeps, but is it\n // actually installed? Check node_modules/.bin/ for the binary.\n if (probePackageJson(workspaceRoot, scanner)) {\n const binName = SCANNER_SIGNALS[scanner].binaryNames[0];\n const binPath = binName ? join(workspaceRoot, \"node_modules\", \".bin\", binName) : null;\n const installed = binPath !== null && existsSync(binPath);\n return {\n scanner,\n available: installed,\n reason: installed\n ? \"found in package.json and installed\"\n : `found in package.json but not installed (run \\`npm install\\`)`,\n };\n }\n\n // 3. Binary probe (slowest)\n const signals = SCANNER_SIGNALS[scanner];\n for (const bin of signals.binaryNames) {\n if (await probeBinary(bin)) {\n return {\n scanner,\n available: true,\n reason: `binary \"${bin}\" found on PATH`,\n };\n }\n }\n\n return {\n scanner,\n available: false,\n reason: \"no config file, package.json entry, or binary found\",\n };\n }),\n );\n\n return results;\n}\n\n// \u2500\u2500 Monorepo subdirectory probing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Common monorepo directory names that may contain workspace\n * subdirectories. Checked one level deep only.\n */\nconst MONOREPO_DIRS = [\"apps\", \"packages\", \"libs\", \"modules\", \"services\"];\n\n/**\n * Detect scanners in monorepo subdirectories. Probes first-level\n * children of common monorepo directories (apps/, packages/, etc.)\n * and npm workspaces for scanner config files. Returns detections\n * with a `workingDir` pointing to the subdirectory.\n *\n * This catches e.g. `apps/mobile/pubspec.yaml` in a polyglot monorepo\n * where the root-level detector only finds ESLint.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @returns Additional detections from subdirectories (may be empty).\n */\nexport async function detectMonorepoScanners(\n workspaceRoot: string,\n): Promise<ScannerDetection[]> {\n const subdirs = new Set<string>();\n\n // 1. Read npm workspaces from package.json\n try {\n const pkgPath = join(workspaceRoot, \"package.json\");\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n if (Array.isArray(pkg.workspaces)) {\n for (const ws of pkg.workspaces) {\n if (typeof ws === \"string\" && !ws.includes(\"*\")) {\n const full = resolve(workspaceRoot, ws);\n if (existsSync(full)) subdirs.add(full);\n }\n }\n }\n } catch {\n // No package.json or not parseable \u2014 continue\n }\n\n // 2. Scan common monorepo directories one level deep\n for (const dir of MONOREPO_DIRS) {\n const full = join(workspaceRoot, dir);\n try {\n const entries = readdirSync(full, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(full, entry.name));\n }\n }\n } catch {\n // Directory doesn't exist \u2014 skip\n }\n }\n\n if (subdirs.size === 0) return [];\n\n // 3. Probe each subdirectory for scanner config files\n const detections: ScannerDetection[] = [];\n const scanners: KnownScanner[] = [\"eslint\", \"semgrep\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"];\n\n for (const subdir of subdirs) {\n for (const scanner of scanners) {\n const configProbe = probeConfigFiles(subdir, scanner);\n if (!configProbe.found) continue;\n\n // For dart_analyze, also verify the binary is on PATH\n if (scanner === \"dart_analyze\") {\n const hasBinary = await probeBinary(\"dart\");\n if (!hasBinary) continue;\n }\n\n const relDir = subdir.replace(workspaceRoot + \"/\", \"\");\n detections.push({\n scanner,\n available: true,\n reason: `config file found in ${relDir}/`,\n ...(configProbe.path ? { configPath: configProbe.path } : {}),\n workingDir: subdir,\n });\n }\n }\n\n return detections;\n}\n\n// Exported for testing\nexport { SCANNER_SIGNALS, MONOREPO_DIRS };\n", "/**\n * Execute a single scanner CLI and capture its raw output.\n *\n * Each scanner has a fixed invocation that produces the format its\n * adapter expects:\n *\n * - ESLint \u2192 `npx eslint -f json .` (JSON array)\n * - Semgrep \u2192 `semgrep --sarif --quiet .` (SARIF 2.1.0)\n * - Bandit \u2192 `bandit -f json -r . -q` (JSON object)\n * - Stryker \u2192 `npx stryker run` then read `reports/mutation/mutation.json`\n *\n * ESLint and Bandit exit non-zero when findings exist \u2014 that is\n * expected, not an error. The runner captures stdout regardless of\n * exit code for those scanners.\n *\n * Stryker is special: it writes to a file instead of stdout, so we\n * read the output file after the process exits.\n *\n * @module scanner/runner\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { KnownScanner } from \"../adapters/common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Result of executing a single scanner.\n */\nexport interface ScannerRunResult {\n /** Which scanner was executed. */\n scanner: KnownScanner;\n /** Whether execution completed and produced parseable output. */\n success: boolean;\n /** The scanner's raw output (stdout or file contents). */\n rawOutput: string;\n /** Error message when `success` is false. */\n error?: string;\n /** Wall-clock execution time in milliseconds. */\n durationMs: number;\n}\n\n// \u2500\u2500 Scanner command definitions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface ScannerCommand {\n /** Binary or npx command. */\n command: string;\n /** CLI arguments. */\n args: string[];\n /** Maximum execution time in ms. */\n timeoutMs: number;\n /** If true, non-zero exit is expected when findings exist. */\n nonZeroIsNormal: boolean;\n /** If set, read output from this file instead of stdout. */\n outputFile?: string;\n}\n\nfunction getScannerCommand(\n scanner: KnownScanner,\n workspaceRoot: string,\n): ScannerCommand {\n switch (scanner) {\n case \"eslint\":\n return {\n command: \"npx\",\n args: [\"eslint\", \"-f\", \"json\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n };\n case \"semgrep\":\n return {\n command: \"semgrep\",\n args: [\"--sarif\", \"--quiet\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: false,\n };\n case \"bandit\":\n return {\n command: \"bandit\",\n args: [\"-f\", \"json\", \"-r\", \".\", \"-q\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n };\n case \"stryker\":\n return {\n command: \"npx\",\n args: [\"stryker\", \"run\"],\n timeoutMs: 300_000,\n nonZeroIsNormal: false,\n outputFile: join(workspaceRoot, \"reports\", \"mutation\", \"mutation.json\"),\n };\n case \"dart_analyze\":\n return {\n command: \"dart\",\n args: [\"analyze\", \"--format=json\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true, // exits 3 when findings exist\n };\n case \"dotnet_format\":\n return {\n command: \"dotnet\",\n args: [\n \"format\",\n \"--verify-no-changes\",\n \"--report\",\n join(workspaceRoot, \".claude-crap\", \"dotnet-report.json\"),\n ],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n outputFile: join(workspaceRoot, \".claude-crap\", \"dotnet-report.json\"),\n };\n }\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Execute a scanner CLI and return its raw output.\n *\n * @param scanner Which scanner to run.\n * @param workspaceRoot Absolute path to the project root (used as cwd).\n * @param options Optional overrides.\n * @returns A {@link ScannerRunResult} with stdout or file output.\n */\nexport function runScanner(\n scanner: KnownScanner,\n workspaceRoot: string,\n options?: { workingDir?: string },\n): Promise<ScannerRunResult> {\n const start = Date.now();\n const cwd = options?.workingDir ?? workspaceRoot;\n const cmd = getScannerCommand(scanner, cwd);\n\n return new Promise((resolve) => {\n execFile(\n cmd.command,\n cmd.args,\n {\n cwd,\n timeout: cmd.timeoutMs,\n maxBuffer: 50 * 1024 * 1024, // 50 MB \u2014 large codebases produce verbose output\n env: { ...process.env, FORCE_COLOR: \"0\" }, // suppress ANSI in output\n },\n (err, stdout, stderr) => {\n const durationMs = Date.now() - start;\n\n // For scanners where non-zero exit means \"findings exist\",\n // we still have valid output in stdout. But if the scanner\n // crashed (e.g. ESLint with no config file), treat it as a\n // real failure even when nonZeroIsNormal is set.\n const isFatalError = cmd.nonZeroIsNormal\n && err\n && (!stdout?.trim() || stderr?.includes(\"Oops!\") || stderr?.includes(\"couldn't find\"));\n\n if (err && (!cmd.nonZeroIsNormal || isFatalError)) {\n // Stryker: check if the output file was written despite the error\n if (cmd.outputFile && existsSync(cmd.outputFile)) {\n try {\n const fileOutput = readFileSync(cmd.outputFile, \"utf-8\");\n resolve({\n scanner,\n success: true,\n rawOutput: fileOutput,\n durationMs,\n });\n return;\n } catch {\n // Fall through to error path\n }\n }\n\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: stderr || (err as Error).message,\n durationMs,\n });\n return;\n }\n\n // For file-based output (Stryker), read from file\n if (cmd.outputFile) {\n if (existsSync(cmd.outputFile)) {\n try {\n const fileOutput = readFileSync(cmd.outputFile, \"utf-8\");\n resolve({\n scanner,\n success: true,\n rawOutput: fileOutput,\n durationMs,\n });\n return;\n } catch (readErr) {\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: `Failed to read output file: ${(readErr as Error).message}`,\n durationMs,\n });\n return;\n }\n }\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: `Scanner completed but output file not found: ${cmd.outputFile}`,\n durationMs,\n });\n return;\n }\n\n // Stdout-based output\n const output = stdout.trim();\n if (!output) {\n resolve({\n scanner,\n success: true,\n rawOutput: \"[]\", // ESLint returns empty when no files match\n durationMs,\n });\n return;\n }\n\n resolve({\n scanner,\n success: true,\n rawOutput: output,\n durationMs,\n });\n },\n );\n });\n}\n\n// Exported for testing\nexport { getScannerCommand, type ScannerCommand };\n", "/**\n * Bootstrap a scanner for projects that don't have one configured.\n *\n * Detects the project type from workspace signals (package.json,\n * tsconfig.json, pyproject.toml, pom.xml, *.csproj, etc.), installs\n * the appropriate scanner, creates a minimal config file, and runs\n * `autoScan()` to verify and ingest findings immediately.\n *\n * Coverage maps to the five languages the tree-sitter engine supports:\n *\n * - JavaScript / TypeScript \u2192 ESLint (npm install + flat config)\n * - Python \u2192 Bandit (install instructions only \u2014 virtualenv boundary)\n * - Java \u2192 Semgrep (install instructions)\n * - C# \u2192 Semgrep (install instructions)\n * - Unknown \u2192 Semgrep (polyglot fallback)\n *\n * For JS/TS projects the tool runs `npm install --save-dev` and writes\n * an `eslint.config.mjs`. For all other languages it returns manual\n * install instructions rather than executing package managers whose\n * environment assumptions may not hold.\n *\n * @module scanner/bootstrap\n */\n\nimport { existsSync, writeFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport type { Logger } from \"pino\";\nimport type { KnownScanner } from \"../adapters/common.js\";\nimport { adaptScannerOutput } from \"../adapters/index.js\";\nimport { detectScanners } from \"./detector.js\";\nimport { runScanner } from \"./runner.js\";\nimport type { AutoScanResult, ScannerResult } from \"./auto-scan.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detected project type, aligned with tree-sitter supported languages.\n */\nexport type ProjectType =\n | \"javascript\"\n | \"typescript\"\n | \"python\"\n | \"java\"\n | \"csharp\"\n | \"dart\"\n | \"unknown\";\n\n/**\n * A single step in the bootstrap process.\n */\nexport interface BootstrapStep {\n /** What was attempted (e.g. \"install eslint\", \"create eslint.config.mjs\"). */\n action: string;\n /** Whether the step completed successfully. */\n success: boolean;\n /** Human-readable detail (command output, error message, or instruction). */\n detail: string;\n}\n\n/**\n * Complete result of a bootstrap_scanner invocation.\n */\nexport interface BootstrapResult {\n /** Detected project type based on workspace signals. */\n projectType: ProjectType;\n /** Whether a scanner was already configured (detected by detector.ts). */\n alreadyConfigured: boolean;\n /** Which scanners were already available, if any. */\n existingScanners: string[];\n /** Steps executed (or instructions returned) during bootstrap. */\n steps: BootstrapStep[];\n /** The auto-scan result after installation (null if skipped). */\n autoScanResult: AutoScanResult | null;\n /** Whether the overall bootstrap succeeded. */\n success: boolean;\n /** Summary message suitable for display. */\n summary: string;\n}\n\n// \u2500\u2500 Project type detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect the project type from workspace signals.\n *\n * Checks in priority order: TypeScript, JavaScript, Python, Java,\n * C#, then unknown. TypeScript wins over plain JavaScript because\n * `tsconfig.json` implies a superset.\n */\nexport function detectProjectType(workspaceRoot: string): ProjectType {\n const has = (file: string) => existsSync(join(workspaceRoot, file));\n\n // JS/TS detection \u2014 package.json is the anchor\n if (has(\"package.json\")) {\n if (has(\"tsconfig.json\")) return \"typescript\";\n return \"javascript\";\n }\n\n // Python detection\n if (has(\"pyproject.toml\") || has(\"setup.py\") || has(\"requirements.txt\")) {\n return \"python\";\n }\n\n // Java detection\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) {\n return \"java\";\n }\n\n // C# detection\n if (has(\"Directory.Build.props\")) return \"csharp\";\n try {\n const entries = readdirSync(workspaceRoot);\n if (entries.some((e) => e.endsWith(\".csproj\") || e.endsWith(\".sln\"))) {\n return \"csharp\";\n }\n } catch {\n // readdirSync can fail on permissions \u2014 fall through\n }\n\n // Dart / Flutter detection\n if (has(\"pubspec.yaml\")) return \"dart\";\n\n return \"unknown\";\n}\n\n// \u2500\u2500 ESLint config generation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Generate a minimal ESLint flat config (ESLint 9+).\n *\n * @param isTypeScript Include typescript-eslint when true.\n * @returns The config file content as a string.\n */\nexport function generateEslintConfig(isTypeScript: boolean): string {\n if (isTypeScript) {\n return `import js from \"@eslint/js\";\nimport tseslint from \"typescript-eslint\";\n\nexport default tseslint.config(\n js.configs.recommended,\n ...tseslint.configs.recommended,\n {\n ignores: [\n \"dist/\",\n \"node_modules/\",\n \"coverage/\",\n \"**/bundle/\",\n \"**/vendor/\",\n \"**/*.min.js\",\n ],\n },\n);\n`;\n }\n\n return `import js from \"@eslint/js\";\n\nexport default [\n js.configs.recommended,\n {\n ignores: [\n \"dist/\",\n \"node_modules/\",\n \"coverage/\",\n \"**/bundle/\",\n \"**/vendor/\",\n \"**/*.min.js\",\n ],\n },\n];\n`;\n}\n\n// \u2500\u2500 Installation helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run `npm install --save-dev` for the given packages.\n */\nfunction npmInstall(\n workspaceRoot: string,\n packages: string[],\n): Promise<BootstrapStep> {\n return new Promise((resolve) => {\n execFile(\n \"npm\",\n [\"install\", \"--save-dev\", ...packages],\n {\n cwd: workspaceRoot,\n timeout: 120_000,\n env: { ...process.env, FORCE_COLOR: \"0\" },\n },\n (err, stdout, stderr) => {\n if (err) {\n resolve({\n action: `npm install --save-dev ${packages.join(\" \")}`,\n success: false,\n detail: stderr || (err as Error).message,\n });\n return;\n }\n resolve({\n action: `npm install --save-dev ${packages.join(\" \")}`,\n success: true,\n detail: `installed ${packages.join(\", \")}`,\n });\n },\n );\n });\n}\n\n/**\n * Write the ESLint config file to the workspace root.\n * Returns failure if the file already exists.\n */\nfunction writeEslintConfigFile(\n workspaceRoot: string,\n isTypeScript: boolean,\n): BootstrapStep {\n const configPath = join(workspaceRoot, \"eslint.config.mjs\");\n if (existsSync(configPath)) {\n return {\n action: \"create eslint.config.mjs\",\n success: true,\n detail: \"eslint.config.mjs already exists \u2014 skipped\",\n };\n }\n\n try {\n writeFileSync(configPath, generateEslintConfig(isTypeScript), \"utf-8\");\n return {\n action: \"create eslint.config.mjs\",\n success: true,\n detail: `created eslint.config.mjs (${isTypeScript ? \"TypeScript\" : \"JavaScript\"} template)`,\n };\n } catch (err) {\n return {\n action: \"create eslint.config.mjs\",\n success: false,\n detail: (err as Error).message,\n };\n }\n}\n\n// \u2500\u2500 Scanner-to-language mapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Map project type \u2192 recommended scanner and install instructions.\n */\ninterface ScannerRecommendation {\n scanner: KnownScanner;\n canAutoInstall: boolean;\n installInstructions: string;\n}\n\nfunction getRecommendation(projectType: ProjectType): ScannerRecommendation {\n switch (projectType) {\n case \"javascript\":\n case \"typescript\":\n return {\n scanner: \"eslint\",\n canAutoInstall: true,\n installInstructions: \"npm install --save-dev eslint @eslint/js\",\n };\n case \"python\":\n return {\n scanner: \"bandit\",\n canAutoInstall: false,\n installInstructions:\n \"pip install bandit (or: pipx install bandit, poetry add --group dev bandit)\",\n };\n case \"java\":\n return {\n scanner: \"semgrep\",\n canAutoInstall: false,\n installInstructions:\n \"brew install semgrep (or: pip install semgrep, pipx install semgrep)\",\n };\n case \"csharp\":\n return {\n scanner: \"dotnet_format\",\n canAutoInstall: false,\n installInstructions:\n \"Install the .NET SDK: https://dotnet.microsoft.com/download\",\n };\n case \"dart\":\n return {\n scanner: \"dart_analyze\",\n canAutoInstall: false,\n installInstructions:\n \"Install the Dart SDK: https://dart.dev/get-dart (or Flutter SDK which includes Dart)\",\n };\n case \"unknown\":\n return {\n scanner: \"semgrep\",\n canAutoInstall: false,\n installInstructions:\n \"brew install semgrep (or: pip install semgrep, pipx install semgrep)\",\n };\n }\n}\n\n// \u2500\u2500 Main orchestrator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Bootstrap a scanner for the current workspace.\n *\n * 1. Check if a scanner is already configured (short-circuit if so)\n * 2. Detect the project type\n * 3. Install the recommended scanner (or return instructions)\n * 4. Run auto_scan to verify and ingest findings\n *\n * @param workspaceRoot Absolute path to the project root.\n * @param sarifStore Live SARIF store for auto-scan ingestion.\n * @param logger Pino logger for progress reporting.\n */\nexport async function bootstrapScanner(\n workspaceRoot: string,\n sarifStore: SarifStore,\n logger: Logger,\n): Promise<BootstrapResult> {\n // 1. Check existing scanners\n const detections = await detectScanners(workspaceRoot);\n const available = detections.filter((d) => d.available);\n\n // A scanner is truly \"configured\" only if it also has a config\n // file. ESLint in package.json without eslint.config.mjs will crash.\n const eslintNeedsConfig = available.some((d) => d.scanner === \"eslint\")\n && !detections.some((d) => d.scanner === \"eslint\" && d.configPath);\n\n if (available.length > 0 && !eslintNeedsConfig) {\n const existingScanners = available.map((d) => d.scanner);\n logger.info(\n { existingScanners },\n \"bootstrap: scanner(s) already configured \u2014 skipping\",\n );\n return {\n projectType: detectProjectType(workspaceRoot),\n alreadyConfigured: true,\n existingScanners,\n steps: [],\n autoScanResult: null,\n success: true,\n summary: `Scanner(s) already configured: ${existingScanners.join(\", \")}. Run auto_scan to ingest findings.`,\n };\n }\n\n // 2. Detect project type\n const projectType = detectProjectType(workspaceRoot);\n const recommendation = getRecommendation(projectType);\n const steps: BootstrapStep[] = [];\n\n logger.info(\n { projectType, scanner: recommendation.scanner },\n \"bootstrap: detected project type\",\n );\n\n // 3. Install scanner (skip npm install if already in package.json)\n if (recommendation.canAutoInstall) {\n const isTypeScript = projectType === \"typescript\";\n const eslintAlreadyInstalled = available.some((d) => d.scanner === \"eslint\");\n\n if (!eslintAlreadyInstalled) {\n const packages = isTypeScript\n ? [\"eslint\", \"@eslint/js\", \"typescript-eslint\"]\n : [\"eslint\", \"@eslint/js\"];\n const installStep = await npmInstall(workspaceRoot, packages);\n steps.push(installStep);\n if (!installStep.success) {\n // npm install failed \u2014 skip config creation, fall through to result\n return buildResult(projectType, steps, null);\n }\n } else {\n steps.push({\n action: \"npm install eslint\",\n success: true,\n detail: \"eslint already in package.json \u2014 skipped install\",\n });\n }\n\n // Always create config if missing\n const configStep = writeEslintConfigFile(workspaceRoot, isTypeScript);\n steps.push(configStep);\n } else {\n // Python / Java / C# / Unknown: return instructions\n steps.push({\n action: `suggest ${recommendation.scanner} install`,\n success: true,\n detail: recommendation.installInstructions,\n });\n }\n\n // 4. Run scanner directly if installation succeeded (inline scan\n // to avoid circular dependency \u2014 autoScan calls bootstrapScanner)\n const installSucceeded = steps.every((s) => s.success);\n let autoScanResult: AutoScanResult | null = null;\n\n if (installSucceeded && recommendation.canAutoInstall) {\n try {\n const scanStart = Date.now();\n const postDetections = await detectScanners(workspaceRoot);\n const postAvailable = postDetections.filter((d) => d.available);\n const scanResults: ScannerResult[] = [];\n let scanFindings = 0;\n\n const settled = await Promise.allSettled(\n postAvailable.map((d) => runScanner(d.scanner, workspaceRoot)),\n );\n\n for (let i = 0; i < postAvailable.length; i++) {\n const det = postAvailable[i]!;\n const res = settled[i]!;\n\n if (res.status === \"rejected\" || !res.value.success) {\n scanResults.push({\n scanner: det.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: res.status === \"fulfilled\" ? res.value.durationMs : 0,\n error: res.status === \"rejected\"\n ? String(res.reason)\n : res.value.error ?? \"unknown error\",\n });\n continue;\n }\n\n const runResult = res.value;\n let parsed: unknown;\n try { parsed = JSON.parse(runResult.rawOutput); } catch { parsed = runResult.rawOutput; }\n const adapted = adaptScannerOutput(runResult.scanner, parsed);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n scanFindings += stats.accepted;\n\n scanResults.push({\n scanner: runResult.scanner,\n success: true,\n findingsIngested: stats.accepted,\n durationMs: runResult.durationMs,\n });\n }\n\n if (scanFindings > 0) await sarifStore.persist();\n\n autoScanResult = {\n detected: postDetections,\n results: scanResults,\n totalFindings: scanFindings,\n totalDurationMs: Date.now() - scanStart,\n };\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"bootstrap: scan after install failed\",\n );\n }\n }\n\n // 5. Build result\n return buildResult(projectType, steps, autoScanResult, recommendation);\n}\n\n/**\n * Build a BootstrapResult from the collected steps and optional scan result.\n */\nfunction buildResult(\n projectType: ProjectType,\n steps: BootstrapStep[],\n autoScanResult: AutoScanResult | null,\n recommendation?: { scanner: KnownScanner; canAutoInstall: boolean; installInstructions: string },\n): BootstrapResult {\n const success = steps.every((s) => s.success);\n const findings = autoScanResult?.totalFindings ?? 0;\n const scanner = recommendation?.scanner ?? \"unknown\";\n\n let summary: string;\n if (success && autoScanResult) {\n summary = `Configured ${scanner} for ${projectType} project. Scan found ${findings} finding(s).`;\n } else if (success && recommendation && !recommendation.canAutoInstall) {\n summary = `Detected ${projectType} project. Install ${scanner} manually: ${recommendation.installInstructions}`;\n } else if (success) {\n summary = `Configured ${scanner} for ${projectType} project.`;\n } else {\n summary = `Failed to configure ${scanner}. Check the error details in the steps.`;\n }\n\n return {\n projectType,\n alreadyConfigured: false,\n existingScanners: [],\n steps,\n autoScanResult,\n success,\n summary,\n };\n}\n", "/**\n * Cyclomatic complexity scanner.\n *\n * Walks the workspace, analyzes each supported source file with\n * tree-sitter, and emits SARIF findings for functions whose cyclomatic\n * complexity exceeds the configured threshold (`cyclomaticMax`).\n *\n * This scanner is an internal analyzer \u2014 it is NOT a \"known scanner\"\n * in the `KnownScanner` union (eslint/semgrep/bandit/stryker). It\n * bypasses the adapter pipeline and writes SARIF directly via\n * `wrapResultsInSarif()` from the common adapter helpers.\n *\n * Severity mapping:\n * - `warning` \u2014 CC > threshold but < 2\u00D7 threshold\n * - `error` \u2014 CC >= 2\u00D7 threshold (aligns with CRAP index hard block at CC >= 30)\n *\n * @module scanner/complexity-scanner\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { Logger } from \"pino\";\n\nimport { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport { detectLanguageFromPath } from \"../ast/language-config.js\";\nimport { wrapResultsInSarif, estimateEffortMinutes } from \"../adapters/common.js\";\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n\n/** Hard cap on files to prevent unbounded analysis. */\nconst MAX_FILES = 20_000;\n\n/** SARIF rule ID for cyclomatic complexity violations. */\nconst RULE_ID = \"complexity/cyclomatic-max\";\n\n/** Source tool identifier used in SARIF properties. */\nconst SOURCE_TOOL = \"complexity\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Result of a complexity scan run. */\nexport interface ComplexityScanResult {\n /** Number of source files successfully analyzed. */\n readonly filesScanned: number;\n /** Total number of functions found across all files. */\n readonly functionsAnalyzed: number;\n /** Number of functions that exceeded the threshold. */\n readonly violations: number;\n /** Wall-clock time for the entire scan. */\n readonly durationMs: number;\n}\n\n/** Configuration accepted by the scanner. */\nexport interface ComplexityScanConfig {\n /** Maximum cyclomatic complexity allowed per function. */\n readonly cyclomaticMax: number;\n /** User-defined exclusion patterns from .claude-crap.json. */\n readonly exclude?: ReadonlyArray<string>;\n}\n\n// \u2500\u2500 Scanner \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Scan a workspace for cyclomatic complexity violations.\n *\n * Walks the directory tree, analyzes each source file with the\n * tree-sitter engine, and emits SARIF findings for functions above\n * the configured threshold. Findings are ingested into the provided\n * `SarifStore` and persisted to disk.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @param engine Initialized tree-sitter engine instance.\n * @param sarifStore Live SARIF store to ingest findings into.\n * @param config Scanner configuration (threshold).\n * @param logger Pino logger for progress and error reporting.\n * @returns Summary of what was scanned and found.\n */\nexport async function scanComplexity(\n workspaceRoot: string,\n engine: TreeSitterEngine,\n sarifStore: SarifStore,\n config: ComplexityScanConfig,\n logger: Logger,\n): Promise<ComplexityScanResult> {\n const start = Date.now();\n const threshold = config.cyclomaticMax;\n const errorThreshold = threshold * 2;\n\n // 1. Collect supported source files\n const filter = createExclusionFilter(config.exclude);\n const files = await collectSourceFiles(workspaceRoot, filter);\n logger.info(\n { fileCount: files.length, threshold },\n \"complexity-scanner: starting analysis\",\n );\n\n // 2. Analyze each file and collect violations\n const sarifResults: object[] = [];\n let filesScanned = 0;\n let functionsAnalyzed = 0;\n let violations = 0;\n\n for (const filePath of files) {\n const language = detectLanguageFromPath(filePath);\n if (!language) continue;\n\n try {\n const metrics = await engine.analyzeFile({ filePath, language });\n filesScanned += 1;\n functionsAnalyzed += metrics.functions.length;\n\n for (const fn of metrics.functions) {\n if (fn.cyclomaticComplexity <= threshold) continue;\n\n const level: SarifLevel =\n fn.cyclomaticComplexity >= errorThreshold ? \"error\" : \"warning\";\n\n const relPath = relative(workspaceRoot, filePath);\n\n sarifResults.push({\n ruleId: RULE_ID,\n level,\n message: {\n text: `Function '${fn.name}' has cyclomatic complexity ${fn.cyclomaticComplexity} (threshold: ${threshold})`,\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: relPath },\n region: {\n startLine: fn.startLine,\n startColumn: 1,\n endLine: fn.endLine,\n endColumn: 1,\n },\n },\n },\n ],\n properties: {\n sourceTool: SOURCE_TOOL,\n effortMinutes: estimateEffortMinutes(level),\n cyclomaticComplexity: fn.cyclomaticComplexity,\n },\n });\n violations += 1;\n }\n } catch (err) {\n logger.warn(\n { filePath, err: (err as Error).message },\n \"complexity-scanner: failed to analyze file, skipping\",\n );\n }\n }\n\n // 3. Ingest findings into the SARIF store\n if (sarifResults.length > 0) {\n const document = wrapResultsInSarif(\n SOURCE_TOOL as never,\n \"0.1.0\",\n sarifResults,\n );\n sarifStore.ingestRun(document, SOURCE_TOOL);\n await sarifStore.persist();\n }\n\n const durationMs = Date.now() - start;\n logger.info(\n { filesScanned, functionsAnalyzed, violations, durationMs },\n \"complexity-scanner: analysis complete\",\n );\n\n return { filesScanned, functionsAnalyzed, violations, durationMs };\n}\n\n// \u2500\u2500 File walker \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Collect source files from the workspace that the tree-sitter engine\n * can analyze. Uses the shared exclusion filter for directory and file\n * filtering. Only returns files whose extension maps to a supported language.\n */\nasync function collectSourceFiles(\n workspaceRoot: string,\n filter: import(\"../shared/exclusions.js\").ExclusionFilter,\n): Promise<string[]> {\n const files: string[] = [];\n let truncated = false;\n\n async function walk(dir: string): Promise<void> {\n if (truncated) return;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (truncated) return;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!detectLanguageFromPath(entry.name)) continue;\n const relPath = relative(workspaceRoot, full);\n if (filter.shouldSkipFile(relPath, entry.name)) continue;\n files.push(full);\n if (files.length >= MAX_FILES) {\n truncated = true;\n return;\n }\n }\n }\n\n await walk(workspaceRoot);\n return files;\n}\n", "/**\n * Monorepo project discovery and project-map generation.\n *\n * At plugin boot the host can call {@link discoverProjectMap} to walk\n * a workspace, detect every sub-project's language/framework, pick the\n * right scanner, and probe whether that scanner binary is available on\n * the host PATH. The resulting {@link ProjectMap} is optionally written\n * to `.claude-crap/projects.json` via {@link persistProjectMap} so\n * subsequent boot cycles can skip the discovery work by calling\n * {@link loadProjectMap} first.\n *\n * Detection priority per sub-directory (first match wins):\n * pubspec.yaml \u2192 dart\n * tsconfig.json + package.json \u2192 typescript\n * package.json (no tsconfig) \u2192 javascript\n * pyproject.toml / setup.py / requirements.txt \u2192 python\n * pom.xml / build.gradle* \u2192 java\n * *.csproj / *.sln / Directory.Build.props \u2192 csharp\n * (none of the above) \u2192 unknown\n *\n * Scanner mapping:\n * typescript / javascript \u2192 eslint\n * python \u2192 bandit\n * java / csharp \u2192 semgrep\n * dart \u2192 dart_analyze\n * unknown \u2192 null\n *\n * @module monorepo/project-map\n */\n\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { promises as fs } from \"node:fs\";\nimport { join, basename, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detected language / platform for a workspace sub-project.\n * Mirrors the set supported by the tree-sitter engine plus Dart.\n */\nexport type ProjectType =\n | \"typescript\"\n | \"javascript\"\n | \"python\"\n | \"java\"\n | \"csharp\"\n | \"dart\"\n | \"unknown\";\n\n/**\n * A discovered sub-project within a monorepo workspace.\n */\nexport interface ProjectEntry {\n /** Human-readable name \u2014 the directory's basename (e.g. \"www\", \"mobile\"). */\n readonly name: string;\n /** Relative path from the workspace root (e.g. \"apps/www\"). */\n readonly path: string;\n /** Detected project type based on marker files. */\n readonly type: ProjectType;\n /** Recommended scanner name, or null when the type is unknown. */\n readonly scanner: string | null;\n /** Whether the scanner binary is reachable on the system PATH. */\n readonly scannerAvailable: boolean;\n}\n\n/**\n * Complete snapshot of a workspace's sub-project layout.\n */\nexport interface ProjectMap {\n /** ISO 8601 timestamp when this map was generated. */\n readonly generatedAt: string;\n /** Absolute path to the workspace root that was scanned. */\n readonly workspaceRoot: string;\n /** True when at least one sub-project was discovered. */\n readonly isMonorepo: boolean;\n /** Discovered sub-projects. Empty for single-project workspaces. */\n readonly projects: ProjectEntry[];\n}\n\n// \u2500\u2500 Internal constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * First-level directories that conventionally contain sub-projects in\n * popular monorepo layouts (Nx, Turborepo, Rush, Lerna, custom).\n */\nconst MONOREPO_DIRS = [\"apps\", \"packages\", \"libs\", \"modules\", \"services\"] as const;\n\n/**\n * Scanner recommended for each project type. `null` means no scanner\n * mapping is defined for the type (only \"unknown\" falls here).\n */\nconst SCANNER_FOR_TYPE: Record<ProjectType, string | null> = {\n typescript: \"eslint\",\n javascript: \"eslint\",\n python: \"bandit\",\n java: \"semgrep\",\n csharp: \"dotnet_format\",\n dart: \"dart_analyze\",\n unknown: null,\n};\n\n/**\n * The binary name to probe for each scanner. Binary availability is\n * checked with `which` via `execFile`, the same approach used in\n * `scanner/detector.ts`.\n */\nconst BINARY_FOR_SCANNER: Record<string, string> = {\n eslint: \"eslint\",\n bandit: \"bandit\",\n semgrep: \"semgrep\",\n dart_analyze: \"dart\",\n dotnet_format: \"dotnet\",\n};\n\n// \u2500\u2500 Binary probe \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Resolve whether the given binary name is reachable on the system\n * PATH. Uses `which` via `execFile` with a short timeout so boot\n * latency stays bounded.\n *\n * @param binaryName The executable name to look up (e.g. \"eslint\").\n * @returns True when `which` exits with code 0.\n */\nfunction probeBinary(binaryName: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\"which\", [binaryName], { timeout: 5_000 }, (err) => {\n resolve(err === null);\n });\n });\n}\n\n// \u2500\u2500 Project type detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect the dominant project type of a single directory by inspecting\n * well-known marker files. Checks are ordered so the most specific\n * signal wins (pubspec.yaml before tsconfig.json, tsconfig.json before\n * bare package.json, etc.).\n *\n * The function is synchronous because it only performs `existsSync` and\n * one `readdirSync` call (for C# extension scanning), keeping the\n * discovery loop fast and free of unnecessary Promise allocation.\n *\n * @param dir Absolute path to the directory to inspect.\n * @returns The detected {@link ProjectType}.\n */\nfunction detectProjectType(dir: string): ProjectType {\n const has = (file: string): boolean => existsSync(join(dir, file));\n\n // Dart / Flutter \u2014 check before JS because some Flutter projects also\n // have a package.json for web sub-packages.\n if (has(\"pubspec.yaml\")) return \"dart\";\n\n // JS / TS \u2014 tsconfig.json implies TypeScript superset.\n if (has(\"package.json\")) {\n if (has(\"tsconfig.json\")) return \"typescript\";\n return \"javascript\";\n }\n\n // Python\n if (has(\"pyproject.toml\") || has(\"setup.py\") || has(\"requirements.txt\")) {\n return \"python\";\n }\n\n // Java (Gradle and Maven)\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) {\n return \"java\";\n }\n\n // C# \u2014 check the well-known single-file marker first, then scan for\n // per-project extension files (.csproj / .sln) at this level only.\n if (has(\"Directory.Build.props\")) return \"csharp\";\n try {\n const entries = readdirSync(dir);\n if (entries.some((e) => e.endsWith(\".csproj\") || e.endsWith(\".sln\"))) {\n return \"csharp\";\n }\n } catch {\n // Permission error or symlink loop \u2014 treat as unknown.\n }\n\n return \"unknown\";\n}\n\n// \u2500\u2500 Subdirectory collection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Normalise an npm workspaces value (which can be a plain string array\n * or an object `{ packages: string[] }`) into a flat array of patterns.\n *\n * @param workspaces The raw value of `package.json#workspaces`.\n * @returns Array of workspace glob patterns (may be empty).\n */\nfunction extractWorkspacePatterns(workspaces: unknown): string[] {\n if (Array.isArray(workspaces)) {\n return workspaces.filter((v): v is string => typeof v === \"string\");\n }\n if (\n workspaces !== null &&\n typeof workspaces === \"object\" &&\n \"packages\" in workspaces &&\n Array.isArray((workspaces as { packages: unknown }).packages)\n ) {\n return ((workspaces as { packages: unknown[] }).packages).filter(\n (v): v is string => typeof v === \"string\",\n );\n }\n return [];\n}\n\n/**\n * Expand a single workspace glob pattern into matching absolute paths.\n *\n * Only supports the common `dir/*` form (one trailing `*`) and plain\n * paths (no glob at all). Full glob engines are deliberately avoided to\n * keep the module dependency-free.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param pattern A workspace pattern such as `\"packages/*\"` or `\"apps/web\"`.\n * @returns Absolute paths of matching directories that exist on disk.\n */\nfunction expandWorkspacePattern(\n workspaceRoot: string,\n pattern: string,\n): string[] {\n if (pattern.endsWith(\"/*\")) {\n // Glob: list one level of the parent directory.\n const parentDir = join(workspaceRoot, pattern.slice(0, -2));\n try {\n const entries = readdirSync(parentDir, { withFileTypes: true });\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith(\".\"))\n .map((e) => join(parentDir, e.name));\n } catch {\n return [];\n }\n }\n\n // Plain path \u2014 verify it exists and is a directory.\n const full = resolve(workspaceRoot, pattern);\n try {\n const entries = readdirSync(full, { withFileTypes: true });\n // readdirSync succeeds only for directories; if we got here it exists.\n void entries; // suppress unused-variable lint\n return [full];\n } catch {\n return [];\n }\n}\n\n/**\n * Collect all candidate sub-project absolute paths for the given\n * workspace root. Sources (deduplicated):\n *\n * 1. npm `workspaces` field in root `package.json` (both array and\n * object-with-packages formats; glob patterns are expanded one\n * level deep with `readdirSync`).\n * 2. One-level-deep subdirectories of conventional monorepo folders\n * (`apps/`, `packages/`, `libs/`, `modules/`, `services/`).\n *\n * Hidden directories (names starting with `.`) are always skipped.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns De-duplicated set of absolute sub-project paths.\n */\nfunction collectSubdirectories(\n workspaceRoot: string,\n extraDirs?: ReadonlyArray<string>,\n): Set<string> {\n const subdirs = new Set<string>();\n\n // 1. npm workspaces\n const pkgPath = join(workspaceRoot, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n const patterns = extractWorkspacePatterns(pkg[\"workspaces\"]);\n for (const pattern of patterns) {\n for (const absPath of expandWorkspacePattern(workspaceRoot, pattern)) {\n subdirs.add(absPath);\n }\n }\n } catch {\n // Malformed JSON or read error \u2014 skip npm workspaces source.\n }\n }\n\n // 2. User-configured projectDirs from .claude-crap.json (highest priority).\n // These can be parent directories scanned one level deep (e.g. \"apps\")\n // or direct project paths (e.g. \"tools/cli\").\n if (extraDirs && extraDirs.length > 0) {\n for (const dir of extraDirs) {\n const absDir = resolve(workspaceRoot, dir);\n if (!existsSync(absDir)) continue;\n\n // If the directory itself has a project marker, treat it as a project.\n const hasMarker = PROJECT_MARKERS.some((m) => existsSync(join(absDir, m)));\n if (hasMarker) {\n subdirs.add(absDir);\n continue;\n }\n\n // Otherwise scan one level deep (it's a parent directory like \"apps\").\n try {\n const entries = readdirSync(absDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(absDir, entry.name));\n }\n }\n } catch {\n // Not readable \u2014 skip.\n }\n }\n }\n\n // 3. Conventional monorepo directories scanned one level deep.\n // Skipped for directories already covered by user config.\n const configuredDirNames = new Set(extraDirs?.map((d) => d.split(\"/\")[0]) ?? []);\n for (const dir of MONOREPO_DIRS) {\n if (configuredDirNames.has(dir)) continue; // User config takes precedence\n const parentDir = join(workspaceRoot, dir);\n try {\n const entries = readdirSync(parentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(parentDir, entry.name));\n }\n }\n } catch {\n // Directory absent \u2014 skip.\n }\n }\n\n return subdirs;\n}\n\n/** Files that indicate a directory is a project root. */\nconst PROJECT_MARKERS = [\n \"package.json\", \"pubspec.yaml\", \"pyproject.toml\", \"setup.py\",\n \"pom.xml\", \"build.gradle\", \"build.gradle.kts\", \"Directory.Build.props\",\n];\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Discover all sub-projects in the given workspace and return a fully\n * populated {@link ProjectMap}.\n *\n * The function:\n * 1. Reads `package.json#workspaces` (supports both array and object\n * `{ packages: [...] }` formats) and resolves glob patterns.\n * 2. Also scans `apps/`, `packages/`, `libs/`, `modules/`, and\n * `services/` one level deep (mirrors `detectMonorepoScanners`).\n * 3. De-duplicates the collected paths.\n * 4. Detects the project type for each subdirectory.\n * 5. Maps project type to a recommended scanner.\n * 6. Probes scanner binary availability via `which`.\n *\n * When no sub-projects are found (single-project workspace) `projects`\n * is an empty array and `isMonorepo` is false.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns The generated {@link ProjectMap}.\n */\nexport async function discoverProjectMap(\n workspaceRoot: string,\n options?: { projectDirs?: ReadonlyArray<string> },\n): Promise<ProjectMap> {\n const subdirs = collectSubdirectories(workspaceRoot, options?.projectDirs);\n\n // Cache binary probe results so each unique scanner is only probed once.\n const binaryCache = new Map<string, Promise<boolean>>();\n\n const probeScanner = (scanner: string): Promise<boolean> => {\n const binaryName = BINARY_FOR_SCANNER[scanner];\n if (binaryName === undefined) return Promise.resolve(false);\n\n const cached = binaryCache.get(scanner);\n if (cached !== undefined) return cached;\n\n const probe = probeBinary(binaryName);\n binaryCache.set(scanner, probe);\n return probe;\n };\n\n const projectEntries = await Promise.all(\n [...subdirs].map(async (absPath): Promise<ProjectEntry> => {\n const relPath = absPath.replace(workspaceRoot + \"/\", \"\");\n const type = detectProjectType(absPath);\n const scanner = SCANNER_FOR_TYPE[type];\n const scannerAvailable =\n scanner !== null ? await probeScanner(scanner) : false;\n\n return {\n name: basename(absPath),\n path: relPath,\n type,\n scanner,\n scannerAvailable,\n };\n }),\n );\n\n // Sort deterministically by relative path so the output is stable\n // across re-runs regardless of readdirSync ordering.\n projectEntries.sort((a, b) => a.path.localeCompare(b.path));\n\n return {\n generatedAt: new Date().toISOString(),\n workspaceRoot,\n isMonorepo: projectEntries.length > 0,\n projects: projectEntries,\n };\n}\n\n/**\n * Write the project map to `.claude-crap/projects.json` under the given\n * workspace root. The `.claude-crap/` directory is created if it does\n * not already exist.\n *\n * The file is written atomically via `fs.writeFile` (Node's default\n * behaviour on POSIX is to truncate-and-rewrite, which is safe for the\n * sizes expected here).\n *\n * @param map The {@link ProjectMap} to serialise.\n * @param workspaceRoot Absolute path to the workspace root.\n */\nexport async function persistProjectMap(\n map: ProjectMap,\n workspaceRoot: string,\n): Promise<void> {\n const dir = join(workspaceRoot, \".claude-crap\");\n await fs.mkdir(dir, { recursive: true });\n const filePath = join(dir, \"projects.json\");\n await fs.writeFile(filePath, JSON.stringify(map, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Read a previously persisted {@link ProjectMap} from\n * `.claude-crap/projects.json`. Returns `null` when the file is absent\n * or cannot be parsed, so callers can fall back to\n * {@link discoverProjectMap} without special-casing errors.\n *\n * This function is intentionally synchronous so it can be called during\n * plugin boot before the async event loop is fully initialised.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns The cached {@link ProjectMap}, or `null`.\n */\nexport function loadProjectMap(workspaceRoot: string): ProjectMap | null {\n const filePath = join(workspaceRoot, \".claude-crap\", \"projects.json\");\n if (!existsSync(filePath)) return null;\n\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const parsed = JSON.parse(raw) as ProjectMap;\n\n // Minimal structural validation \u2014 guard against truncated writes.\n if (\n typeof parsed.generatedAt !== \"string\" ||\n typeof parsed.workspaceRoot !== \"string\" ||\n typeof parsed.isMonorepo !== \"boolean\" ||\n !Array.isArray(parsed.projects)\n ) {\n return null;\n }\n\n return parsed;\n } catch {\n return null;\n }\n}\n", "/**\n * JSON Schema (Draft-07) definitions for every tool exposed by the MCP server.\n *\n * Each schema uses `enum`, `pattern`, `minimum`, `maximum`, `oneOf` and\n * `additionalProperties: false` to eliminate schema hallucinations from the\n * LLM. The MCP SDK automatically validates tool-call inputs against these\n * schemas before invoking the handler \u2014 any drift produces a deterministic\n * error that the agent can consume and correct.\n *\n * These `description` fields are read by the LLM at tool-listing time and\n * become part of the agent's context, so they must be precise, imperative,\n * and never speculative. Keep them short but actionable.\n *\n * @module schemas/tool-schemas\n */\n\n// The MCP SDK consumes these as the `inputSchema` field of a Tool. We type\n// them with `as const` so TypeScript infers literal types and the MCP SDK\n// accepts them without runtime casting.\n\n/**\n * Schema for the `compute_crap` tool. Returns a CRAP score for a single\n * function and a block decision against the configured threshold.\n */\nexport const computeCrapSchema = {\n type: \"object\",\n description:\n \"Compute the CRAP (Change Risk Anti-Patterns) index for a single function. Returns the score and whether it exceeds the configured threshold. A blocked result means the function must be decomposed or covered by more tests before the Stop quality gate will pass.\",\n properties: {\n cyclomaticComplexity: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\n description: \"Cyclomatic complexity of the function (number of linearly independent paths).\",\n },\n coveragePercent: {\n type: \"number\",\n minimum: 0,\n maximum: 100,\n description: \"Test coverage percentage for the function, in the range [0, 100].\",\n },\n functionName: {\n type: \"string\",\n pattern: \"^[A-Za-z_$][A-Za-z0-9_$.:<>]*$\",\n minLength: 1,\n maxLength: 256,\n description: \"Fully qualified name of the function under analysis, used for SARIF traceability.\",\n },\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n description: \"Absolute or workspace-relative path to the source file that contains the function.\",\n },\n },\n required: [\"cyclomaticComplexity\", \"coveragePercent\", \"functionName\", \"filePath\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `compute_tdr` tool. Returns a Technical Debt Ratio and a\n * maintainability letter rating for a scope (project, module, or file).\n */\nexport const computeTdrSchema = {\n type: \"object\",\n description:\n \"Compute the Technical Debt Ratio (TDR) for a scope and return the maintainability letter rating (A..E). Rating E always halts the workflow regardless of the configured tolerance. Use this after aggregating remediation estimates from SARIF findings.\",\n properties: {\n remediationMinutes: {\n type: \"number\",\n minimum: 0,\n maximum: 10_000_000,\n description: \"Total estimated remediation effort in minutes, summed across every finding in the scope.\",\n },\n totalLinesOfCode: {\n type: \"integer\",\n minimum: 1,\n maximum: 100_000_000,\n description: \"Physical lines of code in the scope (project, module, or file).\",\n },\n scope: {\n type: \"string\",\n enum: [\"project\", \"module\", \"file\"],\n description: \"Aggregation scope for the TDR computation.\",\n },\n },\n required: [\"remediationMinutes\", \"totalLinesOfCode\", \"scope\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `analyze_file_ast` tool. Returns deterministic AST\n * metrics (LOC, cyclomatic complexity, node counts) for a source file.\n */\nexport const analyzeFileAstSchema = {\n type: \"object\",\n description:\n \"Parse a source file with tree-sitter and return deterministic metrics (lines of code, cyclomatic complexity per function, top-level node counts). Prefer this tool over reading the file directly \u2014 it is faster and will not bloat the agent context.\",\n properties: {\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n // The lookahead pattern rejects any path traversal (`../`) to prevent\n // the LLM from reading files outside the workspace. Any absolute path\n // that does not contain `../` is still allowed.\n pattern: \"^(?!.*\\\\.\\\\./).*$\",\n description: \"Path to the file to analyze. Paths containing `../` are rejected to prevent workspace escape.\",\n },\n language: {\n type: \"string\",\n enum: [\"csharp\", \"javascript\", \"typescript\", \"python\", \"java\"],\n description: \"Source language of the file. Determines which tree-sitter grammar to load.\",\n },\n },\n required: [\"filePath\", \"language\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `score_project` tool. Aggregates the latest SARIF\n * report and the workspace size into a single project score with\n * Maintainability / Reliability / Security letter grades, an overall\n * grade, the dashboard URL (when running), and the SARIF report path.\n */\nexport const scoreProjectSchema = {\n type: \"object\",\n description:\n \"Compute the aggregate project score (Maintainability / Reliability / Security / Overall A..E), and return both a chat-friendly Markdown summary and a structured JSON snapshot. Includes the local dashboard URL and the consolidated SARIF report path so the user can drill in without opening any extra tooling.\",\n properties: {\n format: {\n type: \"string\",\n enum: [\"markdown\", \"json\", \"both\"],\n description:\n \"Output format. `markdown` returns only the chat summary, `json` returns only the structured snapshot, `both` (default) returns both as separate content blocks.\",\n },\n scope: {\n type: \"string\",\n description: \"Optional project name from the project map. When provided, the score is computed only for files within that project's subtree. Omit to score the entire workspace.\",\n },\n },\n required: [],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `list_projects` tool. Returns the discovered sub-projects\n * in the workspace, or an empty list for single-project workspaces.\n */\nexport const listProjectsSchema = {\n type: \"object\",\n description: \"List all discovered sub-projects in the workspace. In a monorepo, returns each sub-project with its type, path, and recommended scanner. In a single-project workspace, returns an empty list.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `require_test_harness` tool. Checks whether a production\n * source file has an accompanying test file in any of the conventional\n * locations the resolver supports (sibling `.test.`, `__tests__/`, mirror\n * tree, Python `test_` prefix).\n */\nexport const requireTestHarnessSchema = {\n type: \"object\",\n description:\n \"Check whether a production source file has a matching test file. Returns the first existing test path, or the full list of paths the resolver probed when none exists. Use this BEFORE writing any functional code \u2014 the CLAUDE.md Golden Rule requires a test harness to exist first.\",\n properties: {\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n pattern: \"^(?!.*\\\\.\\\\./).*$\",\n description:\n \"Path to the production file. Paths containing `../` are rejected to prevent workspace escape.\",\n },\n },\n required: [\"filePath\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `ingest_scanner_output` tool. Accepts a scanner\n * identifier (Semgrep, ESLint, Bandit, Stryker) plus that scanner's\n * native output (SARIF or JSON), routes the input through the\n * matching adapter in `src/adapters/`, and persists the normalized\n * SARIF 2.1.0 document in the store.\n *\n * This tool is the preferred path for ingesting scanner output that\n * is not already SARIF \u2014 `ingest_sarif` remains the right choice\n * when you already have a SARIF document and just need deduplication.\n */\nexport const ingestScannerOutputSchema = {\n type: \"object\",\n description:\n \"Ingest a scanner's native output (Semgrep SARIF, ESLint JSON, Bandit JSON, or Stryker JSON), route it through the matching adapter, enrich every finding with an effort estimate, and persist the normalized SARIF 2.1.0 document. Prefer this tool over `ingest_sarif` whenever the scanner does not emit SARIF natively.\",\n properties: {\n scanner: {\n type: \"string\",\n enum: [\"semgrep\", \"eslint\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"],\n description: \"Identifier of the producing scanner.\",\n },\n rawOutput: {\n description:\n \"The scanner's native output. Accepts either a JSON string (as produced by the scanner's CLI) or a pre-parsed JSON object / array.\",\n oneOf: [{ type: \"string\" }, { type: \"object\" }, { type: \"array\" }],\n },\n },\n required: [\"scanner\", \"rawOutput\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `ingest_sarif` tool. Accepts a raw SARIF 2.1.0 document\n * from an external scanner, deduplicates against the internal store, and\n * normalizes the output into claude-crap's canonical format.\n */\n/**\n * Schema for the `auto_scan` tool. Auto-detects available scanners\n * in the workspace, runs them, and ingests findings into the SARIF store.\n */\n/**\n * Schema for the `bootstrap_scanner` tool. Detects project type,\n * installs the appropriate scanner, creates config files, and runs\n * auto_scan to verify.\n */\nexport const bootstrapScannerSchema = {\n type: \"object\",\n description:\n \"Detect the project type (JavaScript, TypeScript, Python, Java, C#), install the appropriate scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create a minimal config file, and run auto_scan to verify. Skips installation if a scanner is already configured. Use this when auto_scan finds no scanners and quality grades are vacuously A.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\nexport const autoScanSchema = {\n type: \"object\",\n description:\n \"Auto-detect available scanners (ESLint, Semgrep, Bandit, Stryker) in the workspace, execute them, and ingest findings into the SARIF store. Returns detection results, per-scanner execution stats, and total findings ingested. Call this to populate findings without manual scanner invocation.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\nexport const ingestSarifSchema = {\n type: \"object\",\n description:\n \"Ingest a raw SARIF 2.1.0 report produced by an external scanner (Semgrep, ESLint, Bandit, Stryker, etc.), deduplicate it against the internal store, and return the normalized document. The agent should call this once per scanner invocation, not once per finding.\",\n properties: {\n sarifDocument: {\n type: \"object\",\n description: \"A full SARIF 2.1.0 document with `version` and `runs` keys.\",\n properties: {\n version: { type: \"string\", enum: [\"2.1.0\"] },\n $schema: { type: \"string\" },\n runs: { type: \"array\", minItems: 1 },\n },\n required: [\"version\", \"runs\"],\n },\n sourceTool: {\n type: \"string\",\n pattern: \"^[a-zA-Z0-9._-]{1,64}$\",\n description: \"Stable identifier of the tool that produced the report (`semgrep`, `eslint`, `bandit`, ...).\",\n },\n },\n required: [\"sarifDocument\", \"sourceTool\"],\n additionalProperties: false,\n} as const;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,QAAsB,cAAtB,MAAiC;;AAAjC,YAAA,cAAA;AAOa,YAAA,aAAa;AAE1B,QAAa,OAAb,cAA0B,YAAW;MAEnC,YAAY,GAAS;AACnB,cAAK;AACL,YAAI,CAAC,QAAA,WAAW,KAAK,CAAC;AAAG,gBAAM,IAAI,MAAM,0CAA0C;AACnF,aAAK,MAAM;MACb;MAEA,WAAQ;AACN,eAAO,KAAK;MACd;MAEA,WAAQ;AACN,eAAO;MACT;MAEA,IAAI,QAAK;AACP,eAAO,EAAC,CAAC,KAAK,GAAG,GAAG,EAAC;MACvB;;AAlBF,YAAA,OAAA;AAqBA,QAAa,QAAb,cAA2B,YAAW;MAKpC,YAAY,MAAkC;AAC5C,cAAK;AACL,aAAK,SAAS,OAAO,SAAS,WAAW,CAAC,IAAI,IAAI;MACpD;MAEA,WAAQ;AACN,eAAO,KAAK;MACd;MAEA,WAAQ;AACN,YAAI,KAAK,OAAO,SAAS;AAAG,iBAAO;AACnC,cAAM,OAAO,KAAK,OAAO,CAAC;AAC1B,eAAO,SAAS,MAAM,SAAS;MACjC;MAEA,IAAI,MAAG;;AACL,gBAAO,KAAC,KAAK,UAAI,QAAA,OAAA,SAAA,KAAT,KAAK,OAAS,KAAK,OAAO,OAAO,CAAC,GAAW,MAAgB,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE;MACrF;MAEA,IAAI,QAAK;;AACP,gBAAO,KAAC,KAAK,YAAM,QAAA,OAAA,SAAA,KAAX,KAAK,SAAW,KAAK,OAAO,OAAO,CAAC,OAAkB,MAAK;AACjE,cAAI,aAAa;AAAM,kBAAM,EAAE,GAAG,KAAK,MAAM,EAAE,GAAG,KAAK,KAAK;AAC5D,iBAAO;QACT,GAAG,CA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AK,CAAC;AAChB,CAAC;",
4
+ "sourcesContent": ["// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record<string, number | undefined>\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n", "import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set<string>\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record<string, ValueReference[] | undefined>\n\ntype ScopeValues = {\n [Prefix in string]?: Map<unknown, ValueScopeName>\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set<ValueScopeName>\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set<string>\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n", "import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private rhs?: SafeExpr\n ) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(\n readonly lhs: Code,\n public rhs: SafeExpr,\n private readonly sideEffects?: boolean\n ) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(\n lhs: Code,\n private readonly op: Code,\n rhs: SafeExpr,\n sideEffects?: boolean\n ) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(\n private condition: Code | boolean,\n nodes?: ChildNode[]\n ) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(\n public name: Name,\n public args: Code,\n public async?: boolean\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record<string, SafeExpr | undefined>\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not<T extends Code | SafeExpr>(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n", "import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem<T>(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc<T extends SomeEvaluated> = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude<T, true> | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs<T extends SomeEvaluated> {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude<T, true>) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated<T extends SomeEvaluated>({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc<EvaluatedProperties>\n items: MergeEvaluatedFunc<EvaluatedItems>\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n", "import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n", "import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n", "import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n", "import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = (typeof _jsonTypes)[number]\n\nconst jsonTypes: Set<string> = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n", "import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n", "import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set<JSONType> = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n", "import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n", "import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n", "import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n", "import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set<string>\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set<string>()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n", "'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n", "import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponent} from \"fast-uri\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponent): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set<string> = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let innerBaseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") innerBaseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = innerBaseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n", "import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n", "import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial<ErrorObject>[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial<ErrorObject>[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n", "import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n", "import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport {URIComponent} from \"fast-uri\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set<string> // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set<string>(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URIComponent,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n", "{\n \"$id\": \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n \"description\": \"Meta-schema for $data reference (JSON AnySchema extension proposal)\",\n \"type\": \"object\",\n \"required\": [\"$data\"],\n \"properties\": {\n \"$data\": {\n \"type\": \"string\",\n \"anyOf\": [{\"format\": \"relative-json-pointer\"}, {\"format\": \"json-pointer\"}]\n }\n },\n \"additionalProperties\": false\n}\n", "'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$/u)\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n let acc = ''\n let code = 0\n let i = 0\n\n for (i = 0; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (code === 48) {\n continue\n }\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n break\n }\n\n for (i += 1; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n }\n return acc\n}\n\n/**\n * @typedef {Object} GetIPV6Result\n * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.\n * @property {string} address - The parsed IPv6 address.\n * @property {string} [zone] - The zone identifier, if present.\n */\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {Array<string>} buffer\n * @returns {boolean}\n */\nfunction consumeIsZone (buffer) {\n buffer.length = 0\n return true\n}\n\n/**\n * @param {Array<string>} buffer\n * @param {Array<string>} address\n * @param {GetIPV6Result} output\n * @returns {boolean}\n */\nfunction consumeHextets (buffer, address, output) {\n if (buffer.length) {\n const hex = stringArrayToHexStripped(buffer)\n if (hex !== '') {\n address.push(hex)\n } else {\n output.error = true\n return false\n }\n buffer.length = 0\n }\n return true\n}\n\n/**\n * @param {string} input\n * @returns {GetIPV6Result}\n */\nfunction getIPV6 (input) {\n let tokenCount = 0\n const output = { error: false, address: '', zone: '' }\n /** @type {Array<string>} */\n const address = []\n /** @type {Array<string>} */\n const buffer = []\n let endipv6Encountered = false\n let endIpv6 = false\n\n let consume = consumeHextets\n\n for (let i = 0; i < input.length; i++) {\n const cursor = input[i]\n if (cursor === '[' || cursor === ']') { continue }\n if (cursor === ':') {\n if (endipv6Encountered === true) {\n endIpv6 = true\n }\n if (!consume(buffer, address, output)) { break }\n if (++tokenCount > 7) {\n // not valid\n output.error = true\n break\n }\n if (i > 0 && input[i - 1] === ':') {\n endipv6Encountered = true\n }\n address.push(':')\n continue\n } else if (cursor === '%') {\n if (!consume(buffer, address, output)) { break }\n // switch to zone detection\n consume = consumeIsZone\n } else {\n buffer.push(cursor)\n continue\n }\n }\n if (buffer.length) {\n if (consume === consumeIsZone) {\n output.zone = buffer.join('')\n } else if (endIpv6) {\n address.push(buffer.join(''))\n } else {\n address.push(stringArrayToHexStripped(buffer))\n }\n }\n output.address = address.join('')\n return output\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n */\n\n/**\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n const ipv6 = getIPV6(host)\n\n if (!ipv6.error) {\n let newHost = ipv6.address\n let escapedHost = ipv6.address\n if (ipv6.zone) {\n newHost += '%' + ipv6.zone\n escapedHost += '%25' + ipv6.zone\n }\n return { host: newHost, isIPV6: true, escapedHost }\n } else {\n return { host, isIPV6: false }\n }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n let input = path\n const output = []\n let nextSlash = -1\n let len = 0\n\n // eslint-disable-next-line no-cond-assign\n while (len = input.length) {\n if (len === 1) {\n if (input === '.') {\n break\n } else if (input === '/') {\n output.push('/')\n break\n } else {\n output.push(input)\n break\n }\n } else if (len === 2) {\n if (input[0] === '.') {\n if (input[1] === '.') {\n break\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.' || input[1] === '/') {\n output.push('/')\n break\n }\n }\n } else if (len === 3) {\n if (input === '/..') {\n if (output.length !== 0) {\n output.pop()\n }\n output.push('/')\n break\n }\n }\n if (input[0] === '.') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(3)\n continue\n }\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(2)\n continue\n } else if (input[2] === '.') {\n if (input[3] === '/') {\n input = input.slice(3)\n if (output.length !== 0) {\n output.pop()\n }\n continue\n }\n }\n }\n }\n\n // Rule 2E: Move normal path segment to output\n if ((nextSlash = input.indexOf('/', 1)) === -1) {\n output.push(input)\n break\n } else {\n output.push(input.slice(0, nextSlash))\n input = input.slice(nextSlash)\n }\n }\n\n return output.join('')\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @param {boolean} esc\n * @returns {import('../types/index').URIComponent}\n */\nfunction normalizeComponentEncoding (component, esc) {\n const func = esc !== true ? escape : unescape\n if (component.scheme !== undefined) {\n component.scheme = func(component.scheme)\n }\n if (component.userinfo !== undefined) {\n component.userinfo = func(component.userinfo)\n }\n if (component.host !== undefined) {\n component.host = func(component.host)\n }\n if (component.path !== undefined) {\n component.path = func(component.path)\n }\n if (component.query !== undefined) {\n component.query = func(component.query)\n }\n if (component.fragment !== undefined) {\n component.fragment = func(component.fragment)\n }\n return component\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n const uriTokens = []\n\n if (component.userinfo !== undefined) {\n uriTokens.push(component.userinfo)\n uriTokens.push('@')\n }\n\n if (component.host !== undefined) {\n let host = unescape(component.host)\n if (!isIPv4(host)) {\n const ipV6res = normalizeIPv6(host)\n if (ipV6res.isIPV6 === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = component.host\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof component.port === 'number' || typeof component.port === 'string') {\n uriTokens.push(':')\n uriTokens.push(String(component.port))\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n nonSimpleDomain,\n recomposeAuthority,\n normalizeComponentEncoding,\n removeDotSegments,\n isIPv4,\n isUUID,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n", "'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n 'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n if (wsComponent.secure === true) {\n return true\n } else if (wsComponent.secure === false) {\n return false\n } else if (wsComponent.scheme) {\n return (\n wsComponent.scheme.length === 3 &&\n (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n )\n } else {\n return false\n }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n if (!component.host) {\n component.error = component.error || 'HTTP URIs must have a host.'\n }\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n const secure = String(component.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (component.port === (secure ? 443 : 80) || component.port === '') {\n component.port = undefined\n }\n\n // normalize the empty path\n if (!component.path) {\n component.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n wsComponent.secure = wsIsSecure(wsComponent)\n\n // construct resouce name\n wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n wsComponent.path = undefined\n wsComponent.query = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n wsComponent.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponent.secure === 'boolean') {\n wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n wsComponent.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponent.resourceName) {\n const [path, query] = wsComponent.resourceName.split('?')\n wsComponent.path = (path && path !== '/' ? path : undefined)\n wsComponent.query = query\n wsComponent.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponent.fragment = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n if (!urnComponent.path) {\n urnComponent.error = 'URN can not be parsed'\n return urnComponent\n }\n const matches = urnComponent.path.match(URN_REG)\n if (matches) {\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n urnComponent.nid = matches[1].toLowerCase()\n urnComponent.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n urnComponent.path = undefined\n\n if (schemeHandler) {\n urnComponent = schemeHandler.parse(urnComponent, options)\n }\n } else {\n urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n }\n\n return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n if (urnComponent.nid === undefined) {\n throw new Error('URN without nid cannot be serialized')\n }\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n const nid = urnComponent.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n\n if (schemeHandler) {\n urnComponent = schemeHandler.serialize(urnComponent, options)\n }\n\n const uriComponent = urnComponent\n const nss = urnComponent.nss\n uriComponent.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n const uuidComponent = urnComponent\n uuidComponent.uuid = uuidComponent.nss\n uuidComponent.nss = undefined\n\n if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n }\n\n return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n const urnComponent = uuidComponent\n // normalize UUID\n urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n return (\n scheme && (\n SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n ) ||\n undefined\n}\n\nmodule.exports = {\n wsIsSecure,\n SCHEMES,\n isValidSchemeName,\n getSchemeHandler,\n}\n", "'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = /** @type {T} */ (serialize(parse(uri, options), options))\n } else if (typeof uri === 'object') {\n uri = /** @type {T} */ (parse(serialize(uri, options), options))\n }\n return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n schemelessOptions.skipEscape = true\n return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n /** @type {import('./types/index').URIComponent} */\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base component\n relative = parse(serialize(relative, options), options) // normalize relative component\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path[0] === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n if (typeof uriA === 'string') {\n uriA = unescape(uriA)\n uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })\n } else if (typeof uriA === 'object') {\n uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })\n }\n\n if (typeof uriB === 'string') {\n uriB = unescape(uriB)\n uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })\n } else if (typeof uriB === 'object') {\n uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })\n }\n\n return uriA.toLowerCase() === uriB.toLowerCase()\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n const component = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n if (component.path !== undefined) {\n if (!options.skipEscape) {\n component.path = escape(component.path)\n\n if (component.scheme !== undefined) {\n component.path = component.path.split('%3A').join(':')\n }\n } else {\n component.path = unescape(component.path)\n }\n }\n\n if (options.reference !== 'suffix' && component.scheme) {\n uriTokens.push(component.scheme, ':')\n }\n\n const authority = recomposeAuthority(component)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (component.path && component.path[0] !== '/') {\n uriTokens.push('/')\n }\n }\n if (component.path !== undefined) {\n let s = component.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n if (\n authority === undefined &&\n s[0] === '/' &&\n s[1] === '/'\n ) {\n // don't allow the path to start with \"//\"\n s = '/%2F' + s.slice(2)\n }\n\n uriTokens.push(s)\n }\n\n if (component.query !== undefined) {\n uriTokens.push('?', component.query)\n }\n\n if (component.fragment !== undefined) {\n uriTokens.push('#', component.fragment)\n }\n return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n const options = Object.assign({}, opts)\n /** @type {import('./types/index').URIComponent} */\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n\n let isIP = false\n if (options.reference === 'suffix') {\n if (options.scheme) {\n uri = options.scheme + ':' + uri\n } else {\n uri = '//' + uri\n }\n }\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n if (parsed.host) {\n const ipv4result = isIPv4(parsed.host)\n if (ipv4result === false) {\n const ipv6result = normalizeIPv6(parsed.host)\n parsed.host = ipv6result.host.toLowerCase()\n isIP = ipv6result.isIPV6\n } else {\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n // check if scheme can't handle IRIs\n if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n // if host component is a domain name\n if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n // convert Unicode IDN -> ASCII IDN\n try {\n parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n }\n }\n // convert IRI -> URI\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (uri.indexOf('%') !== -1) {\n if (parsed.scheme !== undefined) {\n parsed.scheme = unescape(parsed.scheme)\n }\n if (parsed.host !== undefined) {\n parsed.host = unescape(parsed.host)\n }\n }\n if (parsed.path) {\n parsed.path = escape(unescape(parsed.path))\n }\n if (parsed.fragment) {\n parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return parsed\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponent,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n", "import * as uri from \"fast-uri\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n", "export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin<Opts> {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n specialNumbers?: \"fast\" | \"null\" // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise<AnySchemaObject>\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo<RemovedOptions> = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo<DeprecatedOptions> = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable<Options[K]>\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = {}\n readonly RULES: ValidationRules\n readonly _compilations: Set<SchemaEnv> = new Set()\n private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}\n private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>\n validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n validate<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n data: unknown\n ): data is JTDDataType<T>\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>\n validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>\n validate<T>(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data: unknown | T // to be validated\n ): boolean | Promise<T> {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema<T>(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile<T>(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compile<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n _meta?: boolean\n ): ValidateFunction<JTDDataType<T>>\n compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync<T = unknown>(\n schema: SchemaObject | JSONSchemaType<T>,\n _meta?: boolean\n ): Promise<ValidateFunction<T>>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>\n compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>>\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise<AnyValidateFunction> {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial<Logger> | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n", "import type {CodeKeywordDefinition} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID')\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n", "import type {Vocabulary} from \"../../types\"\nimport idKeyword from \"./id\"\nimport refKeyword from \"./ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n {keyword: \"$comment\"},\n \"definitions\",\n idKeyword,\n refKeyword,\n]\n\nexport default core\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators, Code} from \"../../compile/codegen\"\n\nconst ops = operators\n\ntype Kwd = \"maximum\" | \"minimum\" | \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n maximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n minimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n exclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n exclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitNumberError = ErrorObject<\n Kwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n", "// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {useFunc} from \"../../compile/util\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n if ($data) {\n const {regExp} = it.opts.code\n const regExpCode = regExp.code === \"new RegExp\" ? _`new RegExp` : useFunc(gen, regExp)\n const valid = gen.let(\"valid\")\n gen.try(\n () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),\n () => gen.assign(valid, false)\n )\n cxt.fail$data(_`!${valid}`)\n } else {\n const regExp = usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n", "import type {ErrorObject, Vocabulary} from \"../../types\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport multipleOf, {MultipleOfError} from \"./multipleOf\"\nimport limitLength from \"./limitLength\"\nimport pattern, {PatternError} from \"./pattern\"\nimport limitProperties from \"./limitProperties\"\nimport required, {RequiredError} from \"./required\"\nimport limitItems from \"./limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"./uniqueItems\"\nimport constKeyword, {ConstError} from \"./const\"\nimport enumKeyword, {EnumError} from \"./enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n", "import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n", "import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator<string>\n | FormatValidator<number>\n | AsyncFormatValidator<string>\n | AsyncFormatValidator<number>\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n", "import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n", "import type {Vocabulary} from \"../types\"\n\nexport const metadataVocabulary: Vocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n]\n\nexport const contentVocabulary: Vocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n]\n", "import type {Vocabulary} from \"../types\"\nimport coreVocabulary from \"./core\"\nimport validationVocabulary from \"./validation\"\nimport getApplicatorVocabulary from \"./applicator\"\nimport formatVocabulary from \"./format\"\nimport {metadataVocabulary, contentVocabulary} from \"./metadata\"\n\nconst draft7Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationVocabulary,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n contentVocabulary,\n]\n\nexport default draft7Vocabularies\n", "import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj<E extends DiscrError> = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n", "import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n const ref = sch.$ref\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n", "{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"http://json-schema.org/draft-07/schema#\",\n \"title\": \"Core schema meta-schema\",\n \"definitions\": {\n \"schemaArray\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\"$ref\": \"#\"}\n },\n \"nonNegativeInteger\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"nonNegativeIntegerDefault0\": {\n \"allOf\": [{\"$ref\": \"#/definitions/nonNegativeInteger\"}, {\"default\": 0}]\n },\n \"simpleTypes\": {\n \"enum\": [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n \"stringArray\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"uniqueItems\": true,\n \"default\": []\n }\n },\n \"type\": [\"object\", \"boolean\"],\n \"properties\": {\n \"$id\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$schema\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"$ref\": {\n \"type\": \"string\",\n \"format\": \"uri-reference\"\n },\n \"$comment\": {\n \"type\": \"string\"\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"default\": true,\n \"readOnly\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"examples\": {\n \"type\": \"array\",\n \"items\": true\n },\n \"multipleOf\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"maximum\": {\n \"type\": \"number\"\n },\n \"exclusiveMaximum\": {\n \"type\": \"number\"\n },\n \"minimum\": {\n \"type\": \"number\"\n },\n \"exclusiveMinimum\": {\n \"type\": \"number\"\n },\n \"maxLength\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minLength\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"pattern\": {\n \"type\": \"string\",\n \"format\": \"regex\"\n },\n \"additionalItems\": {\"$ref\": \"#\"},\n \"items\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/schemaArray\"}],\n \"default\": true\n },\n \"maxItems\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minItems\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"uniqueItems\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"contains\": {\"$ref\": \"#\"},\n \"maxProperties\": {\"$ref\": \"#/definitions/nonNegativeInteger\"},\n \"minProperties\": {\"$ref\": \"#/definitions/nonNegativeIntegerDefault0\"},\n \"required\": {\"$ref\": \"#/definitions/stringArray\"},\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"definitions\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"properties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"patternProperties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"propertyNames\": {\"format\": \"regex\"},\n \"default\": {}\n },\n \"dependencies\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/stringArray\"}]\n }\n },\n \"propertyNames\": {\"$ref\": \"#\"},\n \"const\": true,\n \"enum\": {\n \"type\": \"array\",\n \"items\": true,\n \"minItems\": 1,\n \"uniqueItems\": true\n },\n \"type\": {\n \"anyOf\": [\n {\"$ref\": \"#/definitions/simpleTypes\"},\n {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/definitions/simpleTypes\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n ]\n },\n \"format\": {\"type\": \"string\"},\n \"contentMediaType\": {\"type\": \"string\"},\n \"contentEncoding\": {\"type\": \"string\"},\n \"if\": {\"$ref\": \"#\"},\n \"then\": {\"$ref\": \"#\"},\n \"else\": {\"$ref\": \"#\"},\n \"allOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"anyOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"oneOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"not\": {\"$ref\": \"#\"}\n },\n \"default\": true\n}\n", "import type {AnySchemaObject} from \"./types\"\nimport AjvCore from \"./core\"\nimport draft7Vocabularies from \"./vocabularies/draft7\"\nimport discriminator from \"./vocabularies/discriminator\"\nimport * as draft7MetaSchema from \"./refs/json-schema-draft-07.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\"\n\nexport class Ajv extends AjvCore {\n _addVocabularies(): void {\n super._addVocabularies()\n draft7Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nmodule.exports.Ajv = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from \"./core\"\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\nexport {default as ValidationError} from \"./runtime/validation_error\"\nexport {default as MissingRefError} from \"./compile/ref_error\"\n", "#!/usr/bin/env node\n/**\n * claude-crap MCP server \u2014 entrypoint.\n *\n * Transport: stdio. The server is launched by `.mcp.json` with the\n * arguments `--transport stdio` and it never opens sockets or listens\n * on the network: all communication with Claude Code happens over\n * stdin/stdout as JSON-RPC messages.\n *\n * What this file wires together:\n *\n * Tools:\n * - compute_crap (CRAP index for one function)\n * - compute_tdr (Technical Debt Ratio for a scope)\n * - analyze_file_ast (tree-sitter AST metrics for a source file)\n * - ingest_sarif (normalize + dedupe an external SARIF report)\n * - ingest_scanner_output (route Semgrep/ESLint/Bandit/Stryker native output through an adapter and persist the normalized SARIF)\n * - require_test_harness (check that a production source file has a matching test)\n * - score_project (aggregate the workspace into Maintainability / Reliability / Security / Overall ratings)\n *\n * Resources:\n * - sonar://metrics/current (live CRAP / TDR / rating snapshot)\n * - sonar://reports/latest.sarif (last consolidated SARIF document)\n *\n * The handlers delegate to pure engines in `./metrics`, `./ast` and\n * `./sarif`, so the index file stays focused on routing and\n * cross-cutting concerns (configuration, logging, error boundaries).\n *\n * @module index\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport pino from \"pino\";\n\nimport { adaptScannerOutput, type KnownScanner } from \"./adapters/index.js\";\nimport { TreeSitterEngine } from \"./ast/tree-sitter-engine.js\";\nimport type { SupportedLanguage } from \"./ast/language-config.js\";\nimport { loadConfig, type CrapConfig } from \"./config.js\";\nimport { startDashboard, type DashboardHandle } from \"./dashboard/server.js\";\nimport { computeCrap } from \"./metrics/crap.js\";\nimport {\n computeProjectScore,\n renderProjectScoreMarkdown,\n type ProjectScore,\n} from \"./metrics/score.js\";\nimport { computeTdr, classifyTdr } from \"./metrics/tdr.js\";\nimport { estimateWorkspaceLoc } from \"./metrics/workspace-walker.js\";\nimport { SarifStore, type PersistedSarif } from \"./sarif/sarif-store.js\";\nimport { validateSarifDocument } from \"./sarif/sarif-validator.js\";\nimport { loadCrapConfig, CrapConfigError } from \"./crap-config.js\";\nimport { findTestFile } from \"./tools/test-harness.js\";\nimport { resolveWithinWorkspace } from \"./workspace-guard.js\";\nimport { autoScan } from \"./scanner/auto-scan.js\";\nimport { bootstrapScanner } from \"./scanner/bootstrap.js\";\nimport { discoverProjectMap, persistProjectMap, type ProjectMap } from \"./monorepo/project-map.js\";\nimport {\n autoScanSchema,\n bootstrapScannerSchema,\n computeCrapSchema,\n computeTdrSchema,\n analyzeFileAstSchema,\n ingestSarifSchema,\n ingestScannerOutputSchema,\n listProjectsSchema,\n requireTestHarnessSchema,\n scoreProjectSchema,\n} from \"./schemas/tool-schemas.js\";\n\n// IMPORTANT: the MCP stdio transport uses stdout for JSON-RPC framing.\n// Anything the server logs MUST go to stderr (fd 2) to avoid corrupting\n// the wire format. We configure pino explicitly to write to fd 2.\nconst logger = pino(\n { level: process.env.CLAUDE_CRAP_LOG_LEVEL ?? \"info\" },\n pino.destination(2),\n);\n\n/**\n * Server bootstrap. Loads configuration, instantiates the long-lived\n * engines (tree-sitter, SARIF store), registers tool and resource\n * handlers, and connects the stdio transport. Exits with a non-zero code\n * on fatal startup errors so that Claude Code surfaces the failure to\n * the user instead of silently running without the plugin.\n */\nasync function main(): Promise<void> {\n const config = loadConfig();\n logger.info(\n { config: { ...config, pluginRoot: \"<redacted>\" } },\n \"claude-crap MCP server starting\",\n );\n\n // Load user-defined exclusions and projectDirs from .claude-crap.json (non-fatal).\n let userExclusions: ReadonlyArray<string> = [];\n let userProjectDirs: ReadonlyArray<string> = [];\n try {\n const crapConfig = loadCrapConfig({ workspaceRoot: config.pluginRoot });\n userExclusions = crapConfig.exclude;\n userProjectDirs = crapConfig.projectDirs;\n if (userExclusions.length > 0) {\n logger.info({ exclude: userExclusions }, \"user exclusions loaded from .claude-crap.json\");\n }\n if (userProjectDirs.length > 0) {\n logger.info({ projectDirs: userProjectDirs }, \"user projectDirs loaded from .claude-crap.json\");\n }\n } catch {\n // Non-fatal \u2014 use empty exclusions.\n }\n\n // Long-lived engines. Created once at boot and reused for every call.\n const astEngine = new TreeSitterEngine();\n const sarifStore = new SarifStore({\n workspaceRoot: config.pluginRoot,\n outputDir: config.sarifOutputDir,\n });\n await sarifStore.loadLatest();\n logger.info(\n { findings: sarifStore.size(), path: sarifStore.consolidatedReportPath },\n \"SARIF store ready\",\n );\n\n // Discover monorepo project map (non-fatal).\n let projectMap: ProjectMap | null = null;\n try {\n projectMap = await discoverProjectMap(config.pluginRoot, { projectDirs: userProjectDirs });\n if (projectMap.isMonorepo) {\n logger.info(\n { projects: projectMap.projects.map((p) => `${p.name}(${p.type})`), count: projectMap.projects.length },\n \"monorepo project map discovered\",\n );\n await persistProjectMap(projectMap, config.pluginRoot);\n\n // If any JS/TS sub-projects need ESLint and it's not available,\n // run bootstrap at the monorepo root to auto-install it. In\n // monorepos, ESLint is hoisted to the root node_modules.\n const needsEslint = projectMap.projects.some(\n (p) => (p.type === \"typescript\" || p.type === \"javascript\") && !p.scannerAvailable,\n );\n if (needsEslint) {\n logger.info(\"monorepo: JS/TS projects detected but ESLint not installed \u2014 bootstrapping\");\n try {\n await bootstrapScanner(config.pluginRoot, sarifStore, logger);\n // Re-discover after install so scannerAvailable reflects reality\n projectMap = await discoverProjectMap(config.pluginRoot, { projectDirs: userProjectDirs });\n await persistProjectMap(projectMap, config.pluginRoot);\n } catch (err) {\n logger.warn({ err: (err as Error).message }, \"monorepo ESLint bootstrap failed\");\n }\n }\n }\n } catch (err) {\n logger.warn({ err: (err as Error).message }, \"project map discovery failed\");\n }\n\n // Try to start the local Vue.js dashboard. Failures here are\n // intentionally non-fatal \u2014 the MCP server still works without it.\n let dashboard: DashboardHandle | null = null;\n try {\n dashboard = await startDashboard({\n config,\n sarifStore,\n workspaceStatsProvider: () => estimateWorkspaceLoc(config.pluginRoot, { exclude: userExclusions }),\n logger,\n astEngine,\n exclude: userExclusions,\n });\n } catch (err) {\n logger.warn(\n { err: (err as Error).message, port: config.dashboardPort },\n \"claude-crap dashboard failed to start \u2014 continuing without it\",\n );\n }\n // Make sure the dashboard is closed when the process exits so the TCP\n // port is freed promptly. SIGINT/SIGTERM may arrive from Claude Code's\n // MCP supervisor, from a developer hitting Ctrl-C, or from the test\n // harness in our integration suite.\n //\n // IMPORTANT: installing a custom signal handler overrides Node's\n // default (which exits the process), so we have to call\n // `process.exit()` ourselves once cleanup finishes. Without this the\n // MCP stdio transport would keep reading stdin forever and the\n // Fastify dashboard would keep its listener open, leaving the whole\n // process alive even after SIGTERM.\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.once(signal, () => {\n void (async () => {\n try {\n await dashboard?.close();\n } catch {\n /* best effort \u2014 dashboard may already be down */\n }\n // 130 is the conventional exit code for SIGINT, 143 for SIGTERM.\n const exitCode = signal === \"SIGINT\" ? 130 : 143;\n process.exit(exitCode);\n })();\n });\n }\n\n const server = new Server(\n {\n name: \"claude-crap\",\n version: \"0.1.0\",\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n },\n );\n\n // ------------------------------------------------------------------\n // Tools \u2014 declaration (list)\n // ------------------------------------------------------------------\n // The tool list is what the LLM sees when it introspects the server.\n // Keep the descriptions short, imperative and fact-based.\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"compute_crap\",\n description:\n \"Compute the CRAP (Change Risk Anti-Patterns) index for a function and block when the score exceeds the configured threshold.\",\n inputSchema: computeCrapSchema,\n },\n {\n name: \"compute_tdr\",\n description:\n \"Compute the Technical Debt Ratio for a scope and return the maintainability rating (A..E).\",\n inputSchema: computeTdrSchema,\n },\n {\n name: \"analyze_file_ast\",\n description:\n \"Analyze a source file with tree-sitter and return deterministic metrics (LOC, cyclomatic complexity, function topology).\",\n inputSchema: analyzeFileAstSchema,\n },\n {\n name: \"ingest_sarif\",\n description:\n \"Ingest a raw SARIF 2.1.0 report from an external scanner (Semgrep, ESLint, Bandit, ...), deduplicate it, and persist the consolidated view.\",\n inputSchema: ingestSarifSchema,\n },\n {\n name: \"ingest_scanner_output\",\n description:\n \"Ingest a scanner's native output (Semgrep, ESLint, Bandit, Stryker), route it through the matching adapter, enrich each finding with an effort estimate, and persist the normalized SARIF report.\",\n inputSchema: ingestScannerOutputSchema,\n },\n {\n name: \"require_test_harness\",\n description:\n \"Check whether a production source file has an accompanying test file. Required by the Golden Rule before any functional code is written.\",\n inputSchema: requireTestHarnessSchema,\n },\n {\n name: \"score_project\",\n description:\n \"Aggregate the project score across Maintainability, Reliability, Security and Overall, returning a chat-friendly Markdown summary, the structured JSON, the local dashboard URL, and the consolidated SARIF report path.\",\n inputSchema: scoreProjectSchema,\n },\n {\n name: \"auto_scan\",\n description:\n \"Auto-detect available scanners (ESLint, Semgrep, Bandit, Stryker) in the workspace, run them, and ingest findings into the SARIF store.\",\n inputSchema: autoScanSchema,\n },\n {\n name: \"bootstrap_scanner\",\n description:\n \"Detect project type, install the right scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create minimal config, and run auto_scan to verify.\",\n inputSchema: bootstrapScannerSchema,\n },\n {\n name: \"list_projects\",\n description: \"List all discovered sub-projects in the workspace. In a monorepo, returns each sub-project with its type, path, and recommended scanner.\",\n inputSchema: listProjectsSchema,\n },\n ],\n }));\n\n // ------------------------------------------------------------------\n // Tools \u2014 call dispatch\n // ------------------------------------------------------------------\n // The MCP SDK has already validated `args` against the tool's JSON\n // Schema by the time this handler runs, so we cast to the expected\n // shape without re-validating. Each branch delegates to a pure engine.\n // Tool dispatch is split across two functions to keep cyclomatic\n // complexity within the configured threshold (15) as the tool count\n // grows. Each function handles a subset of tools.\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n logger.info({ tool: name }, \"Tool call received\");\n return handleToolCall(name, args);\n });\n\n // \u2500\u2500 Per-tool handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Extracted from the switch to keep handleToolCall under the\n // cyclomatic complexity threshold.\n\n type ToolResult = { content: Array<{ type: string; text: string }>; isError?: boolean };\n\n function handleComputeCrap(args: Record<string, unknown>): ToolResult {\n const typed = args as {\n cyclomaticComplexity: number;\n coveragePercent: number;\n functionName: string;\n filePath: string;\n };\n const result = computeCrap(\n { cyclomaticComplexity: typed.cyclomaticComplexity, coveragePercent: typed.coveragePercent },\n config.crapThreshold,\n );\n return {\n content: [{ type: \"text\", text: JSON.stringify(\n { tool: \"compute_crap\", function: typed.functionName, file: typed.filePath, ...result }, null, 2,\n ) }],\n isError: result.exceedsThreshold,\n };\n }\n\n function handleComputeTdr(args: Record<string, unknown>): ToolResult {\n const typed = args as {\n remediationMinutes: number;\n totalLinesOfCode: number;\n scope: \"project\" | \"module\" | \"file\";\n };\n const result = computeTdr({\n remediationMinutes: typed.remediationMinutes,\n totalLinesOfCode: typed.totalLinesOfCode,\n minutesPerLoc: config.minutesPerLoc,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify({ tool: \"compute_tdr\", scope: typed.scope, ...result }, null, 2) }],\n };\n }\n\n async function handleAnalyzeFileAst(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { filePath: string; language: SupportedLanguage };\n const absolutePath = resolveWithinWorkspace(config.pluginRoot, typed.filePath);\n try {\n const metrics = await astEngine.analyzeFile({ filePath: absolutePath, language: typed.language });\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"analyze_file_ast\", ...metrics }, null, 2) }] };\n } catch (err) {\n logger.error({ err, filePath: absolutePath, language: typed.language }, \"analyze_file_ast failed\");\n return {\n content: [{ type: \"text\", text: JSON.stringify(\n { tool: \"analyze_file_ast\", status: \"error\", message: (err as Error).message, filePath: typed.filePath, language: typed.language }, null, 2,\n ) }],\n isError: true,\n };\n }\n }\n\n /** Dispatch a tool call to the correct handler. */\n async function handleToolCall(\n name: string,\n args: Record<string, unknown> | undefined,\n ): Promise<ToolResult> {\n switch (name) {\n case \"compute_crap\":\n return handleComputeCrap(args ?? {});\n case \"compute_tdr\":\n return handleComputeTdr(args ?? {});\n case \"analyze_file_ast\":\n return handleAnalyzeFileAst(args ?? {});\n\n case \"score_project\":\n return handleScoreProject(args ?? {});\n case \"require_test_harness\":\n return handleRequireTestHarness(args ?? {});\n case \"ingest_scanner_output\":\n return handleIngestScannerOutput(args ?? {});\n case \"ingest_sarif\":\n return handleIngestSarif(args ?? {});\n case \"bootstrap_scanner\":\n return handleBootstrapScanner();\n case \"auto_scan\":\n return handleAutoScan();\n case \"list_projects\":\n return handleListProjects();\n default:\n throw new Error(`[claude-crap] Unknown tool: ${name}`);\n }\n }\n\n async function handleScoreProject(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { format?: \"markdown\" | \"json\" | \"both\"; scope?: string };\n const format = typed.format ?? \"both\";\n let scoreRoot = config.pluginRoot;\n if (typed.scope && projectMap) {\n const project = projectMap.projects.find((p) => p.name === typed.scope);\n if (project) {\n const { join } = await import(\"node:path\");\n scoreRoot = join(config.pluginRoot, project.path);\n }\n }\n try {\n const workspace = await estimateWorkspaceLoc(scoreRoot, { exclude: userExclusions });\n const score: ProjectScore = computeProjectScore({\n workspaceRoot: scoreRoot, minutesPerLoc: config.minutesPerLoc, tdrMaxRating: config.tdrMaxRating,\n workspace: { physicalLoc: workspace.physicalLoc, fileCount: workspace.fileCount },\n sarifStore, dashboardUrl: dashboard?.url ?? null, sarifReportPath: sarifStore.consolidatedReportPath,\n });\n const blocks: Array<{ type: \"text\"; text: string }> = [];\n if (format === \"markdown\" || format === \"both\") blocks.push({ type: \"text\", text: renderProjectScoreMarkdown(score) });\n if (format === \"json\" || format === \"both\") blocks.push({ type: \"text\", text: JSON.stringify(score, null, 2) });\n const strictness = safeLoadStrictness(config.pluginRoot, logger);\n return { content: blocks, isError: strictness === \"strict\" && !score.overall.passes };\n } catch (err) {\n logger.error({ err }, \"score_project failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"score_project\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleRequireTestHarness(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { filePath: string };\n const absolutePath = resolveWithinWorkspace(config.pluginRoot, typed.filePath);\n try {\n const resolution = await findTestFile(config.pluginRoot, absolutePath);\n const hasTest = resolution.testFile !== null;\n return {\n content: [{ type: \"text\", text: JSON.stringify({\n tool: \"require_test_harness\", filePath: typed.filePath, hasTest, isTestFile: resolution.isTestFile,\n testFile: resolution.testFile, candidates: resolution.candidates,\n ...(hasTest ? {} : { corrective: \"No test file found. Per the CLAUDE.md Golden Rule, create a characterization test at one of the candidate paths before writing any functional code for this file.\" }),\n }, null, 2) }],\n isError: !hasTest,\n };\n } catch (err) {\n logger.error({ err, filePath: absolutePath }, \"require_test_harness failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"require_test_harness\", status: \"error\", message: (err as Error).message, filePath: typed.filePath }, null, 2) }], isError: true };\n }\n }\n\n async function handleIngestScannerOutput(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { scanner: KnownScanner; rawOutput: unknown };\n try {\n const adapted = adaptScannerOutput(typed.scanner, typed.rawOutput);\n validateSarifDocument(adapted.document);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n await sarifStore.persist();\n return { content: [{ type: \"text\", text: JSON.stringify({\n tool: \"ingest_scanner_output\", status: \"accepted\", scanner: typed.scanner,\n findingsParsed: adapted.findingCount, totalEffortMinutes: adapted.totalEffortMinutes,\n accepted: stats.accepted, duplicates: stats.duplicates, total: stats.total,\n storeSize: sarifStore.size(), reportPath: sarifStore.consolidatedReportPath,\n }, null, 2) }] };\n } catch (err) {\n logger.error({ err, scanner: typed.scanner }, \"ingest_scanner_output failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"ingest_scanner_output\", status: \"error\", scanner: typed.scanner, message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleIngestSarif(args: Record<string, unknown>): Promise<ToolResult> {\n const typed = args as { sarifDocument: PersistedSarif; sourceTool: string };\n try {\n validateSarifDocument(typed.sarifDocument);\n const stats = sarifStore.ingestRun(typed.sarifDocument, typed.sourceTool);\n await sarifStore.persist();\n return { content: [{ type: \"text\", text: JSON.stringify({\n tool: \"ingest_sarif\", status: \"accepted\", sourceTool: typed.sourceTool,\n accepted: stats.accepted, duplicates: stats.duplicates, total: stats.total,\n storeSize: sarifStore.size(), reportPath: sarifStore.consolidatedReportPath,\n }, null, 2) }] };\n } catch (err) {\n logger.error({ err, sourceTool: typed.sourceTool }, \"ingest_sarif failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"ingest_sarif\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleBootstrapScanner(): Promise<ToolResult> {\n try {\n const result = await bootstrapScanner(config.pluginRoot, sarifStore, logger);\n return { content: [{ type: \"text\", text: renderBootstrapMarkdown(result) }, { type: \"text\", text: JSON.stringify(result, null, 2) }], isError: !result.success };\n } catch (err) {\n logger.error({ err }, \"bootstrap_scanner failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"bootstrap_scanner\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n async function handleAutoScan(): Promise<ToolResult> {\n try {\n const result = await autoScan(config.pluginRoot, sarifStore, logger, { engine: astEngine, cyclomaticMax: config.cyclomaticMax, exclude: userExclusions });\n return { content: [{ type: \"text\", text: renderAutoScanMarkdown(result) }, { type: \"text\", text: JSON.stringify(result, null, 2) }] };\n } catch (err) {\n logger.error({ err }, \"auto_scan failed\");\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"auto_scan\", status: \"error\", message: (err as Error).message }, null, 2) }], isError: true };\n }\n }\n\n function handleListProjects(): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify({ tool: \"list_projects\", isMonorepo: projectMap?.isMonorepo ?? false, projects: projectMap?.projects ?? [] }, null, 2) }] };\n }\n\n // ------------------------------------------------------------------\n // Resources \u2014 topology and reports\n // ------------------------------------------------------------------\n server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n resources: [\n {\n uri: \"sonar://metrics/current\",\n name: \"Current project metrics\",\n mimeType: \"application/json\",\n description: \"Snapshot of CRAP, TDR, and Reliability / Security ratings.\",\n },\n {\n uri: \"sonar://reports/latest.sarif\",\n name: \"Latest consolidated SARIF 2.1.0 report\",\n mimeType: \"application/sarif+json\",\n description: \"Unified SARIF document produced by the most recent Stop quality-gate run.\",\n },\n ],\n }));\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n if (uri === \"sonar://reports/latest.sarif\") {\n const doc = sarifStore.toSarifDocument();\n return {\n contents: [\n {\n uri,\n mimeType: \"application/sarif+json\",\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n if (uri === \"sonar://metrics/current\") {\n const snapshot = await buildMetricsSnapshot(config, sarifStore);\n return {\n contents: [\n {\n uri,\n mimeType: \"application/json\",\n text: JSON.stringify(snapshot, null, 2),\n },\n ],\n };\n }\n throw new Error(`[claude-crap] Unknown resource URI: ${uri}`);\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n logger.info(\"claude-crap MCP server ready (stdio)\");\n\n // Fire-and-forget: auto-scan runs in background, doesn't block tool calls.\n // If the agent calls score_project before scanning finishes, it gets\n // whatever is in the SARIF store so far. The next call after completion\n // reflects all findings.\n autoScan(config.pluginRoot, sarifStore, logger, {\n engine: astEngine,\n cyclomaticMax: config.cyclomaticMax,\n exclude: userExclusions,\n })\n .then((result) => {\n const scanners = result.results\n .filter((r) => r.success)\n .map((r) => r.scanner);\n logger.info(\n {\n scannersRun: scanners,\n totalFindings: result.totalFindings,\n durationMs: result.totalDurationMs,\n },\n \"auto-scan completed\",\n );\n })\n .catch((err) => {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan failed \u2014 continuing without it\",\n );\n });\n}\n\n/**\n * Render a human-readable Markdown summary of a bootstrap result.\n */\nfunction renderBootstrapMarkdown(result: import(\"./scanner/bootstrap.js\").BootstrapResult): string {\n const lines: string[] = [\"## claude-crap :: bootstrap scanner\\n\"];\n\n lines.push(`**Project type:** ${result.projectType}`);\n\n if (result.alreadyConfigured) {\n lines.push(`**Status:** Scanner(s) already configured: ${result.existingScanners.join(\", \")}`);\n lines.push(\"\\nNo installation needed. Run `auto_scan` to ingest findings.\");\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n\n if (result.steps.length > 0) {\n lines.push(\"### Steps\\n\");\n lines.push(\"| Action | Status | Detail |\");\n lines.push(\"| ------ | :----: | ------ |\");\n for (const s of result.steps) {\n const status = s.success ? \"ok\" : \"failed\";\n lines.push(`| ${s.action} | ${status} | ${s.detail} |`);\n }\n lines.push(\"\");\n }\n\n if (result.autoScanResult) {\n const r = result.autoScanResult;\n const scanners = r.results.filter((s) => s.success).map((s) => s.scanner);\n lines.push(\n `**Auto-scan:** ${r.totalFindings} finding(s) ingested from ${scanners.join(\", \") || \"no scanners\"} in ${(r.totalDurationMs / 1000).toFixed(1)}s`,\n );\n lines.push(\"\");\n }\n\n lines.push(`**Summary:** ${result.summary}`);\n return lines.join(\"\\n\");\n}\n\n/**\n * Render a human-readable Markdown summary of an auto-scan result.\n */\nfunction renderAutoScanMarkdown(result: import(\"./scanner/auto-scan.js\").AutoScanResult): string {\n const lines: string[] = [\"## claude-crap :: auto-scan results\\n\"];\n\n // Detection summary\n lines.push(\"### Detected scanners\\n\");\n lines.push(\"| Scanner | Available | Reason |\");\n lines.push(\"| ------- | :-------: | ------ |\");\n for (const d of result.detected) {\n lines.push(`| ${d.scanner} | ${d.available ? \"yes\" : \"no\"} | ${d.reason} |`);\n }\n lines.push(\"\");\n\n // Execution results\n if (result.results.length > 0) {\n lines.push(\"### Execution results\\n\");\n lines.push(\"| Scanner | Status | Findings | Duration |\");\n lines.push(\"| ------- | :----: | :------: | -------: |\");\n for (const r of result.results) {\n const status = r.success ? \"ok\" : \"failed\";\n const duration = `${(r.durationMs / 1000).toFixed(1)}s`;\n lines.push(`| ${r.scanner} | ${status} | ${r.findingsIngested} | ${duration} |`);\n }\n lines.push(\"\");\n }\n\n // Complexity scan\n if (result.complexityScan) {\n const cs = result.complexityScan;\n lines.push(\"### Cyclomatic complexity scan\\n\");\n lines.push(`- Files scanned: **${cs.filesScanned}**`);\n lines.push(`- Functions analyzed: **${cs.functionsAnalyzed}**`);\n lines.push(`- Violations: **${cs.violations}**`);\n lines.push(`- Duration: ${(cs.durationMs / 1000).toFixed(1)}s`);\n lines.push(\"\");\n }\n\n // Summary\n lines.push(\n `**Total findings ingested:** ${result.totalFindings} in ${(result.totalDurationMs / 1000).toFixed(1)}s`,\n );\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Load the workspace strictness without letting a busted config\n * file take down the `score_project` tool. On any loader error we\n * log to stderr via pino and fall back to `\"strict\"` so the tool\n * stays useful. This is the MCP-server-side counterpart to the\n * `resolveStrictness` helper in `hooks/stop-quality-gate.mjs`.\n *\n * @param workspaceRoot Absolute path the loader should probe for\n * `.claude-crap.json`.\n * @param logger Pino logger used to surface recoverable\n * config errors.\n * @returns The resolved strictness, or `\"strict\"` on\n * error.\n */\nfunction safeLoadStrictness(\n workspaceRoot: string,\n logger: import(\"pino\").Logger,\n): \"strict\" | \"warn\" | \"advisory\" {\n try {\n return loadCrapConfig({ workspaceRoot }).strictness;\n } catch (err) {\n if (err instanceof CrapConfigError) {\n logger.warn(\n { err: err.message },\n \"score_project: invalid sonar config, falling back to strict\",\n );\n return \"strict\";\n }\n throw err;\n }\n}\n\n/**\n * Build a lightweight metrics snapshot that the LLM can read through\n * the `sonar://metrics/current` resource. This is intentionally thin\n * and side-effect free: it derives everything from the in-memory\n * SARIF store without walking the workspace. Callers that need a\n * full scoring payload (with a real LOC walk and the A..E grades per\n * dimension) should invoke the `score_project` tool, which uses the\n * bounded workspace walker and the `metrics/score.ts` engine.\n *\n * @param config Fully resolved server configuration.\n * @param sarifStore Live SARIF store used to read the latest findings.\n */\nasync function buildMetricsSnapshot(\n config: CrapConfig,\n sarifStore: SarifStore,\n): Promise<Record<string, unknown>> {\n const findings = sarifStore.list();\n const totalRemediationMinutes = findings.reduce((sum, f) => {\n const effort = f.properties?.[\"effortMinutes\"];\n return typeof effort === \"number\" ? sum + effort : sum;\n }, 0);\n\n // Cheap LOC approximation derived from the SARIF report: assume\n // ~100 physical lines per file we have at least one finding in.\n // This keeps the resource read lock-free and synchronous-feeling;\n // the `score_project` tool is the authoritative path when a real\n // workspace walk is required.\n const uniqueFiles = new Set(findings.map((f) => f.location.uri));\n const approxLoc = Math.max(uniqueFiles.size * 100, 1);\n\n const tdrPercent =\n totalRemediationMinutes / (config.minutesPerLoc * approxLoc) * 100;\n const rating = classifyTdr(Number.isFinite(tdrPercent) ? tdrPercent : 0);\n\n return {\n generatedAt: new Date().toISOString(),\n config: {\n crapThreshold: config.crapThreshold,\n tdrMaxRating: config.tdrMaxRating,\n minutesPerLoc: config.minutesPerLoc,\n },\n sarif: {\n reportPath: sarifStore.consolidatedReportPath,\n findings: findings.length,\n files: uniqueFiles.size,\n tools: Array.from(new Set(findings.map((f) => f.sourceTool))),\n },\n tdrApprox: {\n percent: Number(tdrPercent.toFixed(4)),\n rating,\n remediationMinutes: totalRemediationMinutes,\n approxLinesOfCode: approxLoc,\n },\n };\n}\n\n// Top-level await would be cleaner, but we keep main() + .catch() so\n// any error during async bootstrap (engine init, store load) surfaces as\n// a non-zero exit code visible to Claude Code's MCP diagnostics.\nmain().catch((err) => {\n // Fatal errors go to stderr to avoid corrupting the JSON-RPC channel\n // on stdout. We use `process.stderr.write` rather than `console.error`\n // so that no lint suppression is needed and so that no buffering layer\n // can swallow the message. A non-zero exit code causes Claude Code to\n // surface the failure in its MCP-server diagnostics.\n process.stderr.write(`[claude-crap] fatal error during startup: ${String(err)}\\n`);\n if (err instanceof Error && err.stack) {\n process.stderr.write(err.stack + \"\\n\");\n }\n process.exit(1);\n});\n", "/**\n * Shared types and helpers for per-scanner SARIF adapters.\n *\n * Every adapter in this directory converts a scanner's native output\n * into a `PersistedSarif` 2.1.0 document that the `SarifStore` can\n * ingest directly. The adapters also enrich the finding `properties`\n * bag with a stable `effortMinutes` field so the Stop quality gate and\n * the Technical Debt Ratio computation can treat every source tool\n * uniformly.\n *\n * Rule-level effort estimates live in `DEFAULT_EFFORT_BY_SEVERITY`.\n * Individual adapters may override the default per rule id when the\n * scanner attaches a more specific hint.\n *\n * @module adapters/common\n */\n\nimport type { PersistedSarif } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n/**\n * The canonical list of scanners claude-crap understands. The\n * `ingest_scanner_output` MCP tool uses this as its `enum` constraint,\n * so keeping it narrow prevents drift.\n */\nexport const KNOWN_SCANNERS = [\"semgrep\", \"eslint\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"] as const;\n\n/**\n * Union of supported scanner identifiers.\n */\nexport type KnownScanner = (typeof KNOWN_SCANNERS)[number];\n\n/**\n * Default remediation effort in minutes per SARIF severity level. These\n * numbers are deliberately conservative \u2014 real projects should override\n * them per rule via adapter-specific rule maps or via SARIF properties.\n *\n * The mapping follows the common-sense rule that every bug takes at\n * least a test plus a patch, so even a note-level finding costs time.\n */\nexport const DEFAULT_EFFORT_BY_SEVERITY: Readonly<Record<SarifLevel, number>> = Object.freeze({\n error: 60,\n warning: 30,\n note: 10,\n none: 5,\n});\n\n/**\n * Envelope common to every adapter output. Adapters return a\n * `PersistedSarif` document and a small stats block describing what\n * they saw, so the MCP tool handler can echo those stats back to the\n * LLM even when the SarifStore rejects duplicates.\n */\nexport interface AdapterResult {\n /** Normalized SARIF 2.1.0 document ready for `SarifStore.ingestRun`. */\n readonly document: PersistedSarif;\n /** Scanner identifier, propagated into every finding's `properties.sourceTool`. */\n readonly sourceTool: KnownScanner;\n /** Raw number of findings the adapter read from the scanner's native output. */\n readonly findingCount: number;\n /** Total estimated remediation effort across all findings, in minutes. */\n readonly totalEffortMinutes: number;\n}\n\n/**\n * Build a `PersistedSarif` document from a flat list of already-mapped\n * result entries. Every adapter produces its results with the same\n * shape and then calls this helper to wrap them in a valid 2.1.0 envelope.\n *\n * @param sourceTool Stable scanner identifier (e.g. `\"semgrep\"`).\n * @param version Adapter version string stored in `tool.driver.version`.\n * @param results Pre-built SARIF `result` entries.\n */\nexport function wrapResultsInSarif(\n sourceTool: KnownScanner,\n version: string,\n results: ReadonlyArray<object>,\n): PersistedSarif {\n return {\n $schema: \"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\",\n version: \"2.1.0\",\n runs: [\n {\n tool: {\n driver: {\n name: sourceTool,\n version,\n },\n },\n results: results as ReadonlyArray<SarifResultShape>,\n },\n ],\n } as PersistedSarif;\n}\n\n/**\n * Narrow structural contract of a SARIF `result` object. We type it\n * loosely so adapters can emit the minimum required fields without\n * importing the full SARIF spec types from `sarif-store.ts`.\n */\ninterface SarifResultShape {\n readonly ruleId: string;\n readonly level?: SarifLevel;\n readonly message: { readonly text: string };\n readonly locations?: ReadonlyArray<{\n readonly physicalLocation?: {\n readonly artifactLocation?: { readonly uri?: string };\n readonly region?: {\n readonly startLine?: number;\n readonly startColumn?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n };\n };\n }>;\n readonly properties?: Record<string, unknown>;\n}\n\n/**\n * Estimate remediation effort for a single finding given its severity\n * and an optional rule-specific override. Returns `minutes` clamped to\n * a non-negative integer.\n *\n * @param level SARIF severity level (`\"error\"`, `\"warning\"`, ...).\n * @param override Optional rule-specific effort in minutes.\n */\nexport function estimateEffortMinutes(level: SarifLevel | undefined, override?: number): number {\n if (typeof override === \"number\" && Number.isFinite(override) && override >= 0) {\n return Math.round(override);\n }\n const base = DEFAULT_EFFORT_BY_SEVERITY[level ?? \"warning\"];\n return Math.max(0, Math.round(base ?? 30));\n}\n", "/**\n * Semgrep adapter.\n *\n * Semgrep already emits SARIF 2.1.0 natively when invoked with\n * `--sarif`, so this adapter's job is not translation but\n * **enrichment**: we walk every `result` entry and stamp a\n * `properties.effortMinutes` value so the Stop quality gate can\n * compute a Technical Debt Ratio, plus we normalize the\n * `properties.sourceTool` field so downstream consumers always know\n * the finding came from Semgrep.\n *\n * If the caller passes a string, we parse it as JSON. If they pass an\n * object that already matches the SARIF 2.1.0 envelope, we use it\n * directly. Anything else throws a descriptive error that the MCP\n * tool handler surfaces back to the LLM.\n *\n * @module adapters/semgrep\n */\n\nimport type { PersistedSarif } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst SEMGREP: KnownScanner = \"semgrep\";\n\n/**\n * Rule-id effort overrides. Semgrep emits lots of stylistic rules\n * that take less than a minute to fix and a handful of deep security\n * rules that deserve more budget than the default warning tier. The\n * list below is intentionally short \u2014 teams should extend it.\n */\nconst SEMGREP_EFFORT_OVERRIDES: ReadonlyMap<RegExp, number> = new Map([\n [/security\\./i, 90],\n [/sqli|xss|ssrf|rce|deserial|crypto/i, 120],\n [/style\\./i, 5],\n [/formatting\\./i, 3],\n]);\n\n/**\n * Accept a Semgrep SARIF document (as a string or object) and return\n * an enriched `PersistedSarif` with effort estimates and a normalized\n * `sourceTool` field.\n *\n * @param input Raw SARIF document from Semgrep (`JSON.stringify`ed or parsed).\n * @returns The enriched document plus per-run stats.\n * @throws When the input is not a SARIF 2.1.0 document.\n */\nexport function adaptSemgrep(input: unknown): AdapterResult {\n const doc = coerceToSarif(input);\n\n let findingCount = 0;\n let totalEffortMinutes = 0;\n\n // We deep-clone the document so callers don't observe a mutation on\n // the value they passed us. JSON round-trip is cheap here; a\n // typical Semgrep SARIF report is well under 1 MB.\n //\n // We operate on the cloned value through a loose `Record`-based view\n // to keep the adapter agnostic to the full SARIF schema \u2014 the\n // canonical types live in `sarif-store.ts` and we only care about a\n // handful of fields here. The final return casts through `unknown`\n // because the JSON round-trip is shape-preserving by construction.\n const cloned = JSON.parse(JSON.stringify(doc)) as {\n runs?: Array<Record<string, unknown>>;\n };\n const runs = Array.isArray(cloned.runs) ? cloned.runs : [];\n\n for (const run of runs) {\n const rawResults = run[\"results\"];\n const results = Array.isArray(rawResults) ? (rawResults as Array<Record<string, unknown>>) : [];\n for (const result of results) {\n findingCount += 1;\n const ruleId = typeof result[\"ruleId\"] === \"string\" ? (result[\"ruleId\"] as string) : \"\";\n const level = result[\"level\"] as SarifLevel | undefined;\n const override = matchOverride(ruleId);\n const effort = estimateEffortMinutes(level, override);\n totalEffortMinutes += effort;\n const existingProps =\n result[\"properties\"] && typeof result[\"properties\"] === \"object\"\n ? (result[\"properties\"] as Record<string, unknown>)\n : {};\n result[\"properties\"] = {\n ...existingProps,\n sourceTool: SEMGREP,\n effortMinutes: effort,\n };\n }\n\n // Overwrite tool.driver.name so store-level filters always match\n // `\"semgrep\"` regardless of the label Semgrep reported. Preserve\n // the existing version and rules[] array when present.\n const existingTool = (run[\"tool\"] as Record<string, unknown> | undefined) ?? {};\n const existingDriver = (existingTool[\"driver\"] as Record<string, unknown> | undefined) ?? {};\n const driverOut: Record<string, unknown> = {\n name: SEMGREP,\n version: typeof existingDriver[\"version\"] === \"string\" ? existingDriver[\"version\"] : \"unknown\",\n };\n if (Array.isArray(existingDriver[\"rules\"])) {\n driverOut[\"rules\"] = existingDriver[\"rules\"];\n }\n run[\"tool\"] = { driver: driverOut };\n }\n\n return {\n document: cloned as unknown as PersistedSarif,\n sourceTool: SEMGREP,\n findingCount,\n totalEffortMinutes,\n };\n}\n\n/**\n * Accept either a pre-parsed SARIF object or a JSON string and return\n * a strongly-typed `PersistedSarif`. Throws on malformed input.\n *\n * @param input Raw caller-provided value.\n */\nfunction coerceToSarif(input: unknown): PersistedSarif {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:semgrep] input is not a SARIF object`);\n }\n const doc = parsed as { version?: unknown; runs?: unknown };\n if (doc.version !== \"2.1.0\") {\n throw new Error(\n `[adapter:semgrep] expected SARIF version 2.1.0, got ${String(doc.version)}`,\n );\n }\n if (!Array.isArray(doc.runs)) {\n throw new Error(`[adapter:semgrep] document is missing a runs[] array`);\n }\n return parsed as PersistedSarif;\n}\n\n/**\n * Return the effort override (in minutes) matching the first pattern\n * that matches the given rule id, or `undefined` when none match.\n *\n * @param ruleId Semgrep rule identifier.\n */\nfunction matchOverride(ruleId: string): number | undefined {\n for (const [pattern, minutes] of SEMGREP_EFFORT_OVERRIDES) {\n if (pattern.test(ruleId)) return minutes;\n }\n return undefined;\n}\n", "/**\n * ESLint adapter.\n *\n * ESLint's default JSON output (`eslint -f json .`) is NOT SARIF.\n * This adapter converts it into a SARIF 2.1.0 document with one\n * `result` per ESLint `messages[]` entry, mapping ESLint's numeric\n * severity to SARIF levels:\n *\n * severity 0 \u2192 \"note\" (parser info / disabled)\n * severity 1 \u2192 \"warning\"\n * severity 2 \u2192 \"error\"\n *\n * ESLint's JSON shape:\n *\n * [\n * {\n * \"filePath\": \"/abs/path/to/foo.js\",\n * \"messages\": [\n * {\n * \"ruleId\": \"no-unused-vars\",\n * \"severity\": 1,\n * \"message\": \"'foo' is defined but never used.\",\n * \"line\": 10,\n * \"column\": 5,\n * \"endLine\": 10,\n * \"endColumn\": 8\n * }\n * ],\n * \"errorCount\": 0,\n * \"warningCount\": 1,\n * \"fatalErrorCount\": 0,\n * \"source\": \"...\",\n * \"usedDeprecatedRules\": []\n * }\n * ]\n *\n * We preserve the full `line`/`column` range when ESLint provides one\n * so the dashboard's hot-spot table can show a precise location.\n *\n * @module adapters/eslint\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst ESLINT: KnownScanner = \"eslint\";\n\n/**\n * ESLint JSON file entry as produced by `eslint -f json`. We type it\n * permissively because many ESLint fields are optional depending on\n * version and plugin.\n */\ninterface EslintFileReport {\n readonly filePath?: string;\n readonly messages?: ReadonlyArray<EslintMessage>;\n}\n\ninterface EslintMessage {\n readonly ruleId?: string | null;\n readonly severity?: number;\n readonly message?: string;\n readonly line?: number;\n readonly column?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n readonly fatal?: boolean;\n}\n\n/**\n * Accept ESLint native JSON output and return a normalized\n * `PersistedSarif` document plus counts.\n *\n * @param input Raw ESLint JSON (string or parsed array).\n * @returns Adapter result.\n * @throws When the input is not a valid ESLint report.\n */\nexport function adaptEslint(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!Array.isArray(parsed)) {\n throw new Error(`[adapter:eslint] expected an array of file reports`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const fileReport of parsed as ReadonlyArray<EslintFileReport>) {\n const filePath = fileReport?.filePath;\n if (typeof filePath !== \"string\" || !filePath) continue;\n const messages = Array.isArray(fileReport.messages) ? fileReport.messages : [];\n for (const msg of messages) {\n const level = mapSeverity(msg.severity);\n const ruleId = typeof msg.ruleId === \"string\" ? msg.ruleId : \"eslint.unknown\";\n const line = typeof msg.line === \"number\" && msg.line > 0 ? msg.line : 1;\n const column = typeof msg.column === \"number\" && msg.column > 0 ? msg.column : 1;\n const effort = estimateEffortMinutes(level);\n totalEffortMinutes += effort;\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message: msg.message ?? ruleId,\n uri: filePath,\n startLine: line,\n startColumn: column,\n endLine: typeof msg.endLine === \"number\" ? msg.endLine : undefined,\n endColumn: typeof msg.endColumn === \"number\" ? msg.endColumn : undefined,\n effortMinutes: effort,\n }),\n );\n }\n }\n\n return {\n document: wrapResultsInSarif(ESLINT, \"unknown\", results),\n sourceTool: ESLINT,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Translate ESLint's numeric severity to a SARIF level. ESLint uses:\n *\n * 0 = off / disabled \u2192 `\"note\"` (informational)\n * 1 = warn \u2192 `\"warning\"`\n * 2 = error \u2192 `\"error\"`\n *\n * Unknown values default to `\"warning\"` so the finding is still\n * visible without being treated as a blocker.\n */\nfunction mapSeverity(severity: number | undefined): SarifLevel {\n switch (severity) {\n case 2:\n return \"error\";\n case 1:\n return \"warning\";\n case 0:\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n/**\n * Assemble a SARIF `result` object from the narrow set of fields an\n * ESLint message provides. The shape matches what the SarifStore\n * expects when hydrating a finding from a persisted document.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n endLine?: number | undefined;\n endColumn?: number | undefined;\n effortMinutes: number;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n ...(opts.endLine !== undefined ? { endLine: opts.endLine } : {}),\n ...(opts.endColumn !== undefined ? { endColumn: opts.endColumn } : {}),\n },\n },\n },\n ],\n properties: {\n sourceTool: ESLINT,\n effortMinutes: opts.effortMinutes,\n },\n };\n}\n", "/**\n * Bandit adapter.\n *\n * Bandit is a Python security linter. When run with `-f json` it\n * emits a JSON report shaped like this (abbreviated):\n *\n * {\n * \"results\": [\n * {\n * \"filename\": \"app.py\",\n * \"line_number\": 42,\n * \"col_offset\": 5,\n * \"test_id\": \"B608\",\n * \"test_name\": \"hardcoded_sql_expressions\",\n * \"issue_severity\": \"HIGH\", // LOW | MEDIUM | HIGH\n * \"issue_confidence\": \"HIGH\", // LOW | MEDIUM | HIGH\n * \"issue_text\": \"Possible SQL injection via string-based query construction.\",\n * \"issue_cwe\": { \"id\": 89 }\n * }\n * ],\n * \"metrics\": { ... },\n * \"errors\": [ ... ]\n * }\n *\n * This adapter converts each `results[]` entry into a SARIF 2.1.0\n * `result`, mapping Bandit severity levels to SARIF levels:\n *\n * LOW \u2192 \"note\"\n * MEDIUM \u2192 \"warning\"\n * HIGH \u2192 \"error\"\n *\n * Every finding gets a rule id of `bandit.<test_id>` (e.g.\n * `bandit.B608`) so it is trivial to correlate with Bandit's own docs\n * from inside the claude-crap dashboard.\n *\n * @module adapters/bandit\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst BANDIT: KnownScanner = \"bandit\";\n\ninterface BanditReport {\n readonly results?: ReadonlyArray<BanditFinding>;\n}\n\ninterface BanditFinding {\n readonly filename?: string;\n readonly line_number?: number;\n readonly col_offset?: number;\n readonly test_id?: string;\n readonly test_name?: string;\n readonly issue_severity?: string;\n readonly issue_confidence?: string;\n readonly issue_text?: string;\n readonly issue_cwe?: { readonly id?: number };\n}\n\n/**\n * Accept a Bandit JSON report and return a normalized\n * `PersistedSarif` document.\n *\n * @param input Raw Bandit JSON (string or parsed object).\n * @returns Adapter result.\n * @throws When the input does not look like a Bandit report.\n */\nexport function adaptBandit(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:bandit] expected a JSON object`);\n }\n const report = parsed as BanditReport;\n if (!Array.isArray(report.results)) {\n throw new Error(`[adapter:bandit] report is missing a results[] array`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const finding of report.results) {\n const filename = finding.filename;\n if (typeof filename !== \"string\" || !filename) continue;\n const level = mapSeverity(finding.issue_severity);\n // High-severity security findings cost more to fix than the\n // generic default, so we bias the budget toward reality. Bandit\n // is always security-focused, so every finding is treated as a\n // security issue for TDR accounting downstream.\n const effortOverride = level === \"error\" ? 120 : level === \"warning\" ? 60 : 20;\n const effort = estimateEffortMinutes(level, effortOverride);\n totalEffortMinutes += effort;\n\n const testId = finding.test_id ?? \"unknown\";\n const ruleId = `bandit.${testId}`;\n const messageText =\n finding.issue_text ??\n `${finding.test_name ?? \"Bandit finding\"} (${finding.issue_severity ?? \"UNKNOWN\"})`;\n\n const startLine =\n typeof finding.line_number === \"number\" && finding.line_number > 0\n ? finding.line_number\n : 1;\n const startColumn =\n typeof finding.col_offset === \"number\" && finding.col_offset >= 0\n ? finding.col_offset + 1\n : 1;\n\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message: messageText,\n uri: filename,\n startLine,\n startColumn,\n effortMinutes: effort,\n cwe: finding.issue_cwe?.id,\n confidence: finding.issue_confidence,\n }),\n );\n }\n\n return {\n document: wrapResultsInSarif(BANDIT, \"unknown\", results),\n sourceTool: BANDIT,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Map Bandit's `issue_severity` string to a SARIF level. Unknown\n * values default to `\"warning\"` so findings are still surfaced.\n */\nfunction mapSeverity(severity: string | undefined): SarifLevel {\n switch ((severity ?? \"\").toUpperCase()) {\n case \"HIGH\":\n return \"error\";\n case \"MEDIUM\":\n return \"warning\";\n case \"LOW\":\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n/**\n * Build the SARIF `result` object for a single Bandit finding. We\n * stash the CWE id and Bandit confidence in the `properties` bag so\n * consumers can surface them in the dashboard hot-spot view.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n effortMinutes: number;\n cwe?: number | undefined;\n confidence?: string | undefined;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n },\n },\n },\n ],\n properties: {\n sourceTool: BANDIT,\n effortMinutes: opts.effortMinutes,\n ...(typeof opts.cwe === \"number\" ? { cwe: opts.cwe } : {}),\n ...(typeof opts.confidence === \"string\" ? { confidence: opts.confidence } : {}),\n },\n };\n}\n", "/**\n * Stryker (JavaScript mutation testing) adapter.\n *\n * Stryker emits a JSON report under `reports/mutation/mutation.json`.\n * The report shape is documented at\n * https://stryker-mutator.io/docs/mutation-testing-elements/mutant-result-schema/ :\n *\n * {\n * \"schemaVersion\": \"1.0\",\n * \"thresholds\": { ... },\n * \"files\": {\n * \"src/foo.ts\": {\n * \"language\": \"typescript\",\n * \"source\": \"...\",\n * \"mutants\": [\n * {\n * \"id\": \"1\",\n * \"mutatorName\": \"ConditionalExpression\",\n * \"replacement\": \"false\",\n * \"location\": {\n * \"start\": { \"line\": 10, \"column\": 5 },\n * \"end\": { \"line\": 10, \"column\": 15 }\n * },\n * \"status\": \"Survived\", // Killed | Survived | Timeout | NoCoverage | RuntimeError | CompileError | Ignored\n * \"statusReason\": \"...\"\n * }\n * ]\n * }\n * }\n * }\n *\n * This adapter treats every **surviving mutant** as a SARIF\n * `error`-level finding \u2014 surviving mutants are exactly the ones the\n * Golden Rule forbids, because they prove the test suite does not\n * pin the code's behavior tightly enough to notice a change.\n *\n * Mutants with status `NoCoverage` become `warning`-level findings\n * (not blocking the Stop gate by themselves, but still ingested so\n * the dashboard can surface uncovered lines). All other statuses are\n * ignored \u2014 they do not represent defects.\n *\n * @module adapters/stryker\n */\n\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\nimport {\n estimateEffortMinutes,\n wrapResultsInSarif,\n type AdapterResult,\n type KnownScanner,\n} from \"./common.js\";\n\nconst STRYKER: KnownScanner = \"stryker\";\n\ninterface StrykerReport {\n readonly schemaVersion?: string;\n readonly files?: Record<string, StrykerFileReport>;\n}\n\ninterface StrykerFileReport {\n readonly language?: string;\n readonly mutants?: ReadonlyArray<StrykerMutant>;\n}\n\ninterface StrykerMutant {\n readonly id?: string;\n readonly mutatorName?: string;\n readonly replacement?: string;\n readonly location?: {\n readonly start?: { readonly line?: number; readonly column?: number };\n readonly end?: { readonly line?: number; readonly column?: number };\n };\n readonly status?: string;\n readonly statusReason?: string;\n}\n\n/**\n * Accept a Stryker JSON mutation report and return a normalized\n * `PersistedSarif` document with one finding per surviving mutant\n * and per uncovered mutant.\n *\n * @param input Raw Stryker report (string or parsed object).\n * @returns Adapter result.\n * @throws When the input is not a Stryker mutation report.\n */\nexport function adaptStryker(input: unknown): AdapterResult {\n const parsed = typeof input === \"string\" ? (JSON.parse(input) as unknown) : input;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`[adapter:stryker] expected a JSON object`);\n }\n const report = parsed as StrykerReport;\n if (!report.files || typeof report.files !== \"object\") {\n throw new Error(`[adapter:stryker] report is missing a files{} map`);\n }\n\n const results: Array<ReturnType<typeof buildSarifResult>> = [];\n let totalEffortMinutes = 0;\n\n for (const [filename, fileReport] of Object.entries(report.files)) {\n const mutants = Array.isArray(fileReport?.mutants) ? fileReport.mutants : [];\n for (const mutant of mutants) {\n const level = classifyMutant(mutant.status);\n if (level === null) continue; // Killed / Ignored / CompileError \u2014 not a defect\n const startLine = mutant.location?.start?.line ?? 1;\n const startColumn = mutant.location?.start?.column ?? 1;\n const endLine = mutant.location?.end?.line;\n const endColumn = mutant.location?.end?.column;\n\n // Surviving mutants cost more to fix than the default error\n // budget because the agent has to first write a killing test,\n // THEN possibly rewrite the code.\n const effortOverride = level === \"error\" ? 45 : 15;\n const effort = estimateEffortMinutes(level, effortOverride);\n totalEffortMinutes += effort;\n\n const mutator = mutant.mutatorName ?? \"Unknown\";\n const ruleId = `stryker.${mutator}`;\n const statusText = mutant.status ?? \"Unknown\";\n const message =\n `${statusText}: ${mutator} mutant on '${mutant.replacement ?? \"?\"}'` +\n (mutant.statusReason ? ` \u2014 ${mutant.statusReason}` : \"\");\n\n results.push(\n buildSarifResult({\n ruleId,\n level,\n message,\n uri: filename,\n startLine,\n startColumn,\n endLine: typeof endLine === \"number\" ? endLine : undefined,\n endColumn: typeof endColumn === \"number\" ? endColumn : undefined,\n effortMinutes: effort,\n mutantId: mutant.id,\n mutator,\n mutantStatus: statusText,\n }),\n );\n }\n }\n\n return {\n document: wrapResultsInSarif(STRYKER, String(report.schemaVersion ?? \"unknown\"), results),\n sourceTool: STRYKER,\n findingCount: results.length,\n totalEffortMinutes,\n };\n}\n\n/**\n * Classify a Stryker mutant status into a SARIF level, or `null` when\n * the status represents a mutant that was correctly handled by the\n * test suite and should not produce a finding.\n */\nfunction classifyMutant(status: string | undefined): SarifLevel | null {\n switch ((status ?? \"\").toLowerCase()) {\n case \"survived\":\n return \"error\";\n case \"nocoverage\":\n return \"warning\";\n case \"timeout\":\n // Timeout mutants are suspicious but not proof of defect \u2014\n // they deserve a note so the dashboard highlights them.\n return \"note\";\n case \"killed\":\n case \"ignored\":\n case \"compileerror\":\n case \"runtimeerror\":\n default:\n return null;\n }\n}\n\n/**\n * Build the SARIF `result` object for a single Stryker mutant. We\n * propagate the mutant id, mutator name, and raw status into\n * `properties` so the dashboard can display them as tags.\n */\nfunction buildSarifResult(opts: {\n ruleId: string;\n level: SarifLevel;\n message: string;\n uri: string;\n startLine: number;\n startColumn: number;\n endLine?: number | undefined;\n endColumn?: number | undefined;\n effortMinutes: number;\n mutantId?: string | undefined;\n mutator?: string | undefined;\n mutantStatus?: string | undefined;\n}) {\n return {\n ruleId: opts.ruleId,\n level: opts.level,\n message: { text: opts.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: opts.uri },\n region: {\n startLine: opts.startLine,\n startColumn: opts.startColumn,\n ...(opts.endLine !== undefined ? { endLine: opts.endLine } : {}),\n ...(opts.endColumn !== undefined ? { endColumn: opts.endColumn } : {}),\n },\n },\n },\n ],\n properties: {\n sourceTool: STRYKER,\n effortMinutes: opts.effortMinutes,\n ...(opts.mutantId ? { mutantId: opts.mutantId } : {}),\n ...(opts.mutator ? { mutator: opts.mutator } : {}),\n ...(opts.mutantStatus ? { mutantStatus: opts.mutantStatus } : {}),\n },\n };\n}\n", "/**\n * Adapter: `dart analyze --format=json` \u2192 SARIF 2.1.0.\n *\n * The Dart analyzer emits JSON with this shape:\n *\n * {\n * \"version\": 1,\n * \"diagnostics\": [\n * {\n * \"code\": \"unused_import\",\n * \"severity\": \"WARNING\",\n * \"type\": \"STATIC_WARNING\",\n * \"location\": {\n * \"file\": \"/absolute/path/to/file.dart\",\n * \"range\": {\n * \"start\": { \"offset\": 7, \"line\": 1, \"column\": 8 },\n * \"end\": { \"offset\": 16, \"line\": 1, \"column\": 17 }\n * }\n * },\n * \"problemMessage\": \"Unused import: 'dart:io'.\",\n * \"correctionMessage\": \"Try removing the import directive.\",\n * \"documentation\": \"https://dart.dev/diagnostics/unused_import\"\n * }\n * ]\n * }\n *\n * Severity mapping:\n * - \"ERROR\" \u2192 SARIF \"error\" (30 min effort)\n * - \"WARNING\" \u2192 SARIF \"warning\" (15 min effort)\n * - \"INFO\" \u2192 SARIF \"note\" (5 min effort)\n *\n * @module adapters/dart-analyzer\n */\n\nimport {\n type AdapterResult,\n wrapResultsInSarif,\n estimateEffortMinutes,\n} from \"./common.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface DartDiagnosticLocation {\n file: string;\n range: {\n start: { offset: number; line: number; column: number };\n end: { offset: number; line: number; column: number };\n };\n}\n\ninterface DartDiagnostic {\n code: string;\n severity: string;\n type: string;\n location: DartDiagnosticLocation;\n problemMessage: string;\n correctionMessage?: string;\n documentation?: string;\n}\n\ninterface DartAnalyzeOutput {\n version: number;\n diagnostics: DartDiagnostic[];\n}\n\n// \u2500\u2500 Severity mapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction mapSeverity(dartSeverity: string): SarifLevel {\n switch (dartSeverity.toUpperCase()) {\n case \"ERROR\":\n return \"error\";\n case \"WARNING\":\n return \"warning\";\n case \"INFO\":\n return \"note\";\n default:\n return \"warning\";\n }\n}\n\n// \u2500\u2500 Effort estimates per severity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst EFFORT_BY_SEVERITY: Record<SarifLevel, number> = {\n error: 30,\n warning: 15,\n note: 5,\n none: 0,\n};\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Convert `dart analyze --format=json` output to SARIF 2.1.0.\n *\n * @param rawOutput The JSON string or pre-parsed object from `dart analyze`.\n */\nexport function adaptDartAnalyzer(rawOutput: unknown): AdapterResult {\n let parsed: DartAnalyzeOutput;\n\n if (typeof rawOutput === \"string\") {\n try {\n parsed = JSON.parse(rawOutput) as DartAnalyzeOutput;\n } catch {\n throw new Error(\"[dart-analyzer adapter] rawOutput is not valid JSON\");\n }\n } else if (rawOutput && typeof rawOutput === \"object\" && \"diagnostics\" in rawOutput) {\n parsed = rawOutput as DartAnalyzeOutput;\n } else {\n throw new Error(\n \"[dart-analyzer adapter] rawOutput must be a JSON string or an object with a 'diagnostics' array\",\n );\n }\n\n if (!Array.isArray(parsed.diagnostics)) {\n throw new Error(\"[dart-analyzer adapter] 'diagnostics' must be an array\");\n }\n\n const results: object[] = [];\n let totalEffortMinutes = 0;\n\n for (const diag of parsed.diagnostics) {\n const level = mapSeverity(diag.severity);\n const effort = EFFORT_BY_SEVERITY[level] ?? estimateEffortMinutes(level);\n totalEffortMinutes += effort;\n\n results.push({\n ruleId: diag.code,\n level,\n message: {\n text: diag.problemMessage + (diag.correctionMessage ? ` ${diag.correctionMessage}` : \"\"),\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: diag.location.file,\n },\n region: {\n startLine: diag.location.range.start.line,\n startColumn: diag.location.range.start.column,\n endLine: diag.location.range.end.line,\n endColumn: diag.location.range.end.column,\n },\n },\n },\n ],\n properties: {\n effortMinutes: effort,\n ...(diag.documentation ? { helpUri: diag.documentation } : {}),\n },\n });\n }\n\n return {\n document: wrapResultsInSarif(\"dart_analyze\", \"1.0.0\", results),\n sourceTool: \"dart_analyze\",\n findingCount: parsed.diagnostics.length,\n totalEffortMinutes,\n };\n}\n", "/**\n * Adapter: `dotnet format --report <path>` JSON output \u2192 SARIF 2.1.0.\n *\n * The dotnet format tool emits a JSON array with this shape:\n *\n * [\n * {\n * \"DocumentId\": { \"ProjectId\": { \"Id\": \"...\" }, \"Id\": \"...\" },\n * \"FileName\": \"AuthController.cs\",\n * \"FilePath\": \"/absolute/path/to/AuthController.cs\",\n * \"FileChanges\": [\n * {\n * \"LineNumber\": 84,\n * \"CharNumber\": 16,\n * \"DiagnosticId\": \"WHITESPACE\",\n * \"FormatDescription\": \"Fix whitespace formatting. Delete 5 characters.\"\n * }\n * ]\n * }\n * ]\n *\n * All dotnet format findings are style/formatting issues, so they\n * map uniformly to SARIF \"warning\" level with a 5-minute effort\n * estimate (formatting fixes are quick, mechanical changes).\n *\n * @module adapters/dotnet-format\n */\n\nimport {\n type AdapterResult,\n wrapResultsInSarif,\n} from \"./common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface DotnetFileChange {\n LineNumber: number;\n CharNumber: number;\n DiagnosticId: string;\n FormatDescription: string;\n}\n\ninterface DotnetFormatDocument {\n DocumentId: {\n ProjectId: { Id: string };\n Id: string;\n };\n FileName: string;\n FilePath: string;\n FileChanges: DotnetFileChange[];\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Convert `dotnet format --report <path>` JSON output to SARIF 2.1.0.\n *\n * @param rawOutput The JSON string or pre-parsed array from `dotnet format`.\n */\nexport function adaptDotnetFormat(rawOutput: unknown): AdapterResult {\n let parsed: DotnetFormatDocument[];\n\n if (typeof rawOutput === \"string\") {\n try {\n parsed = JSON.parse(rawOutput) as DotnetFormatDocument[];\n } catch {\n throw new Error(\"[dotnet-format adapter] rawOutput is not valid JSON\");\n }\n } else if (Array.isArray(rawOutput)) {\n parsed = rawOutput as DotnetFormatDocument[];\n } else {\n throw new Error(\n \"[dotnet-format adapter] rawOutput must be a JSON string or an array of document entries\",\n );\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(\"[dotnet-format adapter] parsed output must be an array\");\n }\n\n const EFFORT_MINUTES = 5;\n const results: object[] = [];\n let findingCount = 0;\n let totalEffortMinutes = 0;\n\n for (const doc of parsed) {\n if (!Array.isArray(doc.FileChanges)) continue;\n\n for (const change of doc.FileChanges) {\n findingCount++;\n totalEffortMinutes += EFFORT_MINUTES;\n\n results.push({\n ruleId: change.DiagnosticId,\n level: \"warning\",\n message: {\n text: change.FormatDescription,\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: doc.FilePath,\n },\n region: {\n startLine: change.LineNumber,\n startColumn: change.CharNumber,\n },\n },\n },\n ],\n properties: {\n effortMinutes: EFFORT_MINUTES,\n },\n });\n }\n }\n\n return {\n document: wrapResultsInSarif(\"dotnet_format\", \"1.0.0\", results),\n sourceTool: \"dotnet_format\",\n findingCount,\n totalEffortMinutes,\n };\n}\n", "/**\n * Public SDK entry point for the per-scanner SARIF adapters.\n *\n * Adapters convert a scanner's native output (SARIF, JSON, or some\n * other structured format) into a normalized `PersistedSarif`\n * document that the `SarifStore` can ingest directly. Every adapter\n * enriches its findings with a stable `effortMinutes` value on the\n * `properties` bag so the Stop quality gate and the project score\n * engine can compute a Technical Debt Ratio.\n *\n * Usage:\n *\n * ```ts\n * import {\n * adaptScannerOutput,\n * adaptSemgrep,\n * adaptEslint,\n * adaptBandit,\n * adaptStryker,\n * } from \"claude-crap/adapters\";\n *\n * const result = adaptScannerOutput(\"eslint\", rawJsonFromEslint);\n * sarifStore.ingestRun(result.document, result.sourceTool);\n * ```\n *\n * @module adapters\n */\n\nexport { adaptSemgrep } from \"./semgrep.js\";\nexport { adaptEslint } from \"./eslint.js\";\nexport { adaptBandit } from \"./bandit.js\";\nexport { adaptStryker } from \"./stryker.js\";\nexport { adaptDartAnalyzer } from \"./dart-analyzer.js\";\nexport { adaptDotnetFormat } from \"./dotnet-format.js\";\n\nexport {\n DEFAULT_EFFORT_BY_SEVERITY,\n KNOWN_SCANNERS,\n estimateEffortMinutes,\n wrapResultsInSarif,\n} from \"./common.js\";\n\nexport type { AdapterResult, KnownScanner } from \"./common.js\";\n\nimport { adaptSemgrep } from \"./semgrep.js\";\nimport { adaptEslint } from \"./eslint.js\";\nimport { adaptBandit } from \"./bandit.js\";\nimport { adaptStryker } from \"./stryker.js\";\nimport { adaptDartAnalyzer } from \"./dart-analyzer.js\";\nimport { adaptDotnetFormat } from \"./dotnet-format.js\";\nimport type { AdapterResult, KnownScanner } from \"./common.js\";\n\n/**\n * Route a raw scanner output to the correct adapter based on its\n * name. Preferred entry point for the `ingest_scanner_output` MCP\n * tool \u2014 the dispatch is a single switch so the compiler can verify\n * every case with `never` exhaustiveness.\n *\n * @param scanner One of the known scanner identifiers.\n * @param rawOutput The scanner's native output (string or parsed).\n * @returns A normalized `AdapterResult`.\n * @throws When `scanner` is unknown or the raw output is malformed.\n */\nexport function adaptScannerOutput(\n scanner: KnownScanner,\n rawOutput: unknown,\n): AdapterResult {\n switch (scanner) {\n case \"semgrep\":\n return adaptSemgrep(rawOutput);\n case \"eslint\":\n return adaptEslint(rawOutput);\n case \"bandit\":\n return adaptBandit(rawOutput);\n case \"stryker\":\n return adaptStryker(rawOutput);\n case \"dart_analyze\":\n return adaptDartAnalyzer(rawOutput);\n case \"dotnet_format\":\n return adaptDotnetFormat(rawOutput);\n default: {\n const exhaustive: never = scanner;\n throw new Error(`[adapters] Unknown scanner: ${String(exhaustive)}`);\n }\n }\n}\n", "/**\n * Tree-sitter based AST analysis engine.\n *\n * This module wraps `web-tree-sitter` (the WASM build of tree-sitter) to\n * parse source files and extract deterministic per-function metrics. The\n * WASM variant is used instead of the native bindings so that `npm install`\n * never has to invoke a C compiler \u2014 matching the plugin's \"zero install\n * friction\" promise.\n *\n * The engine is lazy:\n *\n * - `web-tree-sitter` is initialized only on first use.\n * - Grammar WASM files are loaded on demand and cached per language.\n *\n * This keeps MCP server startup fast (crucial because Claude Code will\n * spin the server up and tear it down across sessions).\n *\n * Usage:\n *\n * ```ts\n * const engine = new TreeSitterEngine();\n * const result = await engine.analyzeFile({\n * filePath: \"src/foo.ts\",\n * language: \"typescript\",\n * });\n * console.log(result.functions);\n * ```\n *\n * @module ast/tree-sitter-engine\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { computeCyclomaticComplexity, type AstNode } from \"./cyclomatic.js\";\nimport { LANGUAGE_TABLE, type LanguageConfig, type SupportedLanguage } from \"./language-config.js\";\n\n/**\n * Minimal typed view of the `web-tree-sitter` Parser class and its\n * static helpers. The npm package uses `export = Parser` (a CommonJS\n * default export), so under ESM interop `await import('web-tree-sitter')`\n * returns `{ default: Parser }` where `Parser`:\n *\n * - is a constructable class (`new Parser()`)\n * - exposes `static init(moduleOptions)` to bootstrap the WASM runtime\n * - exposes the nested `Parser.Language.load(pathOrBytes)` static\n * to load a grammar from a `.wasm` file or a raw byte buffer\n *\n * We model that surface here so downstream consumers of this engine are\n * not forced to import `web-tree-sitter` types directly.\n */\ninterface ParserInstance {\n setLanguage(language: unknown): void;\n parse(source: string): { rootNode: AstNode };\n}\n\ninterface ParserCtor {\n new (): ParserInstance;\n init(options?: { locateFile?: (name: string) => string }): Promise<void>;\n Language: { load(path: string | Uint8Array): Promise<unknown> };\n}\n\n/**\n * Per-function metrics returned by the engine.\n */\nexport interface FunctionMetrics {\n /** Human-readable function name, or `\"<anonymous>\"` when not available. */\n readonly name: string;\n /** 1-based line where the function body starts. */\n readonly startLine: number;\n /** 1-based line where the function body ends. */\n readonly endLine: number;\n /** McCabe cyclomatic complexity (always \u2265 1). */\n readonly cyclomaticComplexity: number;\n /** Physical lines of code covered by the function (endLine - startLine + 1). */\n readonly lineCount: number;\n}\n\n/**\n * File-level metrics returned by the engine.\n */\nexport interface FileMetrics {\n /** File path that was analyzed, echoed from the request for traceability. */\n readonly filePath: string;\n /** Language the file was parsed as. */\n readonly language: SupportedLanguage;\n /** Total physical lines in the file, including blanks and comments. */\n readonly physicalLoc: number;\n /** Physical lines that contain at least one non-whitespace character. */\n readonly logicalLoc: number;\n /** Per-function metrics sorted by starting line. */\n readonly functions: ReadonlyArray<FunctionMetrics>;\n}\n\n/**\n * Request accepted by {@link TreeSitterEngine.analyzeFile}.\n */\nexport interface AnalyzeFileRequest {\n readonly filePath: string;\n readonly language: SupportedLanguage;\n}\n\n/**\n * Options accepted by the engine constructor. All fields are optional and\n * safe defaults are used when omitted.\n */\nexport interface TreeSitterEngineOptions {\n /**\n * Directory where the language grammar WASM files live (one per\n * language, e.g. `tree-sitter-typescript.wasm`). Defaults to the\n * `tree-sitter-wasms/out` directory inside `node_modules`.\n */\n readonly grammarsDir?: string;\n /**\n * Directory where the `web-tree-sitter` runtime WASM (`tree-sitter.wasm`)\n * lives. This is a different package from the grammars \u2014 the runtime\n * ships with `web-tree-sitter` itself. Defaults to that package's\n * install directory inside `node_modules`.\n */\n readonly runtimeDir?: string;\n /**\n * Override the WASM loader for tests. Receives the grammar filename\n * and must return the raw bytes.\n */\n readonly loadGrammar?: (wasmPath: string) => Promise<Uint8Array>;\n}\n\n/**\n * High-level AST engine. Instances are meant to be long-lived \u2014 create\n * one at server startup and reuse it for every analysis request.\n */\nexport class TreeSitterEngine {\n private parserCtor: ParserCtor | null = null;\n private readonly loadedLanguages = new Map<SupportedLanguage, unknown>();\n private readonly grammarsDir: string;\n private readonly runtimeDir: string;\n private readonly loadGrammar: (wasmPath: string) => Promise<Uint8Array>;\n private initPromise: Promise<void> | null = null;\n\n constructor(options: TreeSitterEngineOptions = {}) {\n this.grammarsDir = options.grammarsDir ?? resolveDefaultGrammarsDir();\n this.runtimeDir = options.runtimeDir ?? resolveDefaultRuntimeDir();\n this.loadGrammar = options.loadGrammar ?? ((path) => fs.readFile(path));\n }\n\n /**\n * Analyze a source file and return per-function and file-level metrics.\n *\n * @param req The analysis request.\n * @returns A {@link FileMetrics} snapshot ready to be serialized.\n * @throws When the file cannot be read or the grammar cannot be loaded.\n */\n async analyzeFile(req: AnalyzeFileRequest): Promise<FileMetrics> {\n const languageConfig = LANGUAGE_TABLE[req.language];\n if (!languageConfig) {\n throw new Error(`[tree-sitter-engine] Unsupported language: ${req.language}`);\n }\n\n const source = await fs.readFile(req.filePath, \"utf8\");\n const parser = await this.ensureParserFor(languageConfig);\n const tree = parser.parse(source);\n\n const functions = collectFunctionMetrics(tree.rootNode, languageConfig);\n const { physicalLoc, logicalLoc } = countLines(source);\n\n return {\n filePath: req.filePath,\n language: languageConfig.id,\n physicalLoc,\n logicalLoc,\n functions,\n };\n }\n\n /**\n * Ensure a parser with the requested language grammar bound is ready.\n * Both the Parser class and the grammar are initialized lazily and\n * cached on first use.\n *\n * @param config Language configuration for the requested grammar.\n * @returns A fresh parser instance configured for the language.\n */\n private async ensureParserFor(config: LanguageConfig): Promise<ParserInstance> {\n if (!this.parserCtor) {\n if (!this.initPromise) {\n this.initPromise = this.initParserModule();\n }\n await this.initPromise;\n }\n const Parser = this.parserCtor;\n if (!Parser) {\n throw new Error(\"[tree-sitter-engine] Parser class failed to initialize\");\n }\n\n let language = this.loadedLanguages.get(config.id);\n if (!language) {\n const wasmPath = join(this.grammarsDir, config.wasmName);\n const bytes = await this.loadGrammar(wasmPath);\n language = await Parser.Language.load(bytes);\n this.loadedLanguages.set(config.id, language);\n }\n\n const parser = new Parser();\n parser.setLanguage(language);\n return parser;\n }\n\n /**\n * Import and initialize `web-tree-sitter`. Isolated in its own method\n * so the dynamic import runs exactly once per engine instance.\n *\n * `web-tree-sitter` uses `export = Parser` so under ESM interop the\n * Parser class arrives on the `default` property of the imported\n * namespace. `Parser.init()` is a STATIC method on the class, not a\n * top-level module function.\n */\n private async initParserModule(): Promise<void> {\n const imported = (await import(\"web-tree-sitter\")) as { default: ParserCtor };\n const Parser = imported.default;\n if (!Parser || typeof Parser.init !== \"function\") {\n throw new Error(\n \"[tree-sitter-engine] web-tree-sitter did not expose the expected Parser class\",\n );\n }\n // Emscripten calls `locateFile` to resolve the runtime WASM during\n // `Parser.init()`. The runtime file (`tree-sitter.wasm`) lives inside\n // the `web-tree-sitter` package itself, NOT alongside the grammars,\n // so we route requests for that exact filename to `runtimeDir`.\n // Anything else falls back to `grammarsDir` for the per-language\n // grammar files loaded later by `Parser.Language.load()`.\n await Parser.init({\n locateFile: (name: string) =>\n name === \"tree-sitter.wasm\"\n ? join(this.runtimeDir, name)\n : join(this.grammarsDir, name),\n });\n this.parserCtor = Parser;\n }\n}\n\n/**\n * Resolve the default grammar directory to `tree-sitter-wasms/out` inside\n * `node_modules`. Uses `createRequire` so the lookup works regardless of\n * whether the caller is running from source (`tsx`) or from the built\n * `dist/` directory.\n */\nfunction resolveDefaultGrammarsDir(): string {\n try {\n const requireFromHere = createRequire(import.meta.url);\n // `tree-sitter-wasms` exposes its grammar files under `out/`.\n const pkgJsonPath = requireFromHere.resolve(\"tree-sitter-wasms/package.json\");\n return join(dirname(pkgJsonPath), \"out\");\n } catch {\n // Fall back to a sibling `grammars/` directory if the npm package\n // is not installed \u2014 useful for repo-local grammars.\n const here = dirname(fileURLToPath(import.meta.url));\n return resolve(here, \"..\", \"..\", \"grammars\");\n }\n}\n\n/**\n * Resolve the default runtime directory to the `web-tree-sitter` package\n * root inside `node_modules`. The runtime WASM (`tree-sitter.wasm`) ships\n * with the `web-tree-sitter` package itself rather than with the grammar\n * package, so we have to look it up separately from the grammars.\n */\nfunction resolveDefaultRuntimeDir(): string {\n try {\n const requireFromHere = createRequire(import.meta.url);\n const pkgJsonPath = requireFromHere.resolve(\"web-tree-sitter/package.json\");\n return dirname(pkgJsonPath);\n } catch {\n // Fall back to the grammars directory \u2014 better than nothing if\n // someone is running with a custom layout.\n return resolveDefaultGrammarsDir();\n }\n}\n\n/**\n * Walk the top-level AST and collect metrics for every function node,\n * including nested functions. The caller gets a flat, line-sorted list.\n *\n * @param root AST root node returned by tree-sitter.\n * @param languageConfig Language tables to classify nodes.\n * @returns Flat list of function metrics sorted by start line.\n */\nfunction collectFunctionMetrics(\n root: AstNode,\n languageConfig: LanguageConfig,\n): ReadonlyArray<FunctionMetrics> {\n const out: FunctionMetrics[] = [];\n\n function visit(node: AstNode): void {\n if (languageConfig.functionNodeTypes.has(node.type)) {\n out.push(buildFunctionMetrics(node, languageConfig));\n // Intentionally continue the walk so nested functions are also\n // reported. Each nested function's complexity is computed against\n // its own subtree; cyclomatic.ts skips nested functions during\n // the walk so the parent's score is not inflated.\n }\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (child) visit(child);\n }\n }\n\n visit(root);\n out.sort((a, b) => a.startLine - b.startLine);\n return out;\n}\n\n/**\n * Build a {@link FunctionMetrics} record for a single function node.\n */\nfunction buildFunctionMetrics(node: AstNode, languageConfig: LanguageConfig): FunctionMetrics {\n const name = extractFunctionName(node, languageConfig);\n const position = extractPosition(node);\n const complexity = computeCyclomaticComplexity(node, languageConfig);\n return {\n name,\n startLine: position.startLine,\n endLine: position.endLine,\n cyclomaticComplexity: complexity,\n lineCount: position.endLine - position.startLine + 1,\n };\n}\n\n/**\n * Pull the function name out of a function node. Tree-sitter exposes a\n * `childForFieldName` accessor on its real nodes; we feature-detect it\n * because our minimal {@link AstNode} contract does not require it.\n */\nfunction extractFunctionName(node: AstNode, languageConfig: LanguageConfig): string {\n const anyNode = node as AstNode & {\n childForFieldName?: (field: string) => AstNode | null;\n };\n if (typeof anyNode.childForFieldName === \"function\") {\n for (const field of languageConfig.nameFieldCandidates) {\n const nameNode = anyNode.childForFieldName(field);\n if (nameNode && nameNode.text) return nameNode.text;\n }\n }\n return \"<anonymous>\";\n}\n\n/**\n * Extract 1-based start/end line numbers for a node. Tree-sitter nodes\n * expose `startPosition` and `endPosition` with zero-based rows.\n */\nfunction extractPosition(node: AstNode): { startLine: number; endLine: number } {\n const anyNode = node as AstNode & {\n startPosition?: { row: number };\n endPosition?: { row: number };\n };\n const startRow = anyNode.startPosition?.row ?? 0;\n const endRow = anyNode.endPosition?.row ?? startRow;\n return { startLine: startRow + 1, endLine: endRow + 1 };\n}\n\n/**\n * Count physical and logical lines of code in a raw source string.\n *\n * - **Physical LOC**: number of newline-separated lines, matching how\n * most IDEs report file length.\n * - **Logical LOC**: number of lines that contain at least one\n * non-whitespace character.\n *\n * Comment detection is intentionally NOT done here; comment stripping\n * requires language-aware parsing and the caller can derive a comment\n * ratio from the AST node list if needed.\n *\n * @param source Raw source text.\n * @returns An object with `physicalLoc` and `logicalLoc`.\n */\nfunction countLines(source: string): { physicalLoc: number; logicalLoc: number } {\n if (source.length === 0) return { physicalLoc: 0, logicalLoc: 0 };\n const lines = source.split(/\\r?\\n/);\n let logical = 0;\n for (const line of lines) {\n if (line.trim().length > 0) logical += 1;\n }\n return { physicalLoc: lines.length, logicalLoc: logical };\n}\n", "/**\n * Deterministic cyclomatic complexity walker.\n *\n * Given a tree-sitter subtree rooted at a function node, this module walks\n * the tree and returns the McCabe cyclomatic complexity number. The\n * algorithm is the standard \"1 + (branching nodes + short-circuit operators)\"\n * formulation:\n *\n * CC = 1\n * + count of branching-statement nodes (if, while, for, case, catch, ...)\n * + count of short-circuit operators (&&, ||, ??, `and`, `or`)\n * + count of ternary expressions (counted as branching nodes)\n *\n * The baseline of 1 represents the straight-line path through the function.\n * Every additional branching point multiplies the set of reachable paths.\n *\n * The walker is deliberately language-agnostic: it consults the\n * {@link LanguageConfig} passed in to decide which node types to count.\n * Nested functions inside the subtree are **skipped** \u2014 each function's\n * complexity is reported independently by {@link TreeSitterEngine}.\n *\n * @module ast/cyclomatic\n */\n\nimport type { LanguageConfig } from \"./language-config.js\";\n\n/**\n * Minimal structural contract of a tree-sitter node. We intentionally\n * avoid importing `web-tree-sitter` types here so this module stays\n * unit-testable with a hand-rolled mock tree.\n */\nexport interface AstNode {\n /** Node type name from the grammar (e.g. `\"if_statement\"`). */\n readonly type: string;\n /** Raw source text for operator detection. May be large \u2014 do not log. */\n readonly text: string;\n /** Zero-based child count. */\n readonly childCount: number;\n /** Retrieve a child by index. Returns `null` if out of range. */\n child(index: number): AstNode | null;\n}\n\n/**\n * Compute the cyclomatic complexity of a function subtree.\n *\n * @param root Node rooted at the function (method, arrow, lambda, ...).\n * @param languageConfig Language classification tables for node types.\n * @returns The McCabe cyclomatic complexity (always \u2265 1).\n */\nexport function computeCyclomaticComplexity(root: AstNode, languageConfig: LanguageConfig): number {\n let complexity = 1;\n walk(root, languageConfig, true, (node) => {\n if (languageConfig.branchingNodeTypes.has(node.type)) {\n complexity += 1;\n return;\n }\n // Boolean / short-circuit operators are usually represented as\n // \"binary_expression\" nodes with an operator token child. To avoid\n // coupling to a specific grammar's node shape, we inspect the raw\n // text of the node's direct operator child.\n if (isBooleanExpression(node, languageConfig)) {\n complexity += 1;\n return;\n }\n });\n return complexity;\n}\n\n/**\n * Depth-first walk that skips any nested function subtree so that its\n * complexity is not attributed to the enclosing function.\n *\n * @param node Current node being visited.\n * @param languageConfig Language tables used to detect nested functions.\n * @param isRoot `true` for the starting node (we do not skip it).\n * @param visit Callback invoked for every non-function descendant.\n */\nfunction walk(\n node: AstNode,\n languageConfig: LanguageConfig,\n isRoot: boolean,\n visit: (n: AstNode) => void,\n): void {\n if (!isRoot && languageConfig.functionNodeTypes.has(node.type)) {\n // Nested function \u2014 stop the walk here. Its complexity is reported\n // separately when the engine iterates the top-level function list.\n return;\n }\n visit(node);\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (child) walk(child, languageConfig, false, visit);\n }\n}\n\n/**\n * Return `true` when `node` is a boolean / short-circuit expression that\n * should add one to the cyclomatic complexity. We inspect the node's\n * immediate children for an operator token whose text matches one of the\n * language's short-circuit operators.\n *\n * This is a heuristic \u2014 grammars differ in how they represent operators\n * \u2014 but it is stable enough for the five supported languages because:\n *\n * - JavaScript / TypeScript / Java: binary expression with `\"&&\"` or `\"||\"` token child.\n * - Python: `boolean_operator` node with `\"and\"` / `\"or\"` token child.\n * - C#: binary expression with `\"&&\"`, `\"||\"`, or `\"??\"` token child.\n *\n * @param node Candidate node.\n * @param languageConfig Tables with the language's boolean operator set.\n * @returns `true` when the node is a counted boolean expression.\n */\nfunction isBooleanExpression(node: AstNode, languageConfig: LanguageConfig): boolean {\n // Common type names across supported grammars. We check the type first\n // to avoid scanning text for every node in the tree.\n if (\n node.type !== \"binary_expression\" &&\n node.type !== \"boolean_operator\" &&\n node.type !== \"logical_expression\"\n ) {\n return false;\n }\n for (let i = 0; i < node.childCount; i++) {\n const child = node.child(i);\n if (!child) continue;\n if (languageConfig.booleanOperators.includes(child.text)) {\n return true;\n }\n }\n return false;\n}\n", "/**\n * Per-language tree-sitter node classification tables.\n *\n * Every language grammar exposes a different set of node type names. To\n * keep the AST engine language-agnostic we encode, for each supported\n * language, three sets:\n *\n * - `functionNodeTypes` \u2014 nodes that represent a function/method/lambda.\n * These are the units we report metrics for.\n * - `branchingNodeTypes` \u2014 nodes that add one independent path through\n * the function. Used to compute cyclomatic\n * complexity by counting occurrences.\n * - `nameField` \u2014 the tree-sitter field name that holds the\n * function's identifier, used to extract the\n * function name for reporting.\n *\n * We also define which WASM grammar file to load per language. The paths\n * are resolved at runtime against the `tree-sitter-wasms` package, but\n * can be overridden via the engine constructor if you want to ship your\n * own grammars.\n *\n * @module ast/language-config\n */\n\n/**\n * Languages currently supported by the AST engine. This is the same\n * `enum` that appears in the `analyze_file_ast` tool schema \u2014 keep them\n * in sync when adding a new language.\n */\nexport type SupportedLanguage = \"csharp\" | \"javascript\" | \"typescript\" | \"python\" | \"java\";\n\n/**\n * Per-language classification record. Immutable by convention.\n */\nexport interface LanguageConfig {\n /** Canonical language identifier (stable across releases). */\n readonly id: SupportedLanguage;\n /** WASM grammar filename inside `tree-sitter-wasms/out/`. */\n readonly wasmName: string;\n /** File extensions that should map to this language. */\n readonly extensions: ReadonlyArray<string>;\n /** Tree-sitter node types that represent callable units. */\n readonly functionNodeTypes: ReadonlySet<string>;\n /** Tree-sitter node types that add +1 to cyclomatic complexity. */\n readonly branchingNodeTypes: ReadonlySet<string>;\n /**\n * Boolean / short-circuit operator node types. These are counted only\n * when the node is an `\"&&\"`, `\"||\"`, `\"??\"` (etc.) operator, so the\n * walker inspects the operator text on top of the node type.\n */\n readonly booleanOperators: ReadonlyArray<string>;\n /**\n * Child-field names we try in order to extract the function name. The\n * walker reads the first non-empty match.\n */\n readonly nameFieldCandidates: ReadonlyArray<string>;\n}\n\n// -----------------------------------------------------------------------------\n// C#\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-c-sharp\nconst CSHARP: LanguageConfig = {\n id: \"csharp\",\n wasmName: \"tree-sitter-c_sharp.wasm\",\n extensions: [\".cs\"],\n functionNodeTypes: new Set([\n \"method_declaration\",\n \"local_function_statement\",\n \"lambda_expression\",\n \"anonymous_method_expression\",\n \"constructor_declaration\",\n \"destructor_declaration\",\n \"operator_declaration\",\n \"conversion_operator_declaration\",\n \"accessor_declaration\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"else_clause\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"for_each_statement\",\n \"case_switch_label\",\n \"case_pattern_switch_label\",\n \"switch_expression_arm\",\n \"catch_clause\",\n \"conditional_expression\",\n \"conditional_access_expression\",\n \"when_clause\",\n ]),\n booleanOperators: [\"&&\", \"||\", \"??\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// JavaScript\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-javascript\nconst JAVASCRIPT: LanguageConfig = {\n id: \"javascript\",\n wasmName: \"tree-sitter-javascript.wasm\",\n extensions: [\".js\", \".jsx\", \".mjs\", \".cjs\"],\n functionNodeTypes: new Set([\n \"function_declaration\",\n \"function_expression\",\n \"arrow_function\",\n \"method_definition\",\n \"generator_function\",\n \"generator_function_declaration\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"else_clause\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"for_in_statement\",\n \"for_of_statement\",\n \"switch_case\",\n \"catch_clause\",\n \"ternary_expression\",\n ]),\n booleanOperators: [\"&&\", \"||\", \"??\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// TypeScript\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-typescript\n// The TypeScript grammar inherits most node types from JavaScript, so we\n// extend the JS tables rather than re-declaring them from scratch.\nconst TYPESCRIPT: LanguageConfig = {\n id: \"typescript\",\n wasmName: \"tree-sitter-typescript.wasm\",\n extensions: [\".ts\", \".tsx\", \".mts\", \".cts\"],\n functionNodeTypes: new Set([\n ...JAVASCRIPT.functionNodeTypes,\n \"function_signature\",\n \"method_signature\",\n \"abstract_method_signature\",\n ]),\n branchingNodeTypes: new Set([...JAVASCRIPT.branchingNodeTypes]),\n booleanOperators: [...JAVASCRIPT.booleanOperators],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// Python\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-python\nconst PYTHON: LanguageConfig = {\n id: \"python\",\n wasmName: \"tree-sitter-python.wasm\",\n extensions: [\".py\", \".pyi\"],\n functionNodeTypes: new Set([\"function_definition\", \"lambda\"]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"elif_clause\",\n \"else_clause\",\n \"while_statement\",\n \"for_statement\",\n \"try_statement\",\n \"except_clause\",\n \"conditional_expression\",\n \"match_statement\",\n \"case_clause\",\n ]),\n booleanOperators: [\"and\", \"or\"],\n nameFieldCandidates: [\"name\"],\n};\n\n// -----------------------------------------------------------------------------\n// Java\n// -----------------------------------------------------------------------------\n// Grammar: https://github.com/tree-sitter/tree-sitter-java\nconst JAVA: LanguageConfig = {\n id: \"java\",\n wasmName: \"tree-sitter-java.wasm\",\n extensions: [\".java\"],\n functionNodeTypes: new Set([\n \"method_declaration\",\n \"constructor_declaration\",\n \"lambda_expression\",\n ]),\n branchingNodeTypes: new Set([\n \"if_statement\",\n \"while_statement\",\n \"do_statement\",\n \"for_statement\",\n \"enhanced_for_statement\",\n \"switch_label\",\n \"switch_rule\",\n \"catch_clause\",\n \"ternary_expression\",\n ]),\n booleanOperators: [\"&&\", \"||\"],\n nameFieldCandidates: [\"name\"],\n};\n\n/**\n * Complete language table. Look up by {@link SupportedLanguage} identifier.\n */\nexport const LANGUAGE_TABLE: Readonly<Record<SupportedLanguage, LanguageConfig>> = {\n csharp: CSHARP,\n javascript: JAVASCRIPT,\n typescript: TYPESCRIPT,\n python: PYTHON,\n java: JAVA,\n};\n\n/**\n * Infer a {@link SupportedLanguage} from a file path by matching its\n * extension. Returns `null` when no known language matches. Useful when\n * the caller does not already know the language and wants the engine to\n * pick one automatically.\n *\n * @param filePath File path (absolute or relative).\n * @returns The detected language or `null`.\n */\nexport function detectLanguageFromPath(filePath: string): SupportedLanguage | null {\n const lower = filePath.toLowerCase();\n for (const config of Object.values(LANGUAGE_TABLE)) {\n for (const ext of config.extensions) {\n if (lower.endsWith(ext)) return config.id;\n }\n }\n return null;\n}\n", "/**\n * Deterministic configuration loader for the claude-crap MCP server.\n *\n * Every tunable knob is read from environment variables that are injected\n * by `.mcp.json` at server startup. Those variables are themselves derived\n * from the `CLAUDE_PLUGIN_OPTION_*` values defined in the plugin manifest,\n * which means the configuration chain is:\n *\n * user settings \u2192 plugin.json \"options\" \u2192 .mcp.json \"env\" \u2192 this file\n *\n * If any environment variable is missing or empty, a safe default is used,\n * but the loader NEVER invents stochastic values. This module is the\n * single source of truth for runtime configuration.\n *\n * @module config\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { readlinkSync } from \"node:fs\";\n\n/**\n * Maintainability rating letter grades used throughout claude-crap.\n *\n * The ordering is strict: A is best, E is worst. Callers that need to\n * compare two ratings should use {@link ratingToRank} from `metrics/tdr.ts`\n * rather than comparing the letters directly.\n */\nexport type MaintainabilityRating = \"A\" | \"B\" | \"C\" | \"D\" | \"E\";\n\n/**\n * Fully resolved configuration object consumed by every subsystem of the\n * MCP server. Fields are `readonly` so that downstream code cannot mutate\n * configuration at runtime \u2014 any change must go through a server restart.\n */\nexport interface CrapConfig {\n /** Absolute path to the user's workspace. Resolved via {@link discoverWorkspaceRoot}. */\n readonly pluginRoot: string;\n /** Directory (relative to the workspace) where consolidated SARIF reports are written. */\n readonly sarifOutputDir: string;\n /** Hard block threshold for the CRAP index. Functions above this fail the Stop quality gate. */\n readonly crapThreshold: number;\n /** Maximum cyclomatic complexity allowed per function before warnings fire. */\n readonly cyclomaticMax: number;\n /** Highest (worst) maintainability rating the project is allowed to hold. */\n readonly tdrMaxRating: MaintainabilityRating;\n /** Assumed development cost per line of code, in minutes. Used as the TDR denominator. */\n readonly minutesPerLoc: number;\n /** Local TCP port the Vue.js dashboard will bind to. */\n readonly dashboardPort: number;\n}\n\n/**\n * Detects an unexpanded `.mcp.json` variable template such as\n * `${CLAUDE_PROJECT_DIR}`. Claude Code only expands `${CLAUDE_PLUGIN_ROOT}`\n * inside `.mcp.json`; every other `${VAR}` is passed through verbatim and\n * must NOT be treated as a real filesystem path.\n */\nfunction isLiteralVarTemplate(value: string | undefined): boolean {\n if (value === undefined) return false;\n return /^\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}$/.test(value.trim());\n}\n\n/**\n * Normalize an environment variable that is expected to contain a path.\n * Returns `undefined` if the value is missing, empty, or an unexpanded\n * `${...}` template. Any non-empty concrete string is returned as-is.\n */\nfunction sanitizeEnvPath(value: string | undefined): string | undefined {\n if (value === undefined || value === \"\") return undefined;\n if (isLiteralVarTemplate(value)) return undefined;\n return value;\n}\n\n/**\n * Read the current working directory of the parent process. Claude Code\n * spawns MCP servers with its own cwd set to the user's workspace, so the\n * parent's cwd is the most reliable fallback when `CLAUDE_PROJECT_DIR` is\n * not inherited (e.g. because Claude Code only exports it for hooks).\n *\n * Returns `undefined` on any platform or failure mode the probe cannot\n * handle \u2014 callers must be prepared for a missing result.\n */\nfunction readParentCwdDefault(): string | undefined {\n try {\n const ppid = process.ppid;\n if (!ppid || ppid === 0) return undefined;\n\n if (process.platform === \"linux\") {\n // /proc/<pid>/cwd is a symlink to the process's cwd.\n return readlinkSync(`/proc/${ppid}/cwd`);\n }\n\n if (process.platform === \"darwin\") {\n // `lsof -a -p <pid> -d cwd -F n` emits a single line starting with\n // `n<path>` for the cwd file descriptor. `-F` keeps the output\n // machine-readable.\n const output = execFileSync(\n \"lsof\",\n [\"-a\", \"-p\", String(ppid), \"-d\", \"cwd\", \"-F\", \"n\"],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 2000,\n },\n );\n const match = output.match(/^n(.+)$/m);\n return match?.[1];\n }\n\n // Windows and other platforms: no reliable no-dep probe.\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parameters accepted by {@link discoverWorkspaceRoot}. The only field is\n * an injectable `readParentCwd` implementation so that tests can pin the\n * fallback behavior without spawning `lsof` or reading `/proc`.\n */\nexport interface DiscoverWorkspaceOptions {\n readParentCwd?: () => string | undefined;\n}\n\n/**\n * Resolve the user's workspace directory. Strategy, in strict priority\n * order:\n *\n * 1. `CLAUDE_PROJECT_DIR` (sanitized \u2014 ignored if it's `${...}`)\n * 2. `CLAUDE_CRAP_PLUGIN_ROOT` (sanitized \u2014 legacy explicit override)\n * 3. Parent process cwd (Claude Code's cwd = the workspace)\n * 4. `process.cwd()` (last-resort fallback; usually wrong for\n * MCP servers because Claude Code sets\n * cwd to the plugin cache directory)\n *\n * This function NEVER returns an unexpanded `${...}` template; any source\n * that contains one is skipped as if it were unset.\n *\n * @param options Injection points for tests.\n * @returns A concrete filesystem path.\n */\nexport function discoverWorkspaceRoot(options: DiscoverWorkspaceOptions = {}): string {\n const readParentCwd = options.readParentCwd ?? readParentCwdDefault;\n\n const fromProjectDir = sanitizeEnvPath(process.env.CLAUDE_PROJECT_DIR);\n if (fromProjectDir) return fromProjectDir;\n\n const fromPluginRoot = sanitizeEnvPath(process.env.CLAUDE_CRAP_PLUGIN_ROOT);\n if (fromPluginRoot) return fromPluginRoot;\n\n const fromParent = sanitizeEnvPath(readParentCwd());\n if (fromParent) return fromParent;\n\n return process.cwd();\n}\n\n/**\n * Parse a numeric environment variable, falling back to `fallback` when the\n * variable is undefined or empty. Throws if the value is present but not a\n * finite number \u2014 we prefer a loud startup failure over silently using a\n * wrong threshold.\n *\n * @param name Environment variable name, used only for the error message.\n * @param raw Raw value read from `process.env`.\n * @param fallback Default value used when `raw` is undefined/empty.\n * @returns The parsed number.\n * @throws When `raw` is present but not a finite number.\n */\nfunction parseNumber(name: string, raw: string | undefined, fallback: number): number {\n if (raw === undefined || raw === \"\") return fallback;\n const value = Number(raw);\n if (!Number.isFinite(value)) {\n throw new Error(`[claude-crap] Env ${name}=\"${raw}\" is not a finite number`);\n }\n return value;\n}\n\n/**\n * Parse a maintainability rating from an environment variable. Accepts any\n * casing (`a`, `A`, ` a ` all become `\"A\"`). Throws on invalid letters so\n * the server refuses to start rather than running with an unknown policy.\n *\n * @param raw Raw value read from `process.env`.\n * @param fallback Default rating used when `raw` is undefined.\n * @returns A validated {@link MaintainabilityRating}.\n * @throws When `raw` is a non-empty string that is not A..E.\n */\nfunction parseRating(raw: string | undefined, fallback: MaintainabilityRating): MaintainabilityRating {\n if (!raw) return fallback;\n const normalized = raw.trim().toUpperCase();\n if (![\"A\", \"B\", \"C\", \"D\", \"E\"].includes(normalized)) {\n throw new Error(`[claude-crap] TDR_MAX_RATING=\"${raw}\" must be one of A, B, C, D, E`);\n }\n return normalized as MaintainabilityRating;\n}\n\n/**\n * Build the complete {@link CrapConfig} from the current process environment.\n *\n * This should be called exactly once at server startup. Subsequent callers\n * that need configuration should accept a `CrapConfig` parameter instead\n * of re-reading from `process.env`, so that tests can inject custom values.\n *\n * @returns A fully validated, immutable configuration object.\n * @throws When any environment variable is present but malformed.\n */\nexport function loadConfig(): CrapConfig {\n return {\n pluginRoot: discoverWorkspaceRoot(),\n sarifOutputDir: process.env.CLAUDE_CRAP_SARIF_OUTPUT_DIR ?? \".claude-crap/reports\",\n crapThreshold: parseNumber(\"CLAUDE_CRAP_CRAP_THRESHOLD\", process.env.CLAUDE_CRAP_CRAP_THRESHOLD, 30),\n cyclomaticMax: parseNumber(\"CLAUDE_CRAP_CYCLOMATIC_MAX\", process.env.CLAUDE_CRAP_CYCLOMATIC_MAX, 15),\n tdrMaxRating: parseRating(process.env.CLAUDE_CRAP_TDR_MAX_RATING, \"C\"),\n minutesPerLoc: parseNumber(\"CLAUDE_CRAP_MINUTES_PER_LOC\", process.env.CLAUDE_CRAP_MINUTES_PER_LOC, 30),\n dashboardPort: parseNumber(\"CLAUDE_CRAP_DASHBOARD_PORT\", process.env.CLAUDE_CRAP_DASHBOARD_PORT, 5117),\n };\n}\n", "/**\n * Local Vue.js dashboard for claude-crap \u2014 Fastify HTTP server.\n *\n * The dashboard runs in the same Node.js process as the MCP server,\n * but on a separate TCP port (default 5117). It exposes:\n *\n * GET / \u2192 static index.html (Vue 3 SPA from CDN)\n * GET /api/score \u2192 live ProjectScore JSON from the score engine\n * GET /api/sarif \u2192 consolidated SARIF 2.1.0 document\n * GET /api/health \u2192 simple {status:\"ok\"} liveness probe\n *\n * The server binds to `127.0.0.1` only \u2014 never to `0.0.0.0` \u2014 so the\n * dashboard cannot be reached from outside the developer's machine.\n *\n * If the configured port is already in use (or the bind otherwise\n * fails), `startDashboard()` rejects gracefully and the caller falls\n * back to \"no dashboard\". The MCP server will keep running.\n *\n * IMPORTANT: this module never writes to stdout. The MCP stdio\n * transport reserves stdout for JSON-RPC framing, so all logs and\n * errors here go through the same pino-on-stderr instance the rest of\n * the server uses.\n *\n * @module dashboard/server\n */\n\nimport { promises as fs, existsSync, readFileSync, writeFileSync, unlinkSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport Fastify, { type FastifyInstance } from \"fastify\";\nimport fastifyStatic from \"@fastify/static\";\nimport type { Logger } from \"pino\";\n\nimport type { CrapConfig } from \"../config.js\";\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\nimport {\n computeProjectScore,\n type ProjectScore,\n type WorkspaceStats,\n} from \"../metrics/score.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport type { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport { detectLanguageFromPath } from \"../ast/language-config.js\";\nimport { buildFileDetail } from \"./file-detail.js\";\n\n/**\n * Callback used by the dashboard to refresh workspace LOC stats on\n * every score request. The MCP server provides this so the dashboard\n * does not have to know how to walk the disk itself.\n */\nexport type WorkspaceStatsProvider = () => Promise<WorkspaceStats>;\n\n/**\n * Inputs accepted by {@link startDashboard}.\n */\nexport interface StartDashboardOptions {\n /** Fully resolved server configuration. */\n readonly config: CrapConfig;\n /** Live SARIF store the dashboard reads findings from. */\n readonly sarifStore: SarifStore;\n /** Function that returns up-to-date LOC + file count for the workspace. */\n readonly workspaceStatsProvider: WorkspaceStatsProvider;\n /** Pino logger from the MCP server (writes to stderr). */\n readonly logger: Logger;\n /** Tree-sitter engine for the /api/complexity endpoint. */\n readonly astEngine?: TreeSitterEngine;\n /** User-defined exclusion patterns from .claude-crap.json. */\n readonly exclude?: ReadonlyArray<string>;\n}\n\n/**\n * Handle returned by {@link startDashboard}. Use `url` to build the\n * link the user clicks; call `close()` during shutdown.\n */\nexport interface DashboardHandle {\n readonly url: string;\n close(): Promise<void>;\n}\n\n/**\n * Boot the Fastify dashboard server. Resolves with a {@link DashboardHandle}\n * once the server is listening, or rejects when the bind fails (caller\n * should treat that as a non-fatal degradation).\n *\n * @param options Configuration, store, and provider callback.\n */\nexport async function startDashboard(options: StartDashboardOptions): Promise<DashboardHandle> {\n const { config, sarifStore, workspaceStatsProvider, logger } = options;\n\n // Resolve the public/ directory. After `npm run build` the compiled\n // server lives in `dist/dashboard/server.js`, but we keep the static\n // SPA assets in `src/dashboard/public/` so we don't need a postbuild\n // copy step. We probe both candidate locations in priority order.\n const publicRoot = await resolvePublicRoot(logger);\n\n const fastify: FastifyInstance = Fastify({\n logger: false, // we route everything through pino-on-stderr ourselves\n disableRequestLogging: true,\n });\n\n await fastify.register(fastifyStatic, {\n root: publicRoot,\n prefix: \"/\",\n });\n\n // ------------------------------------------------------------------\n // /api/health \u2014 liveness probe\n // ------------------------------------------------------------------\n fastify.get(\"/api/health\", async () => ({ status: \"ok\", server: \"claude-crap\", version: \"0.4.0\" }));\n\n // ------------------------------------------------------------------\n // /api/score \u2014 live project score\n // ------------------------------------------------------------------\n fastify.get(\"/api/score\", async () => {\n const stats = await workspaceStatsProvider();\n const score = await buildScore(config, sarifStore, stats, urlOf(fastify, config));\n return score;\n });\n\n // ------------------------------------------------------------------\n // /api/sarif \u2014 consolidated SARIF 2.1.0 document\n // ------------------------------------------------------------------\n fastify.get(\"/api/sarif\", async () => sarifStore.toSarifDocument());\n\n // ------------------------------------------------------------------\n // /api/complexity \u2014 top complex functions across the workspace\n // ------------------------------------------------------------------\n fastify.get(\"/api/complexity\", async () => {\n if (!options.astEngine) {\n return { threshold: config.cyclomaticMax, totalFunctions: 0, violationCount: 0, topFunctions: [] };\n }\n return buildComplexityReport(config, options.astEngine, logger, options.exclude);\n });\n\n // ------------------------------------------------------------------\n // /api/file-detail \u2014 per-file source, metrics, and findings\n // ------------------------------------------------------------------\n fastify.get(\"/api/file-detail\", async (request, reply) => {\n const { path: filePath } = request.query as { path?: string };\n if (!filePath) {\n return reply.status(400).send({ error: \"Missing required query parameter: path\" });\n }\n try {\n const detail = await buildFileDetail({\n relativePath: filePath,\n workspaceRoot: config.pluginRoot,\n astEngine: options.astEngine,\n sarifStore,\n cyclomaticMax: config.cyclomaticMax,\n });\n return detail;\n } catch (err) {\n const msg = (err as Error).message;\n if (msg.includes(\"ENOENT\") || msg.includes(\"not found\")) {\n return reply.status(404).send({ error: `File not found: ${filePath}` });\n }\n if (msg.includes(\"escapes the workspace\")) {\n return reply.status(400).send({ error: msg });\n }\n logger.error({ err: msg, filePath }, \"file-detail endpoint error\");\n return reply.status(500).send({ error: \"Internal server error\" });\n }\n });\n\n // ------------------------------------------------------------------\n // / \u2014 explicit SPA fallback for index.html\n // ------------------------------------------------------------------\n // @fastify/static sometimes doesn't serve index.html on GET / when\n // API routes are registered on the same prefix. Explicit fallback\n // ensures the dashboard always loads.\n fastify.get(\"/\", async (_request, reply) => {\n return reply.sendFile(\"index.html\");\n });\n\n // Kill any stale dashboard from a previous session so we always\n // bind to the configured port. This mirrors claude-mem's PID file\n // pattern: write a PID file when alive, check + kill on next boot.\n const pidFilePath = resolvePidFilePath(config);\n await killStaleDashboard(pidFilePath, config.dashboardPort, logger);\n\n await fastify.listen({ port: config.dashboardPort, host: \"127.0.0.1\" });\n\n const url = `http://127.0.0.1:${config.dashboardPort}`;\n logger.info({ url, publicRoot }, \"claude-crap dashboard listening\");\n\n // Write PID file so the next session can find and kill us.\n writePidFile(pidFilePath, config.dashboardPort);\n\n return {\n url,\n async close() {\n removePidFile(pidFilePath);\n await fastify.close();\n },\n };\n}\n\n/**\n * Probe the candidate public/ directories in priority order and return\n * the first one that contains an `index.html`. Throws when none of the\n * candidates exist \u2014 that points at a packaging mistake the developer\n * should fix immediately.\n *\n * @param logger Pino instance for diagnostics.\n */\nasync function resolvePublicRoot(logger: Logger): Promise<string> {\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // 0. Bundled layout: plugin/bundle/mcp-server.mjs \u2192 ./dashboard/public\n resolve(here, \"dashboard\", \"public\"),\n // 1. Compiled layout: dist/dashboard/server.js \u2192 ./public next to it\n // (only present if a build step copies the assets \u2014 not used\n // today, but accepted so a future copy step does not break us).\n resolve(here, \"public\"),\n // 2. Source-relative layout: dist/dashboard/server.js \u2192 ../../src/dashboard/public\n // This is the default \u2014 no copy step required because we resolve\n // upward from `dist/` into `src/` at runtime.\n resolve(here, \"..\", \"..\", \"src\", \"dashboard\", \"public\"),\n ];\n for (const candidate of candidates) {\n try {\n await fs.access(resolve(candidate, \"index.html\"));\n return candidate;\n } catch {\n // probe next\n }\n }\n logger.error({ candidates }, \"dashboard public/ directory not found\");\n throw new Error(\n `[claude-crap] dashboard: index.html not found in any of ${candidates.join(\", \")}`,\n );\n}\n\n/**\n * Resolve the canonical dashboard URL using the live Fastify address\n * info. Falls back to the configured port when the address info is\n * not yet available (e.g. on the very first request during startup).\n */\nfunction urlOf(fastify: FastifyInstance, config: CrapConfig): string {\n const addresses = fastify.addresses?.() ?? [];\n const first = addresses[0];\n if (first) {\n const host = first.address === \"::\" || first.address === \"0.0.0.0\" ? \"127.0.0.1\" : first.address;\n return `http://${host}:${first.port}`;\n }\n return `http://127.0.0.1:${config.dashboardPort}`;\n}\n\n// ------------------------------------------------------------------\n// PID file management \u2014 mirrors claude-mem's worker.pid pattern\n// ------------------------------------------------------------------\n\n/**\n * Shape of the PID file written by the dashboard process.\n */\ninterface DashboardPidFile {\n pid: number;\n port: number;\n startedAt: string;\n}\n\n/**\n * Resolve the path to the PID file. Stored under\n * `.claude-crap/dashboard.pid` in the workspace so it survives\n * across sessions but is gitignored with the rest of `.claude-crap/`.\n */\nfunction resolvePidFilePath(config: CrapConfig): string {\n return join(config.pluginRoot, \".claude-crap\", \"dashboard.pid\");\n}\n\n/**\n * Write the PID file atomically after the dashboard has started.\n */\nfunction writePidFile(path: string, port: number): void {\n const data: DashboardPidFile = {\n pid: process.pid,\n port,\n startedAt: new Date().toISOString(),\n };\n try {\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\");\n } catch {\n /* best effort \u2014 dashboard still works without a PID file */\n }\n}\n\n/**\n * Remove the PID file during graceful shutdown.\n */\nfunction removePidFile(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n /* already gone or never written */\n }\n}\n\n/**\n * Check whether a process is alive using the signal-0 probe.\n * Returns `true` when the process exists and is reachable.\n */\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Read the PID file, kill any stale dashboard process, and free the\n * port so the current session can bind to it. This is the key\n * difference from the port-fallback approach: instead of drifting to\n * 5118, 5119, etc., we reclaim the configured port every time.\n *\n * @param pidFilePath Absolute path to `dashboard.pid`.\n * @param port The configured dashboard port.\n * @param logger Pino logger for diagnostics.\n */\nasync function killStaleDashboard(\n pidFilePath: string,\n port: number,\n logger: Logger,\n): Promise<void> {\n if (!existsSync(pidFilePath)) return;\n\n let stale: DashboardPidFile;\n try {\n stale = JSON.parse(readFileSync(pidFilePath, \"utf8\"));\n } catch {\n // Corrupted PID file \u2014 remove it and move on.\n removePidFile(pidFilePath);\n return;\n }\n\n if (!isPidAlive(stale.pid)) {\n logger.info({ stalePid: stale.pid }, \"stale dashboard PID file found (process dead), removing\");\n removePidFile(pidFilePath);\n return;\n }\n\n // Process is alive \u2014 kill it so we can reclaim the port.\n logger.info(\n { stalePid: stale.pid, port: stale.port, startedAt: stale.startedAt },\n \"killing stale dashboard process from previous session\",\n );\n\n try {\n process.kill(stale.pid, \"SIGTERM\");\n } catch {\n // Permission denied or already gone \u2014 remove PID file either way.\n removePidFile(pidFilePath);\n return;\n }\n\n // Wait up to 3 seconds for the process to exit.\n for (let i = 0; i < 30; i++) {\n if (!isPidAlive(stale.pid)) break;\n await new Promise((r) => setTimeout(r, 100));\n }\n\n // If still alive after 3s, escalate to SIGKILL.\n if (isPidAlive(stale.pid)) {\n try {\n process.kill(stale.pid, \"SIGKILL\");\n } catch {\n /* best effort */\n }\n await new Promise((r) => setTimeout(r, 200));\n }\n\n removePidFile(pidFilePath);\n\n // Give the OS a moment to release the TCP port after the process dies.\n await new Promise((r) => setTimeout(r, 300));\n}\n\n// \u2500\u2500 Complexity report builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Entry in the complexity report's top-functions list. */\ninterface ComplexityEntry {\n filePath: string;\n name: string;\n cyclomaticComplexity: number;\n startLine: number;\n endLine: number;\n lineCount: number;\n}\n\n/** Shape returned by GET /api/complexity. */\ninterface ComplexityReport {\n threshold: number;\n totalFunctions: number;\n violationCount: number;\n topFunctions: ComplexityEntry[];\n}\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n\n/**\n * Walk the workspace and collect per-function complexity metrics,\n * returning the top 20 most complex functions. This runs on demand\n * when the dashboard requests /api/complexity.\n */\nasync function buildComplexityReport(\n config: CrapConfig,\n engine: TreeSitterEngine,\n logger: Logger,\n exclude?: ReadonlyArray<string>,\n): Promise<ComplexityReport> {\n const threshold = config.cyclomaticMax;\n const filter = createExclusionFilter(exclude);\n const allFunctions: ComplexityEntry[] = [];\n let totalFunctions = 0;\n\n async function walk(dir: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n const language = detectLanguageFromPath(entry.name);\n if (!language) continue;\n try {\n const metrics = await engine.analyzeFile({ filePath: full, language });\n for (const fn of metrics.functions) {\n totalFunctions += 1;\n allFunctions.push({\n filePath: full.startsWith(config.pluginRoot)\n ? full.substring(config.pluginRoot.length + 1)\n : full,\n name: fn.name,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n startLine: fn.startLine,\n endLine: fn.endLine,\n lineCount: fn.lineCount,\n });\n }\n } catch (err) {\n logger.warn(\n { filePath: full, err: (err as Error).message },\n \"complexity-report: failed to analyze file\",\n );\n }\n }\n }\n\n await walk(config.pluginRoot);\n\n // Sort by complexity descending and take top 20\n allFunctions.sort((a, b) => b.cyclomaticComplexity - a.cyclomaticComplexity);\n const topFunctions = allFunctions.slice(0, 20);\n const violationCount = allFunctions.filter(\n (f) => f.cyclomaticComplexity > threshold,\n ).length;\n\n return { threshold, totalFunctions, violationCount, topFunctions };\n}\n\n/**\n * Wrap {@link computeProjectScore} so the dashboard endpoint can call\n * it with the live store and provide consistent location metadata.\n */\nasync function buildScore(\n config: CrapConfig,\n sarifStore: SarifStore,\n workspace: WorkspaceStats,\n dashboardUrl: string | null,\n): Promise<ProjectScore> {\n return computeProjectScore({\n workspaceRoot: config.pluginRoot,\n minutesPerLoc: config.minutesPerLoc,\n tdrMaxRating: config.tdrMaxRating,\n workspace,\n sarifStore,\n dashboardUrl,\n sarifReportPath: sarifStore.consolidatedReportPath,\n });\n}\n", "/**\n * Centralized file and directory exclusion system.\n *\n * Every filesystem walker in the codebase (workspace-walker,\n * complexity-scanner, dashboard file-detail) imports from this module\n * instead of maintaining its own `SKIP_DIRS` constant. This\n * guarantees all subsystems agree on what to exclude.\n *\n * User-configurable exclusions from `.claude-crap.json` are layered\n * on top of the defaults via {@link createExclusionFilter}.\n *\n * @module shared/exclusions\n */\n\nimport picomatch from \"picomatch\";\n\n// \u2500\u2500 Default exclusions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Directories excluded by name at any depth. A walker that encounters\n * a directory entry whose name is in this set should skip the entire\n * subtree. The set covers package managers, VCS, build outputs for\n * all major frameworks, language-specific caches, and plugin state.\n */\nexport const DEFAULT_SKIP_DIRS: ReadonlySet<string> = new Set([\n // Package managers / vendored deps\n \"node_modules\",\n \"vendor\",\n\n // Version control\n \".git\",\n\n // Build outputs (general)\n \"dist\",\n \"build\",\n \"bundle\",\n \"out\",\n \"target\",\n \"coverage\",\n\n // Framework build outputs\n \".next\", // Next.js\n \".nuxt\", // Nuxt 2\n \".output\", // Nuxt 3\n \".vercel\", // Vercel\n \".svelte-kit\", // SvelteKit\n \".astro\", // Astro\n \".angular\", // Angular\n \".turbo\", // Turborepo\n \".parcel-cache\",// Parcel\n \".expo\", // Expo / React Native\n\n // Language-specific caches\n \".venv\",\n \"venv\",\n \"__pycache__\",\n \".cache\",\n \".dart_tool\", // Dart / Flutter\n \".gradle\", // Gradle\n\n // IDE state\n \".idea\",\n\n // Plugin infrastructure (excluded so the plugin's own hook/bundle\n // files don't pollute workspace metrics when developing the plugin\n // itself, and don't appear in scans of any project)\n \"plugin\",\n \"hooks\",\n \"skills\",\n\n // Plugin state\n \".claude-crap\",\n \".claude-plugin\",\n \".claude-sonar\",\n \".codesight\",\n]);\n\n/**\n * Filename-level glob patterns that match generated or minified files\n * regardless of which directory they live in. Matched against the\n * bare filename (not the full path).\n */\nexport const DEFAULT_SKIP_PATTERNS: ReadonlyArray<string> = [\n \"*.min.js\",\n \"*.min.css\",\n \"*.min.mjs\",\n \"*.min.cjs\",\n \"*.bundle.js\",\n \"*.chunk.js\",\n];\n\n// \u2500\u2500 Exclusion filter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Stateless, pre-compiled filter that every filesystem walker uses\n * to decide whether to skip a directory or file.\n */\nexport interface ExclusionFilter {\n /** Returns `true` when the directory should be skipped entirely. */\n shouldSkipDir(dirName: string): boolean;\n /** Returns `true` when the file should be excluded from analysis. */\n shouldSkipFile(relativePath: string, fileName: string): boolean;\n}\n\n/**\n * Create an {@link ExclusionFilter} that combines the built-in\n * defaults with optional user-defined patterns from `.claude-crap.json`.\n *\n * User patterns follow `.gitignore`-style conventions:\n * - `apps/legacy/` \u2192 trailing `/` means directory exclusion\n * - `*.proto.ts` \u2192 glob matched against workspace-relative path\n * - `src/generated/**` \u2192 path-prefix glob\n *\n * Picomatch matchers are compiled once at construction, so per-file\n * checks are O(1) set lookups plus O(n) matcher calls where n is\n * the small number of user patterns (typically < 20).\n *\n * @param userExclusions Optional patterns from `.claude-crap.json`.\n */\nexport function createExclusionFilter(\n userExclusions?: ReadonlyArray<string>,\n): ExclusionFilter {\n // Split user patterns into directory exclusions and file globs\n const extraDirs = new Set<string>();\n const fileGlobs: string[] = [];\n\n for (const pattern of userExclusions ?? []) {\n if (pattern.endsWith(\"/\")) {\n // Directory exclusion \u2014 strip trailing slash\n extraDirs.add(pattern.slice(0, -1));\n } else {\n fileGlobs.push(pattern);\n }\n }\n\n // Compile filename-level matchers once\n const defaultFileMatchers = DEFAULT_SKIP_PATTERNS.map((p) =>\n picomatch(p, { dot: true }),\n );\n const userFileMatchers = fileGlobs.map((p) =>\n picomatch(p, { dot: true }),\n );\n\n return {\n shouldSkipDir(dirName: string): boolean {\n // Hidden directories are always skipped except .claude-plugin\n if (dirName.startsWith(\".\") && dirName !== \".claude-plugin\") {\n return DEFAULT_SKIP_DIRS.has(dirName) || true;\n }\n return DEFAULT_SKIP_DIRS.has(dirName) || extraDirs.has(dirName);\n },\n\n shouldSkipFile(relativePath: string, fileName: string): boolean {\n // Check filename against default minified/bundled patterns\n for (const matcher of defaultFileMatchers) {\n if (matcher(fileName)) return true;\n }\n // Check against user-defined globs (matched on relative path)\n for (const matcher of userFileMatchers) {\n if (matcher(relativePath) || matcher(fileName)) return true;\n }\n return false;\n },\n };\n}\n", "/**\n * Technical Debt Ratio (TDR) \u2014 deterministic computation and rating.\n *\n * The Technical Debt Ratio expresses how expensive it would be to remediate\n * all known issues in a scope, relative to how much it would have cost to\n * write the code in the first place. Formally (see docs/quality-gate.md):\n *\n * TDR = remediationCost / (costPerLine \u00D7 totalLinesOfCode)\n *\n * Where the remediation cost is the sum (in minutes) of every linter /\n * scanner / mutator finding's individual estimated effort, and the per-line\n * cost is assumed to be a constant `minutesPerLoc` (industry default: 30\n * minutes per line of code, including design, writing and review).\n *\n * The resulting ratio is converted to a percentage and mapped to a letter\n * grade A..E. The thresholds are strict and non-negotiable:\n *\n * | Rating | TDR % | Meaning |\n * |--------|--------------|-------------------------------------------|\n * | A | 0..5% | Excellent \u2014 remediation cost is noise |\n * | B | >5..10% | Low risk |\n * | C | >10..20% | Moderate, watch closely |\n * | D | >20..50% | Critical, remediation plan required |\n * | E | >50% | Unmaintainable \u2014 halt feature work |\n *\n * Rating E always halts the workflow at the Stop quality gate, regardless\n * of the configured `TDR_MAX_RATING` tolerance.\n *\n * @module metrics/tdr\n */\n\nimport type { MaintainabilityRating } from \"../config.js\";\n\n/**\n * Inputs required to compute a Technical Debt Ratio over any scope\n * (project, module, or file).\n */\nexport interface TdrInput {\n /** Sum of all finding remediation estimates, in minutes. Must be \u2265 0. */\n readonly remediationMinutes: number;\n /** Total lines of code in the scope. Must be > 0 (division denominator). */\n readonly totalLinesOfCode: number;\n /** Assumed development cost per LOC, in minutes. Must be > 0. */\n readonly minutesPerLoc: number;\n}\n\n/**\n * Result of a TDR computation with both the raw ratio and the letter grade.\n */\nexport interface TdrResult {\n /** Raw ratio (remediation / development), rounded to 6 decimals. */\n readonly ratio: number;\n /** Same ratio expressed as a percentage, rounded to 4 decimals. */\n readonly percent: number;\n /** Letter grade derived from `percent` via {@link classifyTdr}. */\n readonly rating: MaintainabilityRating;\n /** Remediation input, echoed for traceability. */\n readonly remediationMinutes: number;\n /** LOC input, echoed for traceability. */\n readonly totalLinesOfCode: number;\n /** Computed `minutesPerLoc \u00D7 totalLinesOfCode`, useful for the dashboard. */\n readonly developmentCostMinutes: number;\n}\n\n/** Canonical ordering used by {@link ratingToRank}. */\nconst RATING_ORDER: ReadonlyArray<MaintainabilityRating> = [\"A\", \"B\", \"C\", \"D\", \"E\"];\n\n/**\n * Convert a letter rating to its numeric rank (A=0, E=4). Useful when\n * comparing two ratings without relying on lexical order.\n *\n * @param rating The rating letter.\n * @returns Its rank in `[0, 4]`.\n */\nexport function ratingToRank(rating: MaintainabilityRating): number {\n return RATING_ORDER.indexOf(rating);\n}\n\n/**\n * Return `true` when `actual` is strictly worse than `limit`, false otherwise.\n * Used by the Stop quality gate to decide whether to block task completion.\n *\n * @param actual Rating currently achieved by the project.\n * @param limit Maximum tolerated rating (worst allowed).\n * @returns `true` if `actual` should trigger a block.\n *\n * @example\n * ratingIsWorseThan(\"D\", \"C\") // \u2192 true\n * ratingIsWorseThan(\"B\", \"C\") // \u2192 false\n * ratingIsWorseThan(\"C\", \"C\") // \u2192 false (equal, not worse)\n */\nexport function ratingIsWorseThan(\n actual: MaintainabilityRating,\n limit: MaintainabilityRating,\n): boolean {\n return ratingToRank(actual) > ratingToRank(limit);\n}\n\n/**\n * Map a TDR percentage to its letter rating. The boundaries are inclusive\n * on the upper end (5% is still an A, 10% is still a B, etc.).\n *\n * @param percent TDR expressed as a percentage. Must be \u2265 0.\n * @returns Letter rating A..E.\n * @throws When `percent` is negative or not finite.\n */\nexport function classifyTdr(percent: number): MaintainabilityRating {\n if (!Number.isFinite(percent) || percent < 0) {\n throw new Error(`[tdr] percent is invalid: ${percent}`);\n }\n if (percent <= 5) return \"A\";\n if (percent <= 10) return \"B\";\n if (percent <= 20) return \"C\";\n if (percent <= 50) return \"D\";\n return \"E\";\n}\n\n/**\n * Compute the Technical Debt Ratio for a scope and return the full result.\n * This function is pure and deterministic.\n *\n * @param input Remediation minutes, total LOC and the cost-per-line assumption.\n * @returns A {@link TdrResult} ready to be serialized to SARIF properties.\n * @throws When any numeric input is out of range.\n *\n * @example\n * // 240 minutes of remediation across 500 LOC at 30 min/LOC\n * computeTdr({ remediationMinutes: 240, totalLinesOfCode: 500, minutesPerLoc: 30 })\n * // \u2192 { ratio: 0.016, percent: 1.6, rating: \"A\", ... }\n */\nexport function computeTdr(input: TdrInput): TdrResult {\n if (input.totalLinesOfCode <= 0) {\n throw new Error(`[tdr] totalLinesOfCode must be > 0, got ${input.totalLinesOfCode}`);\n }\n if (input.minutesPerLoc <= 0) {\n throw new Error(`[tdr] minutesPerLoc must be > 0, got ${input.minutesPerLoc}`);\n }\n if (input.remediationMinutes < 0) {\n throw new Error(`[tdr] remediationMinutes must be \u2265 0, got ${input.remediationMinutes}`);\n }\n\n const developmentCostMinutes = input.minutesPerLoc * input.totalLinesOfCode;\n const ratio = input.remediationMinutes / developmentCostMinutes;\n const percent = ratio * 100;\n const rating = classifyTdr(percent);\n\n return {\n ratio: Number(ratio.toFixed(6)),\n percent: Number(percent.toFixed(4)),\n rating,\n remediationMinutes: input.remediationMinutes,\n totalLinesOfCode: input.totalLinesOfCode,\n developmentCostMinutes,\n };\n}\n", "/**\n * Aggregate project score engine.\n *\n * Given a fully resolved configuration, the live SARIF store, and a\n * workspace LOC walker, this module produces a single immutable\n * `ProjectScore` snapshot describing the entire project's quality\n * posture across three dimensions:\n *\n * - **Maintainability** \u2014 derived from the Technical Debt Ratio (TDR)\n * using the existing `metrics/tdr.ts` engine.\n * - **Reliability** \u2014 derived from the worst non-security finding.\n * - **Security** \u2014 derived from the worst security finding.\n *\n * Each dimension produces a letter grade A..E and the `overall` field\n * collapses them by taking the worst grade. The `passes` field tells\n * the caller whether the overall grade is within the configured\n * `tdrMaxRating` tolerance \u2014 handy for the Stop quality gate and the\n * `score_project` MCP tool.\n *\n * Security vs reliability is determined by a heuristic on the `ruleId`:\n * any rule whose identifier matches a security keyword (`sec`, `sql`,\n * `xss`, `csrf`, `injection`, `crypt`, `auth`, `secret`, `password`,\n * `cve`, `vuln`) is treated as security. Everything else is reliability.\n * This is intentionally coarse: adapters that stamp a richer SARIF\n * taxonomy (e.g. `properties.tags = [\"security\"]`) could replace this\n * classifier with an exact match, but the regex is sufficient for the\n * scanners this plugin ships with.\n *\n * The score engine is pure: it does no I/O, takes a `WorkspaceStats`\n * value (which the caller produces from the bounded LOC walker), and\n * returns a brand new score object on every call. Tests can construct\n * a `SarifStore` in memory and verify the boundaries directly.\n *\n * @module metrics/score\n */\n\nimport type { MaintainabilityRating } from \"../config.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport { classifyTdr, ratingIsWorseThan } from \"./tdr.js\";\n\n/**\n * Letter rating shared by every dimension. The same A..E scale used by\n * SonarQube's reliability and security ratings, where A is best and E\n * is unmaintainable / blocker-class.\n */\nexport type SeverityRating = MaintainabilityRating;\n\n/**\n * Workspace size statistics produced by an external bounded walker.\n * The score engine does not walk the disk itself \u2014 pass these in.\n */\nexport interface WorkspaceStats {\n /** Total physical lines of code under the workspace root. */\n readonly physicalLoc: number;\n /** Number of files visited by the walker. */\n readonly fileCount: number;\n}\n\n/**\n * Per-dimension breakdown.\n */\nexport interface DimensionScore {\n readonly rating: SeverityRating;\n readonly findings: number;\n readonly errorFindings: number;\n readonly warningFindings: number;\n readonly noteFindings: number;\n}\n\n/**\n * Per-finding-level summary plus per-tool counts.\n */\nexport interface FindingsSummary {\n readonly total: number;\n readonly error: number;\n readonly warning: number;\n readonly note: number;\n readonly byTool: Readonly<Record<string, number>>;\n readonly byFile: Readonly<Record<string, number>>;\n}\n\n/**\n * Maintainability dimension expressed as a TDR percentage.\n */\nexport interface MaintainabilityScore {\n readonly rating: MaintainabilityRating;\n readonly tdrPercent: number;\n readonly remediationMinutes: number;\n readonly developmentCostMinutes: number;\n}\n\n/**\n * Pointer to where the consolidated report can be found.\n */\nexport interface ScoreLocation {\n /** Local dashboard URL when the HTTP server is running, otherwise `null`. */\n readonly dashboardUrl: string | null;\n /** Absolute path to the consolidated SARIF document on disk. */\n readonly sarifReportPath: string;\n}\n\n/**\n * The full project score snapshot. Returned from {@link computeProjectScore}.\n */\nexport interface ProjectScore {\n readonly generatedAt: string;\n readonly workspaceRoot: string;\n readonly loc: { readonly physical: number; readonly files: number };\n readonly findings: FindingsSummary;\n readonly maintainability: MaintainabilityScore;\n readonly reliability: DimensionScore;\n readonly security: DimensionScore;\n readonly overall: {\n readonly rating: SeverityRating;\n /** True when `overall.rating` is no worse than `policyRating`. */\n readonly passes: boolean;\n /** Echoed from the configured policy. */\n readonly policyRating: MaintainabilityRating;\n };\n readonly location: ScoreLocation;\n}\n\n/**\n * Inputs accepted by {@link computeProjectScore}.\n */\nexport interface ComputeProjectScoreInput {\n readonly workspaceRoot: string;\n readonly minutesPerLoc: number;\n readonly tdrMaxRating: MaintainabilityRating;\n readonly workspace: WorkspaceStats;\n readonly sarifStore: SarifStore;\n readonly dashboardUrl: string | null;\n readonly sarifReportPath: string;\n}\n\n/**\n * Pattern that classifies a rule identifier as security-relevant.\n * Matches case-insensitively against the rule id text. Intentionally\n * permissive \u2014 false positives in classification are recoverable, but\n * a missed security finding being graded as reliability is not.\n */\nconst SECURITY_RULE_PATTERN =\n /(sec|sql|xss|csrf|ssrf|injection|crypt|auth|secret|password|token|cve|vuln|jwt|cors|rce|deserial|prototype-pollution)/i;\n\n/**\n * Compute the full project score. Pure function \u2014 no side effects.\n *\n * @param input Aggregated inputs.\n * @returns A {@link ProjectScore} ready to be serialized.\n */\nexport function computeProjectScore(input: ComputeProjectScoreInput): ProjectScore {\n const findingsList = input.sarifStore.list();\n\n // ---- Findings summary ----\n /** @type {Record<string, number>} */\n const byTool: Record<string, number> = {};\n const byFile: Record<string, number> = {};\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n let remediationMinutes = 0;\n\n /** Findings split by classification. */\n const securityFindings: Array<{ level: string }> = [];\n const reliabilityFindings: Array<{ level: string }> = [];\n\n for (const finding of findingsList) {\n if (finding.level === \"error\") errorCount += 1;\n else if (finding.level === \"warning\") warningCount += 1;\n else if (finding.level === \"note\") noteCount += 1;\n\n byTool[finding.sourceTool] = (byTool[finding.sourceTool] ?? 0) + 1;\n byFile[finding.location.uri] = (byFile[finding.location.uri] ?? 0) + 1;\n\n const effort =\n typeof finding.properties?.effortMinutes === \"number\"\n ? finding.properties.effortMinutes\n : 0;\n remediationMinutes += effort;\n\n if (SECURITY_RULE_PATTERN.test(finding.ruleId)) {\n securityFindings.push({ level: finding.level });\n } else {\n reliabilityFindings.push({ level: finding.level });\n }\n }\n\n const findings: FindingsSummary = {\n total: findingsList.length,\n error: errorCount,\n warning: warningCount,\n note: noteCount,\n byTool,\n byFile,\n };\n\n // ---- Maintainability (TDR) ----\n // Guard against an empty workspace; the TDR formula divides by LOC.\n const safeLoc = Math.max(input.workspace.physicalLoc, 1);\n const developmentCostMinutes = input.minutesPerLoc * safeLoc;\n const tdrPercent = (remediationMinutes / developmentCostMinutes) * 100;\n const tdrRating = classifyTdr(tdrPercent);\n\n const maintainability: MaintainabilityScore = {\n rating: tdrRating,\n tdrPercent: Number(tdrPercent.toFixed(4)),\n remediationMinutes,\n developmentCostMinutes,\n };\n\n // ---- Reliability and security dimensions ----\n const reliability = scoreDimension(reliabilityFindings);\n const security = scoreDimension(securityFindings);\n\n // ---- Overall = the worst of the three ----\n const overallRating = worstOf(maintainability.rating, reliability.rating, security.rating);\n const passes = !ratingIsWorseThan(overallRating, input.tdrMaxRating);\n\n return {\n generatedAt: new Date().toISOString(),\n workspaceRoot: input.workspaceRoot,\n loc: { physical: input.workspace.physicalLoc, files: input.workspace.fileCount },\n findings,\n maintainability,\n reliability,\n security,\n overall: {\n rating: overallRating,\n passes,\n policyRating: input.tdrMaxRating,\n },\n location: {\n dashboardUrl: input.dashboardUrl,\n sarifReportPath: input.sarifReportPath,\n },\n };\n}\n\n/**\n * Score a single dimension (reliability or security) from its findings.\n *\n * The mapping is intentionally coarse and maps directly from SARIF\n * levels to letter ratings:\n *\n * - 0 findings \u2192 A\n * - only `note` findings \u2192 B\n * - 1+ `warning`, 0 `error` \u2192 C\n * - 1\u20132 `error` \u2192 D\n * - 3+ `error` \u2192 E\n *\n * Projects that stamp explicit blocker / major / minor categories on\n * their SARIF properties can wrap this function with their own\n * taxonomy-aware classifier.\n *\n * @param findings Findings classified into this dimension.\n */\nfunction scoreDimension(findings: ReadonlyArray<{ level: string }>): DimensionScore {\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n for (const f of findings) {\n if (f.level === \"error\") errorCount += 1;\n else if (f.level === \"warning\") warningCount += 1;\n else if (f.level === \"note\") noteCount += 1;\n }\n let rating: SeverityRating;\n if (errorCount >= 3) rating = \"E\";\n else if (errorCount >= 1) rating = \"D\";\n else if (warningCount >= 1) rating = \"C\";\n else if (noteCount >= 1) rating = \"B\";\n else rating = \"A\";\n\n return {\n rating,\n findings: findings.length,\n errorFindings: errorCount,\n warningFindings: warningCount,\n noteFindings: noteCount,\n };\n}\n\n/**\n * Return the worst (alphabetically highest) of an arbitrary number of\n * letter ratings. Used to collapse the three dimension ratings into the\n * overall project rating.\n *\n * @param ratings Two or more letter ratings.\n * @returns The worst rating.\n */\nfunction worstOf(...ratings: ReadonlyArray<SeverityRating>): SeverityRating {\n let worst: SeverityRating = \"A\";\n for (const r of ratings) {\n if (ratingIsWorseThan(r, worst)) worst = r;\n }\n return worst;\n}\n\n/**\n * Render a project score as a compact Markdown summary suitable for\n * display directly in a chat session. Keep it under ~30 lines so it\n * does not dominate the conversation context.\n *\n * @param score The score to render.\n */\nexport function renderProjectScoreMarkdown(score: ProjectScore): string {\n const verdict = score.overall.passes ? \"\u2705 passes policy\" : \"\u274C FAILS policy\";\n const dashboardLine = score.location.dashboardUrl\n ? `\uD83D\uDCCA Dashboard: ${score.location.dashboardUrl}`\n : `\uD83D\uDCCA Dashboard: <not running \u2014 start the MCP server to enable>`;\n\n return [\n `## claude-crap :: project score`,\n ``,\n `**Overall: ${score.overall.rating}** (${verdict}, policy ceiling = ${score.overall.policyRating})`,\n ``,\n `| Dimension | Rating | Detail |`,\n `| --------------- | :----: | --------------------------------------------------- |`,\n `| Maintainability | ${score.maintainability.rating} | TDR ${score.maintainability.tdrPercent}% (${score.maintainability.remediationMinutes} min over ${score.loc.physical} LOC) |`,\n `| Reliability | ${score.reliability.rating} | ${score.reliability.errorFindings} error \u00B7 ${score.reliability.warningFindings} warning \u00B7 ${score.reliability.noteFindings} note |`,\n `| Security | ${score.security.rating} | ${score.security.errorFindings} error \u00B7 ${score.security.warningFindings} warning \u00B7 ${score.security.noteFindings} note |`,\n ``,\n `Workspace: **${score.loc.physical} LOC** across **${score.loc.files} files**`,\n `Findings: **${score.findings.total} total** (${score.findings.error} error \u00B7 ${score.findings.warning} warning \u00B7 ${score.findings.note} note)`,\n `Tools: ${Object.keys(score.findings.byTool).join(\", \") || \"<none ingested>\"}`,\n ``,\n dashboardLine,\n `\uD83D\uDCC4 Report: ${score.location.sarifReportPath}`,\n ].join(\"\\n\");\n}\n", "/**\n * File detail builder for the dashboard.\n *\n * Given a workspace-relative file path, this module produces a rich\n * detail payload combining source code, per-function AST metrics, and\n * SARIF findings filtered to that file. The dashboard uses this to\n * render a ReportGenerator-style annotated code view.\n *\n * The builder is extracted into its own module (rather than inlined in\n * `server.ts`) so that:\n * - The logic is unit-testable without booting the HTTP server.\n * - The types are importable by both the Fastify route and tests.\n *\n * @module dashboard/file-detail\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { resolveWithinWorkspace } from \"../workspace-guard.js\";\nimport { detectLanguageFromPath, type SupportedLanguage } from \"../ast/language-config.js\";\nimport type { TreeSitterEngine, FunctionMetrics } from \"../ast/tree-sitter-engine.js\";\nimport type { SarifStore, IngestedFinding } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Per-function entry in the detail response. */\nexport interface FileDetailFunction {\n readonly name: string;\n readonly startLine: number;\n readonly endLine: number;\n readonly cyclomaticComplexity: number;\n readonly lineCount: number;\n}\n\n/** Per-finding entry in the detail response. */\nexport interface FileDetailFinding {\n readonly ruleId: string;\n readonly level: string;\n readonly message: string;\n readonly sourceTool: string;\n readonly startLine: number;\n readonly startColumn: number;\n readonly endLine: number;\n readonly endColumn: number;\n readonly effortMinutes: number;\n}\n\n/** Summary statistics for the file. */\nexport interface FileDetailSummary {\n readonly totalFindings: number;\n readonly errorCount: number;\n readonly warningCount: number;\n readonly noteCount: number;\n readonly totalEffortMinutes: number;\n readonly avgComplexity: number;\n readonly maxComplexity: number;\n}\n\n/** Full response payload for the file detail endpoint. */\nexport interface FileDetailResponse {\n readonly filePath: string;\n readonly language: SupportedLanguage | null;\n readonly physicalLoc: number;\n readonly logicalLoc: number;\n readonly cyclomaticMax: number;\n readonly sourceLines: string[];\n readonly functions: FileDetailFunction[];\n readonly findings: FileDetailFinding[];\n readonly summary: FileDetailSummary;\n}\n\n/** Input accepted by {@link buildFileDetail}. */\nexport interface BuildFileDetailInput {\n readonly relativePath: string;\n readonly workspaceRoot: string;\n readonly astEngine?: TreeSitterEngine | undefined;\n readonly sarifStore: SarifStore;\n readonly cyclomaticMax: number;\n}\n\n// \u2500\u2500 Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Build the file detail payload. Pure function aside from the file\n * read and the tree-sitter analysis (both deterministic for a given\n * file).\n *\n * @throws When the file does not exist or the path escapes the workspace.\n */\nexport async function buildFileDetail(\n input: BuildFileDetailInput,\n): Promise<FileDetailResponse> {\n const { relativePath, workspaceRoot, astEngine, sarifStore, cyclomaticMax } = input;\n\n // 1. Guard against path traversal\n const absolutePath = resolveWithinWorkspace(workspaceRoot, relativePath);\n\n // 2. Read source\n const source = await fs.readFile(absolutePath, \"utf8\");\n const sourceLines = source.split(/\\r?\\n/);\n // Remove trailing empty line from files ending with \\n\n if (sourceLines.length > 0 && sourceLines[sourceLines.length - 1] === \"\") {\n sourceLines.pop();\n }\n\n const physicalLoc = sourceLines.length;\n let logicalLoc = 0;\n for (const line of sourceLines) {\n if (line.trim().length > 0) logicalLoc += 1;\n }\n\n // 3. AST analysis (if language is supported)\n const language = detectLanguageFromPath(relativePath);\n let functions: FileDetailFunction[] = [];\n\n if (language && astEngine) {\n try {\n const metrics = await astEngine.analyzeFile({\n filePath: absolutePath,\n language,\n });\n functions = metrics.functions.map((fn: FunctionMetrics) => ({\n name: fn.name,\n startLine: fn.startLine,\n endLine: fn.endLine,\n cyclomaticComplexity: fn.cyclomaticComplexity,\n lineCount: fn.lineCount,\n }));\n } catch {\n // Analysis failure is non-fatal \u2014 return empty functions\n }\n }\n\n // 4. Filter SARIF findings for this file\n const allFindings = sarifStore.list();\n const fileFindings = allFindings.filter(\n (f: IngestedFinding) => f.location.uri === relativePath,\n );\n\n const findings: FileDetailFinding[] = fileFindings.map((f: IngestedFinding) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: f.message,\n sourceTool: f.sourceTool,\n startLine: f.location.startLine,\n startColumn: f.location.startColumn,\n endLine: f.location.endLine ?? f.location.startLine,\n endColumn: f.location.endColumn ?? 0,\n effortMinutes:\n typeof f.properties?.effortMinutes === \"number\"\n ? f.properties.effortMinutes\n : 0,\n }));\n\n // 5. Build summary\n let errorCount = 0;\n let warningCount = 0;\n let noteCount = 0;\n let totalEffortMinutes = 0;\n\n for (const f of findings) {\n if (f.level === \"error\") errorCount += 1;\n else if (f.level === \"warning\") warningCount += 1;\n else if (f.level === \"note\") noteCount += 1;\n totalEffortMinutes += f.effortMinutes;\n }\n\n const complexities = functions.map((f) => f.cyclomaticComplexity);\n const maxComplexity = complexities.length > 0 ? Math.max(...complexities) : 0;\n const avgComplexity =\n complexities.length > 0\n ? Math.round(\n (complexities.reduce((a, b) => a + b, 0) / complexities.length) * 100,\n ) / 100\n : 0;\n\n return {\n filePath: relativePath,\n language,\n physicalLoc,\n logicalLoc,\n cyclomaticMax,\n sourceLines,\n functions,\n findings,\n summary: {\n totalFindings: findings.length,\n errorCount,\n warningCount,\n noteCount,\n totalEffortMinutes,\n avgComplexity,\n maxComplexity,\n },\n };\n}\n", "/**\n * Workspace path containment guard.\n *\n * Every MCP tool that accepts a user-supplied file path routes it\n * through {@link resolveWithinWorkspace} before touching the\n * filesystem. The guard rejects any resolved absolute path that is\n * outside the configured workspace root, so the agent cannot be\n * tricked (via prompt injection through scanner output, or via its\n * own confusion) into reading files that live next to the project\n * but outside it.\n *\n * F-A01-01: the original guard in `src/index.ts` used a naive\n * `candidate.startsWith(workspace)` check, which suffers from prefix\n * confusion \u2014 for a workspace like `/Users/x/claude-crap`, an\n * absolute input path such as `/Users/x/claude-crap-evil/secret.ts`\n * would pass the check because the two share the literal prefix up\n * to the final segment. This module replaces that check with a\n * separator-aware comparison: the candidate is only accepted if it\n * equals the workspace exactly OR begins with `workspace + sep`.\n *\n * This module is intentionally pure (no I/O, no global state) so it\n * can be unit-tested without any fixtures.\n *\n * @module workspace-guard\n */\n\nimport { isAbsolute, resolve, sep } from \"node:path\";\n\n/**\n * Resolve a user-supplied file path against a workspace root, returning\n * the absolute path only if it is contained inside the root. Throws a\n * descriptive error when the resolved candidate escapes the workspace.\n *\n * Rules enforced (must stay in sync with\n * `src/tests/workspace-guard.test.ts`):\n *\n * 1. Relative paths are resolved against `workspaceRoot`.\n * 2. Absolute paths are accepted as-is for resolution.\n * 3. The resolved candidate must equal `workspaceRoot` OR begin with\n * `workspaceRoot + sep`. Sibling directories that merely share a\n * prefix (e.g. `/tmp/workspace-evil` vs `/tmp/workspace`) are\n * rejected.\n * 4. The comparison uses the platform's native path separator, so\n * the guard works on both POSIX and Windows.\n *\n * @param workspaceRoot Absolute or relative path to the workspace root.\n * Non-absolute values are resolved against the\n * current working directory, which matches the\n * behavior of the previous in-lined guard.\n * @param filePath User-supplied path. May be absolute or relative\n * to the workspace root.\n * @returns The absolute, workspace-contained path.\n * @throws `Error` when the candidate escapes the workspace.\n */\nexport function resolveWithinWorkspace(workspaceRoot: string, filePath: string): string {\n const workspace = resolve(workspaceRoot);\n const candidate = isAbsolute(filePath) ? resolve(filePath) : resolve(workspace, filePath);\n if (candidate !== workspace && !candidate.startsWith(workspace + sep)) {\n throw new Error(\n `[claude-crap] Refusing to access '${filePath}' \u2014 path escapes the workspace root`,\n );\n }\n return candidate;\n}\n", "/**\n * CRAP (Change Risk Anti-Patterns) index \u2014 deterministic computation.\n *\n * The CRAP index is a single number that summarizes how dangerous it is\n * to change a given function. It combines two signals:\n *\n * 1. Cyclomatic complexity (`comp`) \u2014 how many independent paths the\n * function has. Tracks how easy it is to reason about the code.\n * 2. Test coverage percentage (`cov`) \u2014 empirical safety net provided\n * by the automated test suite.\n *\n * The formula (see docs/quality-gate.md) is:\n *\n * CRAP(m) = comp(m)\u00B2 \u00D7 (1 \u2212 cov(m)/100)\u00B3 + comp(m)\n *\n * The cubic uncovered-weight term makes CRAP punish uncovered, branchy\n * code extremely aggressively. A function with complexity 10 and 0%\n * coverage scores CRAP = 10\u00B2 \u00D7 1\u00B3 + 10 = 110, well above the 30 threshold.\n *\n * The additive `+ comp(m)` tail is intentional: it means that any function\n * with `comp \u2265 30` can NEVER reach a passing CRAP score, even with 100%\n * coverage (because the final term alone equals the threshold). This\n * encodes the policy \"functions above complexity 30 must be decomposed,\n * period\" \u2014 you cannot test your way out of structural complexity.\n *\n * @module metrics/crap\n */\n\n/**\n * Inputs required to compute CRAP for a single function.\n */\nexport interface CrapInput {\n /** Cyclomatic complexity of the function. Must be an integer \u2265 1. */\n readonly cyclomaticComplexity: number;\n /** Test coverage percentage for the function. Must be in `[0, 100]`. */\n readonly coveragePercent: number;\n}\n\n/**\n * Result of a CRAP computation, including the inputs used so callers can\n * echo the context back to the LLM or dump it to a SARIF result's\n * `properties` bag without re-reading the source data.\n */\nexport interface CrapResult {\n /** The CRAP score, rounded to 4 decimals for stable serialization. */\n readonly crap: number;\n /** Cyclomatic complexity echoed from the input. */\n readonly cyclomaticComplexity: number;\n /** Coverage percentage echoed from the input. */\n readonly coveragePercent: number;\n /** `true` when `crap > threshold` \u2014 caller should block on this. */\n readonly exceedsThreshold: boolean;\n /** The threshold used for the `exceedsThreshold` decision. */\n readonly threshold: number;\n}\n\n/**\n * Compute the CRAP index for a single function, against a configurable\n * block threshold. This function is pure, deterministic, and performs no\n * I/O \u2014 it can be called from any context (MCP tool handler, hook, unit\n * test) without side effects.\n *\n * @param input Cyclomatic complexity and coverage for the function.\n * @param threshold The CRAP score above which the caller should block.\n * @returns A {@link CrapResult} containing the score and decision.\n * @throws When any input is out of range or not finite.\n *\n * @example\n * // 12 branches, 60% coverage, threshold = 30\n * computeCrap({ cyclomaticComplexity: 12, coveragePercent: 60 }, 30)\n * // \u2192 { crap: 21.216, exceedsThreshold: false, ... }\n */\nexport function computeCrap(input: CrapInput, threshold: number): CrapResult {\n if (!Number.isFinite(input.cyclomaticComplexity) || input.cyclomaticComplexity < 1) {\n throw new Error(\n `[crap] cyclomaticComplexity must be \u2265 1, got ${input.cyclomaticComplexity}`,\n );\n }\n if (!Number.isFinite(input.coveragePercent) || input.coveragePercent < 0 || input.coveragePercent > 100) {\n throw new Error(\n `[crap] coveragePercent must be in [0, 100], got ${input.coveragePercent}`,\n );\n }\n if (!Number.isFinite(threshold) || threshold <= 0) {\n throw new Error(`[crap] threshold must be > 0, got ${threshold}`);\n }\n\n const comp = input.cyclomaticComplexity;\n const uncovered = 1 - input.coveragePercent / 100;\n const crap = comp * comp * Math.pow(uncovered, 3) + comp;\n\n return {\n // Round to 4 decimals so JSON serialization is stable across runs\n // (important for SARIF diffing and dashboard caching).\n crap: Number(crap.toFixed(4)),\n cyclomaticComplexity: comp,\n coveragePercent: input.coveragePercent,\n exceedsThreshold: crap > threshold,\n threshold,\n };\n}\n", "/**\n * Bounded workspace walker.\n *\n * Counts physical lines of code across a workspace, skipping directories\n * that should not contribute to the Technical Debt Ratio (dependency\n * caches, build artifacts, VCS metadata, etc.) and capping the file\n * count to keep the walk well under the Stop hook's 120-second budget\n * even on pathological repositories.\n *\n * This is the TypeScript twin of `hooks/lib/quality-gate.mjs#estimateWorkspaceLoc`.\n * The two are independent so neither side has to import files from outside\n * its own project tree.\n *\n * @module metrics/workspace-walker\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\n\n/**\n * Result returned by {@link estimateWorkspaceLoc}.\n */\nexport interface WorkspaceWalkResult {\n /** Total physical lines of code across every file the walker read. */\n readonly physicalLoc: number;\n /** Number of code files the walker visited. */\n readonly fileCount: number;\n /** `true` when the walker hit {@link MAX_FILES_WALKED} and stopped early. */\n readonly truncated: boolean;\n}\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n// The createExclusionFilter() factory is called once per walk with\n// optional user-defined patterns from .claude-crap.json.\n\n/**\n * Extensions the walker treats as \"code\". Anything else is ignored,\n * including markdown, JSON, YAML, lockfiles, and binaries.\n */\nconst CODE_EXTENSIONS: ReadonlySet<string> = new Set([\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".py\",\n \".java\",\n \".cs\",\n \".go\",\n \".rs\",\n \".rb\",\n \".php\",\n \".swift\",\n \".kt\",\n \".scala\",\n \".dart\",\n \".vue\",\n]);\n\n/**\n * Hard cap on the number of files the walker will read. Protects against\n * pathological repositories where the walk would otherwise dominate the\n * Stop hook's budget. When hit, the walker returns the partial count\n * with `truncated: true` and the caller may decide how to react.\n */\nexport const MAX_FILES_WALKED = 20_000;\n\n/**\n * Walk a workspace and return its physical LOC + file count. Never\n * follows symbolic links. Skips hidden directories except `.claude-plugin`\n * (which is tiny and contains the manifest).\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @param options Optional settings including user-defined exclusion patterns.\n * @returns A {@link WorkspaceWalkResult} snapshot.\n */\nexport async function estimateWorkspaceLoc(\n workspaceRoot: string,\n options?: { exclude?: ReadonlyArray<string> },\n): Promise<WorkspaceWalkResult> {\n const filter = createExclusionFilter(options?.exclude);\n let physicalLoc = 0;\n let fileCount = 0;\n let truncated = false;\n\n async function walk(dir: string): Promise<void> {\n if (truncated) return;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (truncated) return;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n const lower = entry.name.toLowerCase();\n const dot = lower.lastIndexOf(\".\");\n if (dot < 0) continue;\n const ext = lower.substring(dot);\n if (!CODE_EXTENSIONS.has(ext)) continue;\n const relPath = relative(workspaceRoot, full);\n if (filter.shouldSkipFile(relPath, entry.name)) continue;\n fileCount += 1;\n if (fileCount > MAX_FILES_WALKED) {\n truncated = true;\n return;\n }\n try {\n const content = await fs.readFile(full, \"utf8\");\n if (content.length > 0) {\n const lines = content.split(/\\r?\\n/).length;\n physicalLoc += content.endsWith(\"\\n\") ? lines - 1 : lines;\n }\n } catch {\n // Unreadable file (permissions, binary). Skip silently.\n }\n }\n }\n\n await walk(workspaceRoot);\n return { physicalLoc, fileCount, truncated };\n}\n", "/**\n * On-disk SARIF 2.1.0 store with finding deduplication.\n *\n * The Stop quality gate and the `ingest_sarif` MCP tool both need a\n * single, consolidated view of every finding produced across the current\n * session. This module provides:\n *\n * - `loadLatest()` \u2014 read the consolidated SARIF document from disk,\n * or return an empty seed when no report exists yet.\n * - `ingestRun()` \u2014 merge a new SARIF run from an external scanner\n * (Semgrep, ESLint, Bandit, Stryker, ...) into the\n * in-memory store, deduplicating by\n * `(ruleId, uri, startLine, startColumn)`.\n * - `persist()` \u2014 atomically write the consolidated document back\n * to disk so other processes (the dashboard) can\n * read it.\n *\n * The store is intentionally simple: it does NOT attempt to preserve\n * per-tool run separation inside the persisted file. Instead, every\n * ingested run is flattened into a single `runs[0]` entry whose `tool.driver`\n * is claude-crap itself, and the original scanner name is recorded on\n * each finding via the `properties.sourceTool` field. This keeps the\n * consolidated document easy to diff between sessions.\n *\n * @module sarif/sarif-store\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\nimport { buildSarifDocument, type SarifFinding, type SarifLevel } from \"./sarif-builder.js\";\n\n/**\n * The shape of a persisted SARIF 2.1.0 document, narrowed to the fields\n * we actually read and write. The full spec has many more optional\n * fields; we ignore them on read and do not emit them on write.\n */\nexport interface PersistedSarif {\n readonly $schema?: string;\n readonly version: \"2.1.0\";\n readonly runs: ReadonlyArray<SarifRun>;\n}\n\ninterface SarifRun {\n readonly tool: {\n readonly driver: {\n readonly name: string;\n readonly version: string;\n readonly informationUri?: string;\n readonly rules?: ReadonlyArray<unknown>;\n };\n };\n readonly results: ReadonlyArray<SarifResult>;\n}\n\ninterface SarifResult {\n readonly ruleId: string;\n readonly level?: SarifLevel;\n readonly message: { readonly text: string };\n readonly locations?: ReadonlyArray<SarifResultLocation>;\n readonly properties?: Record<string, unknown>;\n}\n\ninterface SarifResultLocation {\n readonly physicalLocation?: {\n readonly artifactLocation?: { readonly uri?: string };\n readonly region?: {\n readonly startLine?: number;\n readonly startColumn?: number;\n readonly endLine?: number;\n readonly endColumn?: number;\n };\n };\n}\n\n/**\n * Options accepted by the {@link SarifStore} constructor.\n */\nexport interface SarifStoreOptions {\n /** Workspace root. Used to resolve relative `outputDir`. */\n readonly workspaceRoot: string;\n /** Directory (absolute or workspace-relative) where reports are written. */\n readonly outputDir: string;\n /** Filename for the consolidated SARIF document. Defaults to `latest.sarif`. */\n readonly fileName?: string;\n}\n\n/**\n * A finding together with its deduplication key. Used internally and\n * returned by {@link SarifStore.ingestRun} so callers can see which\n * findings were accepted.\n */\nexport interface IngestedFinding extends SarifFinding {\n /** Stable deduplication key, shape: `ruleId|uri|line|col`. */\n readonly dedupKey: string;\n /** Name of the scanner that produced the finding (propagated from `sourceTool`). */\n readonly sourceTool: string;\n}\n\n/**\n * On-disk SARIF store.\n */\nexport class SarifStore {\n private readonly filePath: string;\n /** In-memory index of findings keyed by their dedup string. */\n private readonly findings = new Map<string, IngestedFinding>();\n /** Tool invocations we have already ingested, for telemetry. */\n private toolInvocations = 0;\n\n constructor(options: SarifStoreOptions) {\n const dir = isAbsolute(options.outputDir)\n ? options.outputDir\n : resolve(options.workspaceRoot, options.outputDir);\n this.filePath = join(dir, options.fileName ?? \"latest.sarif\");\n }\n\n /**\n * Absolute path to the consolidated SARIF file on disk.\n */\n get consolidatedReportPath(): string {\n return this.filePath;\n }\n\n /**\n * Load the consolidated document from disk into memory. If the file is\n * missing, the store is initialized empty. Top-level parsing errors\n * still throw (a file that is not valid JSON, or that declares a\n * different SARIF version, is a real safety signal). However, once\n * the document is parsed, malformed individual runs and results are\n * tolerated: F-A08-01 showed that a single bad entry in `latest.sarif`\n * could crash the MCP server on boot and persistently DoS the\n * developer. Each run / result is wrapped in its own try/catch so a\n * single bad entry logs to stderr and is dropped, but the rest of\n * the file still loads.\n *\n * @throws When the file exists but is not valid SARIF 2.1.0 JSON.\n */\n async loadLatest(): Promise<void> {\n try {\n const raw = await fs.readFile(this.filePath, \"utf8\");\n const parsed = JSON.parse(raw) as PersistedSarif;\n if (parsed.version !== \"2.1.0\") {\n throw new Error(`Expected SARIF 2.1.0, got ${parsed.version}`);\n }\n this.findings.clear();\n // Defensive against tampered / mis-generated files: `runs` must\n // be an array. Anything else is dropped with a stderr warning.\n if (!Array.isArray(parsed.runs)) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: 'runs' is not an array, dropping entire document\\n`,\n );\n return;\n }\n for (const run of parsed.runs) {\n try {\n if (!run || typeof run !== \"object\" || !Array.isArray(run.results)) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: skipping run with non-iterable 'results'\\n`,\n );\n continue;\n }\n for (const result of run.results) {\n try {\n const finding = hydrateFindingFromResult(result);\n if (finding) this.findings.set(finding.dedupKey, finding);\n } catch (entryErr) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: dropping malformed result: ${(entryErr as Error).message}\\n`,\n );\n }\n }\n } catch (runErr) {\n process.stderr.write(\n `[sarif-store] ${this.filePath}: dropping malformed run: ${(runErr as Error).message}\\n`,\n );\n }\n }\n } catch (err) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === \"ENOENT\") {\n // No report on disk yet \u2014 normal for a fresh workspace.\n this.findings.clear();\n return;\n }\n throw new Error(\n `[sarif-store] Failed to load consolidated report at ${this.filePath}: ${error.message}`,\n { cause: err },\n );\n }\n }\n\n /**\n * Merge a raw SARIF document (from any external scanner) into the\n * store, deduplicating by `(ruleId, uri, startLine, startColumn)`. The\n * last writer wins for the message and level fields \u2014 later ingestions\n * can refine earlier ones.\n *\n * @param sarifDocument The raw SARIF document as received from the tool.\n * @param sourceTool Stable identifier of the producing scanner.\n * @returns Stats describing what was accepted.\n */\n ingestRun(\n sarifDocument: PersistedSarif,\n sourceTool: string,\n ): { accepted: number; duplicates: number; total: number } {\n if (sarifDocument.version !== \"2.1.0\") {\n throw new Error(\n `[sarif-store] ingestRun received version ${sarifDocument.version}, expected 2.1.0`,\n );\n }\n\n this.toolInvocations += 1;\n let accepted = 0;\n let duplicates = 0;\n let total = 0;\n\n for (const run of sarifDocument.runs) {\n for (const result of run.results) {\n total += 1;\n const finding = hydrateFindingFromResult(result, sourceTool);\n if (!finding) continue;\n if (this.findings.has(finding.dedupKey)) {\n duplicates += 1;\n // Overwrite with the latest metadata so the consolidated view\n // reflects the most recent scanner output for this location.\n this.findings.set(finding.dedupKey, finding);\n continue;\n }\n this.findings.set(finding.dedupKey, finding);\n accepted += 1;\n }\n }\n\n return { accepted, duplicates, total };\n }\n\n /**\n * Snapshot all currently tracked findings as a plain array. Mostly\n * useful for tests and for the dashboard API.\n */\n list(): ReadonlyArray<IngestedFinding> {\n return Array.from(this.findings.values());\n }\n\n /**\n * Atomically write the consolidated document back to disk. Uses a\n * temporary file and `rename` so concurrent readers never observe\n * a half-written document.\n */\n async persist(): Promise<void> {\n const doc = this.toSarifDocument();\n await fs.mkdir(dirname(this.filePath), { recursive: true });\n const tmp = `${this.filePath}.${process.pid}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(doc, null, 2), \"utf8\");\n await fs.rename(tmp, this.filePath);\n }\n\n /**\n * Build the current consolidated SARIF document from the in-memory\n * findings without touching disk.\n */\n toSarifDocument() {\n // Strip the store-only `dedupKey` and `sourceTool` fields before\n // serializing, but keep `sourceTool` in the per-finding `properties`\n // bag so consumers can still trace origin.\n const findings: SarifFinding[] = Array.from(this.findings.values()).map((f) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: f.message,\n location: f.location,\n properties: {\n ...(f.properties ?? {}),\n sourceTool: f.sourceTool,\n },\n }));\n\n return buildSarifDocument(\n {\n name: \"claude-crap\",\n version: \"0.1.0\",\n informationUri: \"https://github.com/local/claude-crap\",\n },\n findings,\n );\n }\n\n /**\n * Number of unique findings currently tracked.\n */\n size(): number {\n return this.findings.size;\n }\n\n /**\n * Number of times `ingestRun` has been called on this instance.\n */\n get invocationsCount(): number {\n return this.toolInvocations;\n }\n}\n\n/**\n * Convert a raw SARIF `result` object into an {@link IngestedFinding}.\n * Returns `null` when the result is malformed (missing ruleId, message,\n * or physical location), since a finding without coordinates cannot be\n * deduplicated and is therefore useless.\n *\n * @param result Raw SARIF `result` object from the scanner's document.\n * @param sourceTool Optional scanner identifier. If omitted, we read it\n * from `result.properties.sourceTool` (used when\n * reloading a persisted report).\n * @returns The hydrated finding, or `null` when invalid.\n */\nfunction hydrateFindingFromResult(\n result: SarifResult,\n sourceTool?: string,\n): IngestedFinding | null {\n if (!result.ruleId || !result.message?.text) return null;\n const loc = result.locations?.[0]?.physicalLocation;\n const uri = loc?.artifactLocation?.uri;\n const region = loc?.region;\n if (!uri || region?.startLine === undefined || region.startColumn === undefined) return null;\n\n const resolvedSourceTool =\n sourceTool ??\n (typeof result.properties?.sourceTool === \"string\"\n ? (result.properties.sourceTool as string)\n : \"unknown\");\n\n const level: SarifLevel = result.level ?? \"warning\";\n const dedupKey = `${result.ruleId}|${uri}|${region.startLine}|${region.startColumn}`;\n\n return {\n ruleId: result.ruleId,\n level,\n message: result.message.text,\n location: {\n uri,\n startLine: region.startLine,\n startColumn: region.startColumn,\n ...(region.endLine !== undefined ? { endLine: region.endLine } : {}),\n ...(region.endColumn !== undefined ? { endColumn: region.endColumn } : {}),\n },\n ...(result.properties ? { properties: result.properties } : {}),\n dedupKey,\n sourceTool: resolvedSourceTool,\n };\n}\n", "/**\n * Minimal SARIF 2.1.0 document builder.\n *\n * Every report that leaves the MCP server on its way to the agent is\n * normalized to SARIF 2.1.0 first. This module provides the typed\n * helpers used to wrap raw findings in the canonical\n * `tool \u2192 runs \u2192 results` taxonomy with exact file coordinates.\n *\n * Per-scanner adapters (Semgrep, ESLint, Bandit, Stryker) live under\n * `src/adapters/` and call into `buildSarifDocument` through the\n * `wrapResultsInSarif` helper in `src/adapters/common.ts`. The\n * on-disk deduplication store lives in `./sarif-store.ts`.\n *\n * The SARIF 2.1.0 spec lives at:\n * https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html\n *\n * @module sarif/sarif-builder\n */\n\n/**\n * Severity levels supported by SARIF 2.1.0. They map 1:1 to the\n * `result.level` field. `\"error\"` is the strongest, `\"none\"` is informational.\n */\nexport type SarifLevel = \"none\" | \"note\" | \"warning\" | \"error\";\n\n/**\n * Physical location of a finding inside a source artifact. `startLine` and\n * `startColumn` are 1-based, matching the SARIF spec. `endLine` and\n * `endColumn` are optional \u2014 omit them for point-like findings.\n */\nexport interface SarifLocation {\n /** Artifact URI, typically a file path relative to the workspace root. */\n readonly uri: string;\n /** 1-based line number where the finding starts. */\n readonly startLine: number;\n /** 1-based column number where the finding starts. */\n readonly startColumn: number;\n /** Optional 1-based line number where the finding ends. */\n readonly endLine?: number;\n /** Optional 1-based column number where the finding ends. */\n readonly endColumn?: number;\n}\n\n/**\n * A single finding ready to be embedded in a SARIF run. This is the\n * internal shape used by claude-crap adapters; it is converted into the\n * official SARIF `result` object by {@link buildSarifDocument}.\n */\nexport interface SarifFinding {\n /** Stable rule identifier (e.g. `\"SONAR-CRAP-001\"`, `\"semgrep.python.sqli\"`). */\n readonly ruleId: string;\n /** Severity level for this finding. */\n readonly level: SarifLevel;\n /** Human-readable message describing the finding. */\n readonly message: string;\n /** Physical location where the finding was detected. */\n readonly location: SarifLocation;\n /** Optional extra metadata stored in the SARIF `properties` bag. */\n readonly properties?: Record<string, unknown>;\n}\n\n/**\n * Metadata describing the tool that produced a SARIF run. The `name` is\n * required by the spec; `version` is strongly recommended so that dashboard\n * diffs can distinguish between scanner releases.\n */\nexport interface SarifToolInfo {\n /** Tool display name (e.g. `\"claude-crap\"`, `\"semgrep\"`). */\n readonly name: string;\n /** Tool semantic version. */\n readonly version: string;\n /** Optional URL pointing to the tool's documentation or home page. */\n readonly informationUri?: string;\n}\n\n/**\n * Build a minimal but valid SARIF 2.1.0 document from a list of findings.\n *\n * The returned object conforms to the SARIF JSON schema hosted at:\n * https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\n *\n * Rules are deduplicated by `ruleId` and emitted in the `tool.driver.rules`\n * array so that downstream consumers (Claude Code, the dashboard, or any\n * third-party SARIF viewer) can render a rule index.\n *\n * @param tool Metadata about the producing tool.\n * @param findings Findings to include in the single run.\n * @returns A SARIF 2.1.0 document literal (frozen by `as const`).\n */\nexport function buildSarifDocument(tool: SarifToolInfo, findings: ReadonlyArray<SarifFinding>) {\n return {\n $schema: \"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json\",\n version: \"2.1.0\",\n runs: [\n {\n tool: {\n driver: {\n name: tool.name,\n version: tool.version,\n informationUri: tool.informationUri ?? \"https://github.com/local/claude-crap\",\n // Deduplicate rules by id while preserving insertion order so\n // the emitted `rules` array matches the order findings appear.\n rules: Array.from(\n new Map(\n findings.map((f) => [\n f.ruleId,\n {\n id: f.ruleId,\n shortDescription: { text: f.ruleId },\n defaultConfiguration: { level: f.level },\n },\n ]),\n ).values(),\n ),\n },\n },\n results: findings.map((f) => ({\n ruleId: f.ruleId,\n level: f.level,\n message: { text: f.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: f.location.uri },\n region: {\n startLine: f.location.startLine,\n startColumn: f.location.startColumn,\n ...(f.location.endLine !== undefined ? { endLine: f.location.endLine } : {}),\n ...(f.location.endColumn !== undefined ? { endColumn: f.location.endColumn } : {}),\n },\n },\n },\n ],\n ...(f.properties ? { properties: f.properties } : {}),\n })),\n },\n ],\n } as const;\n}\n", "/**\n * AJV-backed minimal SARIF 2.1.0 document validator.\n *\n * F-A05-01: the `ingest_sarif` MCP tool accepts a caller-supplied\n * `sarifDocument` object and, before this module existed, only\n * checked `version === \"2.1.0\"`. That was enough for tool-call\n * dispatch but not for the payload itself \u2014 a SARIF with a missing\n * `runs[]`, a `results` array of wrong-type entries, or a result\n * without a `ruleId` would still be accepted by the MCP tool and\n * flow through to the store, the dashboard, and any downstream\n * consumer that uploads claude-crap's SARIF to GitHub code-scanning\n * or an IDE viewer.\n *\n * This module uses the `ajv` dependency (already in package.json) to\n * compile a minimal JSON Schema that covers exactly the fields\n * claude-crap reads: `version`, `runs`, `runs[].tool.driver.name`,\n * and the per-result shape. Everything else (tool metadata, rule\n * definitions, snippets, etc.) is passthrough \u2014 we do not enforce\n * the full SARIF 2.1.0 spec because claude-crap does not consume\n * those fields.\n *\n * The compiled validator is cached so the ~5 ms AJV compile cost is\n * paid once per MCP server process, not once per ingestion.\n *\n * @module sarif/sarif-validator\n */\n\nimport { Ajv, type ValidateFunction } from \"ajv\";\n\n/**\n * Minimal JSON Schema covering every field claude-crap reads from a\n * SARIF 2.1.0 document. Passthrough fields are allowed because\n * `additionalProperties` is left at the default (`true`).\n *\n * Keep this schema in sync with `hydrateFindingFromResult` in\n * `src/sarif/sarif-store.ts` \u2014 anything the store reads MUST be\n * covered here, and nothing else should be enforced.\n */\nconst SARIF_MINIMAL_SCHEMA = {\n type: \"object\",\n properties: {\n version: { type: \"string\", enum: [\"2.1.0\"] },\n $schema: { type: \"string\" },\n runs: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n tool: {\n type: \"object\",\n properties: {\n driver: {\n type: \"object\",\n properties: {\n name: { type: \"string\", minLength: 1 },\n version: { type: \"string\" },\n },\n required: [\"name\"],\n },\n },\n required: [\"driver\"],\n },\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n ruleId: { type: \"string\", minLength: 1 },\n level: { type: \"string\", enum: [\"none\", \"note\", \"warning\", \"error\"] },\n message: {\n type: \"object\",\n properties: { text: { type: \"string\", minLength: 1 } },\n required: [\"text\"],\n },\n locations: { type: \"array\" },\n properties: { type: \"object\" },\n },\n required: [\"ruleId\", \"message\"],\n },\n },\n },\n required: [\"tool\", \"results\"],\n },\n },\n },\n required: [\"version\", \"runs\"],\n} as const;\n\n/**\n * Lazily-compiled validator instance. `null` until the first call to\n * {@link validateSarifDocument}, then reused for the lifetime of the\n * process.\n */\nlet cachedValidator: ValidateFunction | null = null;\n\n/**\n * Returned by {@link validateSarifDocument} when the document fails\n * schema validation. Includes the full AJV error array for callers\n * that want to surface structured diagnostics.\n */\nexport class SarifValidationError extends Error {\n public readonly errors: unknown;\n\n constructor(message: string, errors: unknown) {\n super(message);\n this.name = \"SarifValidationError\";\n this.errors = errors;\n }\n}\n\n/**\n * Obtain the compiled AJV validator, compiling on first use.\n *\n * The schema above intentionally allows passthrough fields on every\n * object (AJV's default `additionalProperties: true`). We disable\n * `strict` so AJV does not warn about benign constructs like the\n * `format`/`enum` combination.\n */\nfunction getValidator(): ValidateFunction {\n if (cachedValidator) return cachedValidator;\n const ajv = new Ajv({ allErrors: false, strict: false });\n const validator = ajv.compile(SARIF_MINIMAL_SCHEMA);\n cachedValidator = validator;\n return validator;\n}\n\n/**\n * Validate a SARIF 2.1.0 document against the minimal schema. Throws\n * {@link SarifValidationError} when the document does not match.\n *\n * @param doc Document to validate. May be any value \u2014 the validator\n * treats non-object inputs as a schema violation.\n * @throws {@link SarifValidationError} on any validation failure.\n */\nexport function validateSarifDocument(doc: unknown): void {\n const validator = getValidator();\n if (validator(doc)) return;\n const first = validator.errors?.[0];\n const path = first?.instancePath?.length ? first.instancePath : \"<root>\";\n const message = first?.message ?? \"unknown validation error\";\n throw new SarifValidationError(\n `[sarif-validator] SARIF document is not valid 2.1.0: ${path} ${message}`,\n validator.errors ?? null,\n );\n}\n", "/**\n * Workspace-level sonar configuration loader.\n *\n * Every subsystem that can be made stricter or looser (the Stop\n * quality gate, the `score_project` tool's `isError` flag) consults\n * this loader to decide how hard to push back when a policy fails.\n * Teams adopt claude-crap in stages:\n *\n * - `strict` (default) \u2014 the Stop hook exits 2 on any policy\n * failure and the `score_project` tool returns `isError: true`.\n * Matches the current, hard-coded behavior.\n * - `warn` \u2014 the Stop hook exits 0 but writes the\n * full verdict to stdout so the agent still sees every failing\n * rule in its hook transcript. `score_project.isError` stays\n * false even on a failing project.\n * - `advisory` \u2014 the Stop hook exits 0 and writes a\n * single-line summary. Minimal pressure on the agent.\n *\n * The loader resolves the `strictness` value in strict priority\n * order so a team's committed default can be overridden per-session\n * without editing the file:\n *\n * 1. `CLAUDE_CRAP_STRICTNESS` environment variable\n * 2. `.claude-crap.json` at the workspace root\n * 3. Hardcoded default `\"strict\"` (zero behavior change for\n * installs that never create the file)\n *\n * The loader is intentionally tiny \u2014 it does a single synchronous\n * file read, one optional env probe, and validates the string\n * against the enum. A hook script can call it from inside its\n * 15-second budget without breaking a sweat.\n *\n * @module crap-config\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Exhaustive list of valid strictness values. Keep this in sync with\n * the `Strictness` type below \u2014 the tuple is `as const` so TypeScript\n * derives the union from the same source of truth.\n */\nexport const STRICTNESS_VALUES = [\"strict\", \"warn\", \"advisory\"] as const;\n\n/**\n * Union of valid strictness values. Used by every consumer of\n * {@link CrapConfig} to branch on the mode without dealing with\n * arbitrary strings.\n */\nexport type Strictness = (typeof STRICTNESS_VALUES)[number];\n\n/**\n * Hardcoded default used when neither the environment variable nor\n * `.claude-crap.json` provides a value. Chosen as `\"strict\"` so the\n * plugin adopts gradually on existing codebases without blocking.\n * Teams that want hard enforcement can set `\"strict\"` in\n * `.claude-crap.json` or via `CLAUDE_CRAP_STRICTNESS=strict`.\n */\nexport const DEFAULT_STRICTNESS: Strictness = \"warn\";\n\n/**\n * Thrown by {@link loadCrapConfig} when the configuration is\n * rejected. Callers in the hook layer fall back to the default on a\n * throw so a busted config never deadlocks the user, while callers\n * in the MCP server surface the error verbatim.\n */\nexport class CrapConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CrapConfigError\";\n }\n}\n\n/**\n * Structure of the resolved sonar configuration returned by\n * {@link loadCrapConfig}. The shape is deliberately minimal for\n * v0.1.0; future releases may add threshold overrides under the\n * same `.claude-crap.json` file.\n */\nexport interface CrapConfig {\n /** Final strictness, after env override, file, and default fallback. */\n readonly strictness: Strictness;\n /** Where the strictness value actually came from. Useful for diagnostics. */\n readonly strictnessSource: \"env\" | \"file\" | \"default\";\n /** User-defined exclusion patterns (directories with trailing `/`, or file globs). */\n readonly exclude: ReadonlyArray<string>;\n /** Relative paths to directories containing sub-projects (e.g. `[\"apps\", \"packages\"]`). */\n readonly projectDirs: ReadonlyArray<string>;\n}\n\n/**\n * Options accepted by {@link loadCrapConfig}. The only required\n * field is the workspace root the loader should search for\n * `.claude-crap.json`.\n */\nexport interface LoadCrapConfigOptions {\n /**\n * Absolute path to the workspace root. The loader reads\n * `.claude-crap.json` from this directory only \u2014 it does not\n * walk parent directories.\n */\n readonly workspaceRoot: string;\n}\n\n/**\n * Resolve the effective sonar configuration for a given workspace\n * root. Pure function except for the one synchronous file read on\n * `<workspaceRoot>/.claude-crap.json` and the two env lookups.\n *\n * @param options Search options. Only `workspaceRoot` is required.\n * @returns The resolved {@link CrapConfig}.\n * @throws {@link CrapConfigError} on any invalid input.\n */\nexport function loadCrapConfig(options: LoadCrapConfigOptions): CrapConfig {\n // Always read the file to extract `exclude`, even when strictness\n // comes from the environment variable.\n const fileResult = readFromFile(options.workspaceRoot);\n const exclude = fileResult?.exclude ?? [];\n const projectDirs = fileResult?.projectDirs ?? [];\n\n const envRaw = process.env[\"CLAUDE_CRAP_STRICTNESS\"];\n if (typeof envRaw === \"string\" && envRaw.trim() !== \"\") {\n const normalized = envRaw.trim().toLowerCase();\n if (!isStrictness(normalized)) {\n throw new CrapConfigError(\n `[crap-config] CLAUDE_CRAP_STRICTNESS=\"${envRaw}\" is not a valid strictness. ` +\n `Expected one of: ${STRICTNESS_VALUES.join(\", \")}.`,\n );\n }\n return { strictness: normalized, strictnessSource: \"env\", exclude, projectDirs };\n }\n\n if (fileResult?.strictness) {\n return { strictness: fileResult.strictness, strictnessSource: \"file\", exclude, projectDirs };\n }\n\n return { strictness: DEFAULT_STRICTNESS, strictnessSource: \"default\", exclude, projectDirs };\n}\n\n/**\n * Attempt to read and validate `.claude-crap.json` at the\n * workspace root. Returns `null` when the file is missing (which\n * is the common case for fresh installs). Throws\n * {@link CrapConfigError} on any other failure mode \u2014 a malformed\n * JSON file, a non-object root, a missing or wrong-type\n * `strictness` field, or an unknown enum value \u2014 so the caller\n * cannot accidentally drop into the default on a typo.\n *\n * @param workspaceRoot Absolute workspace root.\n * @returns The validated strictness, or `null` when no\n * file is present.\n */\ninterface FileResult {\n strictness: Strictness | null;\n exclude: string[];\n projectDirs: string[];\n}\n\nfunction readFromFile(workspaceRoot: string): FileResult | null {\n const filePath = join(workspaceRoot, \".claude-crap.json\");\n let raw: string;\n try {\n raw = readFileSync(filePath, \"utf8\");\n } catch (err) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === \"ENOENT\") return null;\n throw new CrapConfigError(\n `[crap-config] Failed to read ${filePath}: ${error.message}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new CrapConfigError(\n `[crap-config] ${filePath} is not valid JSON: ${(err as Error).message}`,\n );\n }\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath} must be a JSON object at the top level`,\n );\n }\n const doc = parsed as Record<string, unknown>;\n\n // Parse strictness\n let strictness: Strictness | null = null;\n if (\"strictness\" in doc) {\n const value = doc[\"strictness\"];\n if (typeof value !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'strictness' must be a string, got ${typeof value}`,\n );\n }\n const normalized = value.trim().toLowerCase();\n if (!isStrictness(normalized)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'strictness' is \"${value}\"; ` +\n `expected one of ${STRICTNESS_VALUES.join(\", \")}.`,\n );\n }\n strictness = normalized;\n }\n\n // Parse exclude\n let exclude: string[] = [];\n if (\"exclude\" in doc) {\n const raw = doc[\"exclude\"];\n if (!Array.isArray(raw)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'exclude' must be an array of strings`,\n );\n }\n for (const item of raw) {\n if (typeof item !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: every entry in 'exclude' must be a string, got ${typeof item}`,\n );\n }\n }\n exclude = raw as string[];\n }\n\n // Parse projectDirs\n let projectDirs: string[] = [];\n if (\"projectDirs\" in doc) {\n const raw = doc[\"projectDirs\"];\n if (!Array.isArray(raw)) {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: 'projectDirs' must be an array of strings`,\n );\n }\n for (const item of raw) {\n if (typeof item !== \"string\") {\n throw new CrapConfigError(\n `[crap-config] ${filePath}: every entry in 'projectDirs' must be a string, got ${typeof item}`,\n );\n }\n }\n projectDirs = raw as string[];\n }\n\n return { strictness, exclude, projectDirs };\n}\n\n/**\n * Runtime type guard for the {@link Strictness} union. Lets callers\n * narrow an arbitrary string to the union without casting.\n *\n * @param value Arbitrary string.\n * @returns `true` when `value` is a recognized strictness.\n */\nfunction isStrictness(value: string): value is Strictness {\n return (STRICTNESS_VALUES as ReadonlyArray<string>).includes(value);\n}\n", "/**\n * Deterministic test-file resolver used by the `require_test_harness`\n * MCP tool.\n *\n * Given a production source file (for example `src/foo/bar.ts`), this\n * module enumerates the conventional locations where a matching test\n * file would live and returns the first existing match \u2014 or `null` when\n * none of the candidates exist.\n *\n * This is a TypeScript twin of `hooks/lib/test-harness.mjs`. The two\n * are intentionally independent so neither side has to import files\n * from outside its own project tree:\n *\n * - Hooks use the `.mjs` copy (vanilla JS, zero deps, runs everywhere).\n * - The MCP server uses this typed copy so its consumers get full\n * type safety and so the server stays a self-contained npm package.\n *\n * Both copies implement the same conventions and are validated against\n * the same unit tests \u2014 see `src/tests/test-harness.test.ts`.\n *\n * @module tools/test-harness\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\n\n/**\n * Result of probing the filesystem for a matching test file.\n */\nexport interface TestFileResolution {\n /** Absolute path of the first matching test file, or `null` when none exists. */\n readonly testFile: string | null;\n /** Absolute paths of every location the resolver tried. */\n readonly candidates: ReadonlyArray<string>;\n /** `true` when the input path itself is a test file. */\n readonly isTestFile: boolean;\n}\n\n/** Matches `.test.` and `.spec.` suffixes inside a file basename. */\nconst TEST_SUFFIX_PATTERN = /\\.(test|spec)\\./;\n\n/**\n * Return `true` when the given path is already a test file. Matching is\n * done against the basename (`foo.test.ts`, `test_foo.py`) and against\n * common test directory names in the path (`__tests__`, `tests`, `test`).\n *\n * @param filePath An absolute or relative source path.\n */\nexport function isTestFile(filePath: string): boolean {\n const base = basename(filePath);\n if (TEST_SUFFIX_PATTERN.test(base)) return true;\n if (base.startsWith(\"test_\") && base.endsWith(\".py\")) return true;\n const parts = filePath.split(sep);\n return parts.includes(\"__tests__\") || parts.includes(\"tests\") || parts.includes(\"test\");\n}\n\n/**\n * Enumerate every plausible test file path for a given production source\n * file. Does not touch the filesystem \u2014 the caller is expected to probe\n * existence separately (see {@link findTestFile}).\n *\n * Supported conventions, in the order they are probed:\n *\n * 1. Sibling `<base>.test.<ext>` / `<base>.spec.<ext>`\n * 2. Sibling `__tests__/<base>.test.<ext>`\n * 3. Mirror tree under `tests/`, `test/`, or `__tests__/` at the\n * workspace root (e.g. `tests/src/foo/bar.test.ts`)\n * 4. **Nearest-ancestor flat test directory**: walk up from the source\n * file's directory toward the workspace root, and at every ancestor\n * check for `tests/<base>.test.<ext>`. Matches layouts where tests\n * live in a single flat directory near the source (this project\n * uses it for `src/mcp-server/src/tests/`).\n * 5. Python-specific: sibling `test_<base>.py` and mirror-tree\n * `tests/.../test_<base>.py`.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param filePath Absolute path to the production file.\n * @returns Ordered list of absolute candidate paths.\n */\nexport function candidatePaths(workspaceRoot: string, filePath: string): ReadonlyArray<string> {\n const absSource = resolve(filePath);\n const ext = extname(absSource);\n const base = basename(absSource, ext);\n const dir = dirname(absSource);\n const absWorkspace = resolve(workspaceRoot);\n const relFromRoot = relative(absWorkspace, absSource);\n const relDir = dirname(relFromRoot);\n\n const candidates = new Set<string>();\n\n // 1. Sibling <base>.test.<ext> / <base>.spec.<ext>\n candidates.add(join(dir, `${base}.test${ext}`));\n candidates.add(join(dir, `${base}.spec${ext}`));\n\n // 2. Sibling __tests__/<base>.test.<ext>\n candidates.add(join(dir, \"__tests__\", `${base}.test${ext}`));\n candidates.add(join(dir, \"__tests__\", `${base}.spec${ext}`));\n\n // 3. Mirror tree under tests/, test/, or __tests__ at the workspace root.\n for (const testRoot of [\"tests\", \"test\", \"__tests__\"]) {\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}.test${ext}`));\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}.spec${ext}`));\n candidates.add(join(absWorkspace, testRoot, relDir, `${base}${ext}`));\n }\n\n // 4. Nearest-ancestor flat test directory. Walk up from `dir` to\n // `absWorkspace`, and at each ancestor probe for a flat\n // `tests/<base>.test.<ext>` (or `test/`, `__tests__/`) layout.\n let current = dir;\n while (current.length >= absWorkspace.length) {\n for (const testRoot of [\"tests\", \"test\", \"__tests__\"]) {\n candidates.add(join(current, testRoot, `${base}.test${ext}`));\n candidates.add(join(current, testRoot, `${base}.spec${ext}`));\n candidates.add(join(current, testRoot, `${base}${ext}`));\n }\n if (current === absWorkspace) break;\n const parent = dirname(current);\n if (parent === current) break; // reached filesystem root, stop\n current = parent;\n }\n\n // 5. Python-specific variants.\n if (ext === \".py\") {\n candidates.add(join(dir, `test_${base}.py`));\n candidates.add(join(absWorkspace, \"tests\", `test_${base}.py`));\n candidates.add(join(absWorkspace, \"tests\", relDir, `test_${base}.py`));\n }\n\n return Array.from(candidates);\n}\n\n/**\n * Probe the filesystem and return the first candidate that exists, or\n * `null` when none of them do. Returns early with `isTestFile: true`\n * when the input is already a test file.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param filePath Absolute or relative path to the production file.\n */\nexport async function findTestFile(\n workspaceRoot: string,\n filePath: string,\n): Promise<TestFileResolution> {\n const absolute = isAbsolute(filePath) ? filePath : resolve(workspaceRoot, filePath);\n if (isTestFile(absolute)) {\n return { testFile: absolute, candidates: [absolute], isTestFile: true };\n }\n const candidates = candidatePaths(workspaceRoot, absolute);\n for (const candidate of candidates) {\n try {\n await fs.access(candidate);\n return { testFile: candidate, candidates, isTestFile: false };\n } catch {\n // Probe next candidate.\n }\n }\n return { testFile: null, candidates, isTestFile: false };\n}\n", "/**\n * Orchestrator: detect available scanners, run them, and ingest results.\n *\n * This module ties together the detector, runner, and adapter pipeline\n * into a single `autoScan()` function that:\n *\n * 1. Probes the workspace for available scanners\n * 2. Executes detected scanners in parallel\n * 3. Routes each scanner's output through its adapter\n * 4. Ingests the normalized SARIF into the store\n *\n * The function is designed to be called:\n * - At MCP server boot (fire-and-forget, non-blocking)\n * - On demand via the `auto_scan` MCP tool\n *\n * Failures in individual scanners are logged and skipped \u2014 a broken\n * Semgrep install should not prevent ESLint from running.\n *\n * @module scanner/auto-scan\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Logger } from \"pino\";\nimport { detectScanners, detectMonorepoScanners, type ScannerDetection } from \"./detector.js\";\nimport { runScanner, type ScannerRunResult } from \"./runner.js\";\nimport { bootstrapScanner } from \"./bootstrap.js\";\nimport { scanComplexity, type ComplexityScanResult } from \"./complexity-scanner.js\";\nimport { adaptScannerOutput, type KnownScanner } from \"../adapters/index.js\";\nimport type { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-scanner result within the auto-scan summary.\n */\nexport interface ScannerResult {\n scanner: KnownScanner;\n success: boolean;\n findingsIngested: number;\n durationMs: number;\n error?: string;\n}\n\n/**\n * Complete result of an auto-scan run.\n */\nexport interface AutoScanResult {\n /** Detection results for all four scanners. */\n detected: ScannerDetection[];\n /** Execution + ingestion results for scanners that were available. */\n results: ScannerResult[];\n /** Total findings ingested across all scanners. */\n totalFindings: number;\n /** Wall-clock time for the entire auto-scan. */\n totalDurationMs: number;\n /** Result of the built-in cyclomatic complexity scan, when enabled. */\n complexityScan?: ComplexityScanResult;\n}\n\n// \u2500\u2500 Orchestrator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Ingest a single scanner's raw output through its adapter and into\n * the SARIF store. Returns the number of accepted findings.\n */\nfunction ingestScannerRun(\n scanner: KnownScanner,\n rawOutput: string,\n sarifStore: SarifStore,\n): { accepted: number } {\n // Parse the raw output \u2014 adapters accept string or object\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawOutput);\n } catch {\n // Semgrep outputs SARIF as a string, others are JSON.\n // If parsing fails, pass the raw string to the adapter.\n parsed = rawOutput;\n }\n\n const adapted = adaptScannerOutput(scanner, parsed);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n return { accepted: stats.accepted };\n}\n\n/**\n * Auto-detect, run, and ingest all available scanners.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @param sarifStore Live SARIF store to ingest findings into.\n * @param logger Pino logger for progress and error reporting.\n * @returns Summary of what was detected, run, and ingested.\n */\nexport async function autoScan(\n workspaceRoot: string,\n sarifStore: SarifStore,\n logger: Logger,\n options?: { engine?: TreeSitterEngine; cyclomaticMax?: number; exclude?: ReadonlyArray<string> },\n): Promise<AutoScanResult> {\n const start = Date.now();\n\n // 1. Detect available scanners (root + monorepo subdirs)\n const detected = await detectScanners(workspaceRoot);\n const monorepoDetected = await detectMonorepoScanners(workspaceRoot);\n\n // Merge monorepo detections \u2014 skip duplicates (same scanner already found at root)\n const rootScannerSet = new Set(detected.filter((d) => d.available).map((d) => d.scanner));\n for (const md of monorepoDetected) {\n if (!rootScannerSet.has(md.scanner)) {\n detected.push(md);\n }\n }\n\n const available = detected.filter((d) => d.available);\n\n logger.info(\n {\n detected: detected.map((d) => `${d.scanner}:${d.available}`),\n monorepo: monorepoDetected.length,\n available: available.length,\n },\n \"auto-scan: detection complete\",\n );\n\n // If ESLint is detected (e.g. in package.json) but has no config file,\n // bootstrap will create one before we try to scan.\n const eslintConfigFiles = [\n \"eslint.config.js\", \"eslint.config.mjs\", \"eslint.config.cjs\",\n \"eslint.config.ts\", \"eslint.config.mts\", \"eslint.config.cts\",\n \".eslintrc.js\", \".eslintrc.cjs\", \".eslintrc.yaml\",\n \".eslintrc.yml\", \".eslintrc.json\",\n ];\n const eslintDetected = available.some((d) => d.scanner === \"eslint\");\n const hasEslintConfig = eslintConfigFiles.some((f) => existsSync(join(workspaceRoot, f)));\n\n if (eslintDetected && !hasEslintConfig) {\n logger.info(\"auto-scan: ESLint detected but no config \u2014 running bootstrap\");\n try {\n const bootstrapResult = await bootstrapScanner(workspaceRoot, sarifStore, logger);\n if (bootstrapResult.autoScanResult) {\n return bootstrapResult.autoScanResult;\n }\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: bootstrap config creation failed\",\n );\n }\n }\n\n if (available.length === 0) {\n // No scanners configured \u2014 try to bootstrap one automatically.\n logger.info(\"auto-scan: no scanners found, attempting bootstrap\");\n try {\n const bootstrapResult = await bootstrapScanner(workspaceRoot, sarifStore, logger);\n if (bootstrapResult.autoScanResult) {\n return bootstrapResult.autoScanResult;\n }\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: bootstrap failed \u2014 continuing with empty results\",\n );\n }\n\n return {\n detected,\n results: [],\n totalFindings: 0,\n totalDurationMs: Date.now() - start,\n };\n }\n\n // 2. Run all available scanners in parallel (each from its detected workingDir)\n const runResults = await Promise.allSettled(\n available.map((d) => runScanner(d.scanner, workspaceRoot, d.workingDir ? { workingDir: d.workingDir } : undefined)),\n );\n\n // 3. Ingest results\n const results: ScannerResult[] = [];\n let totalFindings = 0;\n let persistNeeded = false;\n\n for (let i = 0; i < available.length; i++) {\n const detection = available[i]!;\n const settled = runResults[i]!;\n\n if (settled.status === \"rejected\") {\n const error = String(settled.reason);\n logger.warn(\n { scanner: detection.scanner, error },\n \"auto-scan: scanner execution rejected\",\n );\n results.push({\n scanner: detection.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: 0,\n error,\n });\n continue;\n }\n\n const runResult: ScannerRunResult = settled.value;\n\n if (!runResult.success) {\n logger.warn(\n { scanner: runResult.scanner, error: runResult.error },\n \"auto-scan: scanner returned failure\",\n );\n results.push({\n scanner: runResult.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: runResult.durationMs,\n error: runResult.error ?? \"unknown error\",\n });\n continue;\n }\n\n // Ingest through adapter pipeline\n try {\n const { accepted } = ingestScannerRun(\n runResult.scanner,\n runResult.rawOutput,\n sarifStore,\n );\n totalFindings += accepted;\n persistNeeded = true;\n\n logger.info(\n { scanner: runResult.scanner, accepted, durationMs: runResult.durationMs },\n \"auto-scan: scanner ingested\",\n );\n\n results.push({\n scanner: runResult.scanner,\n success: true,\n findingsIngested: accepted,\n durationMs: runResult.durationMs,\n });\n } catch (err) {\n const error = (err as Error).message;\n logger.warn(\n { scanner: runResult.scanner, error },\n \"auto-scan: adapter/ingestion failed\",\n );\n results.push({\n scanner: runResult.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: runResult.durationMs,\n error,\n });\n }\n }\n\n // 4. Persist consolidated SARIF if anything was ingested\n if (persistNeeded) {\n await sarifStore.persist();\n }\n\n // 5. Run built-in cyclomatic complexity scanner\n let complexityScan: ComplexityScanResult | undefined;\n if (options?.engine) {\n try {\n complexityScan = await scanComplexity(\n workspaceRoot,\n options.engine,\n sarifStore,\n { cyclomaticMax: options.cyclomaticMax ?? 15, ...(options.exclude ? { exclude: options.exclude } : {}) },\n logger,\n );\n totalFindings += complexityScan.violations;\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"auto-scan: complexity scanner failed \u2014 continuing without it\",\n );\n }\n }\n\n return {\n detected,\n results,\n totalFindings,\n totalDurationMs: Date.now() - start,\n ...(complexityScan ? { complexityScan } : {}),\n };\n}\n", "/**\n * Auto-detect which scanners are available in the current workspace.\n *\n * For each of the four supported scanners (ESLint, Semgrep, Bandit,\n * Stryker) the detector probes three signal layers in order:\n *\n * 1. Config file existence (fastest \u2014 a single `fs.stat`)\n * 2. Package.json dependency (for JS-ecosystem scanners)\n * 3. Binary availability via `which` (slowest \u2014 spawns a child process)\n *\n * Detection short-circuits on the first hit, so a project that has an\n * `eslint.config.mjs` will never shell out to `which eslint`.\n *\n * The module is side-effect-free beyond filesystem reads and one\n * `child_process.execFile` per binary probe.\n *\n * @module scanner/detector\n */\n\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport type { KnownScanner } from \"../adapters/common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Result of probing a single scanner's availability.\n */\nexport interface ScannerDetection {\n /** Which scanner was probed. */\n scanner: KnownScanner;\n /** Whether the scanner is available and can be executed. */\n available: boolean;\n /** Human-readable reason for the verdict. */\n reason: string;\n /** Path to the config file that triggered detection, if any. */\n configPath?: string;\n /** Working directory to run the scanner from (defaults to workspace root). */\n workingDir?: string;\n}\n\n// \u2500\u2500 Detection signals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Config file globs and package.json keys per scanner. Order matters:\n * the first matching config file short-circuits further probes.\n */\ninterface ScannerSignals {\n configFiles: string[];\n packageJsonKeys: string[];\n binaryNames: string[];\n}\n\nconst SCANNER_SIGNALS: Record<KnownScanner, ScannerSignals> = {\n eslint: {\n configFiles: [\n \"eslint.config.js\",\n \"eslint.config.mjs\",\n \"eslint.config.cjs\",\n \"eslint.config.ts\",\n \"eslint.config.mts\",\n \"eslint.config.cts\",\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \".eslintrc.yaml\",\n \".eslintrc.yml\",\n \".eslintrc.json\",\n ],\n packageJsonKeys: [\"eslint\"],\n binaryNames: [\"eslint\"],\n },\n semgrep: {\n configFiles: [\n \".semgrep.yml\",\n \".semgrep.yaml\",\n \".semgrep.json\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"semgrep\"],\n },\n bandit: {\n configFiles: [\n \".bandit\",\n \"bandit.yaml\",\n \"bandit.yml\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"bandit\"],\n },\n stryker: {\n configFiles: [\n \"stryker.conf.js\",\n \"stryker.conf.mjs\",\n \"stryker.conf.cjs\",\n \"stryker.conf.json\",\n \".strykerrc\",\n \".strykerrc.json\",\n ],\n packageJsonKeys: [\"@stryker-mutator/core\"],\n binaryNames: [\"stryker\"],\n },\n dart_analyze: {\n configFiles: [\n \"analysis_options.yaml\",\n \"pubspec.yaml\",\n ],\n packageJsonKeys: [],\n binaryNames: [\"dart\"],\n },\n dotnet_format: {\n configFiles: [],\n packageJsonKeys: [],\n binaryNames: [\"dotnet\"],\n },\n};\n\n// \u2500\u2500 Probes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Check if any of the scanner's config files exist in the workspace.\n */\nfunction probeConfigFiles(\n workspaceRoot: string,\n scanner: KnownScanner,\n): { found: boolean; path?: string } {\n const signals = SCANNER_SIGNALS[scanner];\n for (const file of signals.configFiles) {\n const fullPath = join(workspaceRoot, file);\n if (existsSync(fullPath)) {\n return { found: true, path: fullPath };\n }\n }\n return { found: false };\n}\n\n/**\n * Check if the scanner appears in package.json deps or devDeps.\n */\nfunction probePackageJson(\n workspaceRoot: string,\n scanner: KnownScanner,\n): boolean {\n const signals = SCANNER_SIGNALS[scanner];\n if (signals.packageJsonKeys.length === 0) return false;\n\n const pkgPath = join(workspaceRoot, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n const deps = {\n ...(typeof pkg.dependencies === \"object\" && pkg.dependencies !== null\n ? (pkg.dependencies as Record<string, string>)\n : {}),\n ...(typeof pkg.devDependencies === \"object\" && pkg.devDependencies !== null\n ? (pkg.devDependencies as Record<string, string>)\n : {}),\n };\n return signals.packageJsonKeys.some((key) => key in deps);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a binary is available on PATH via `which`.\n */\nfunction probeBinary(binaryName: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\"which\", [binaryName], { timeout: 5_000 }, (err) => {\n resolve(err === null);\n });\n });\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect which supported scanners are available in the given workspace.\n * Probes config files, package.json, and binary availability in order,\n * short-circuiting on first match.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @returns One {@link ScannerDetection} per known scanner.\n */\nexport async function detectScanners(\n workspaceRoot: string,\n): Promise<ScannerDetection[]> {\n const scanners: KnownScanner[] = [\"eslint\", \"semgrep\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"];\n\n const results = await Promise.all(\n scanners.map(async (scanner): Promise<ScannerDetection> => {\n // 1. Config file probe (fastest)\n const configProbe = probeConfigFiles(workspaceRoot, scanner);\n if (configProbe.found && configProbe.path) {\n return {\n scanner,\n available: true,\n reason: `config file found: ${configProbe.path.replace(workspaceRoot + \"/\", \"\")}`,\n configPath: configProbe.path,\n };\n }\n\n // 2. Package.json probe \u2014 declared in deps/devDeps, but is it\n // actually installed? Check node_modules/.bin/ for the binary.\n if (probePackageJson(workspaceRoot, scanner)) {\n const binName = SCANNER_SIGNALS[scanner].binaryNames[0];\n const binPath = binName ? join(workspaceRoot, \"node_modules\", \".bin\", binName) : null;\n const installed = binPath !== null && existsSync(binPath);\n return {\n scanner,\n available: installed,\n reason: installed\n ? \"found in package.json and installed\"\n : `found in package.json but not installed (run \\`npm install\\`)`,\n };\n }\n\n // 3. Binary probe (slowest)\n const signals = SCANNER_SIGNALS[scanner];\n for (const bin of signals.binaryNames) {\n if (await probeBinary(bin)) {\n return {\n scanner,\n available: true,\n reason: `binary \"${bin}\" found on PATH`,\n };\n }\n }\n\n return {\n scanner,\n available: false,\n reason: \"no config file, package.json entry, or binary found\",\n };\n }),\n );\n\n return results;\n}\n\n// \u2500\u2500 Monorepo subdirectory probing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Common monorepo directory names that may contain workspace\n * subdirectories. Checked one level deep only.\n */\nconst MONOREPO_DIRS = [\"apps\", \"packages\", \"libs\", \"modules\", \"services\"];\n\n/**\n * Detect scanners in monorepo subdirectories. Probes first-level\n * children of common monorepo directories (apps/, packages/, etc.)\n * and npm workspaces for scanner config files. Returns detections\n * with a `workingDir` pointing to the subdirectory.\n *\n * This catches e.g. `apps/mobile/pubspec.yaml` in a polyglot monorepo\n * where the root-level detector only finds ESLint.\n *\n * @param workspaceRoot Absolute path to the project root.\n * @returns Additional detections from subdirectories (may be empty).\n */\nexport async function detectMonorepoScanners(\n workspaceRoot: string,\n): Promise<ScannerDetection[]> {\n const subdirs = new Set<string>();\n\n // 1. Read npm workspaces from package.json\n try {\n const pkgPath = join(workspaceRoot, \"package.json\");\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n if (Array.isArray(pkg.workspaces)) {\n for (const ws of pkg.workspaces) {\n if (typeof ws === \"string\" && !ws.includes(\"*\")) {\n const full = resolve(workspaceRoot, ws);\n if (existsSync(full)) subdirs.add(full);\n }\n }\n }\n } catch {\n // No package.json or not parseable \u2014 continue\n }\n\n // 2. Scan common monorepo directories one level deep\n for (const dir of MONOREPO_DIRS) {\n const full = join(workspaceRoot, dir);\n try {\n const entries = readdirSync(full, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(full, entry.name));\n }\n }\n } catch {\n // Directory doesn't exist \u2014 skip\n }\n }\n\n if (subdirs.size === 0) return [];\n\n // 3. Probe each subdirectory for scanner config files\n const detections: ScannerDetection[] = [];\n const scanners: KnownScanner[] = [\"eslint\", \"semgrep\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"];\n\n for (const subdir of subdirs) {\n for (const scanner of scanners) {\n const configProbe = probeConfigFiles(subdir, scanner);\n if (!configProbe.found) continue;\n\n // For dart_analyze, also verify the binary is on PATH\n if (scanner === \"dart_analyze\") {\n const hasBinary = await probeBinary(\"dart\");\n if (!hasBinary) continue;\n }\n\n const relDir = subdir.replace(workspaceRoot + \"/\", \"\");\n detections.push({\n scanner,\n available: true,\n reason: `config file found in ${relDir}/`,\n ...(configProbe.path ? { configPath: configProbe.path } : {}),\n workingDir: subdir,\n });\n }\n }\n\n return detections;\n}\n\n// Exported for testing\nexport { SCANNER_SIGNALS, MONOREPO_DIRS };\n", "/**\n * Execute a single scanner CLI and capture its raw output.\n *\n * Each scanner has a fixed invocation that produces the format its\n * adapter expects:\n *\n * - ESLint \u2192 `npx eslint -f json .` (JSON array)\n * - Semgrep \u2192 `semgrep --sarif --quiet .` (SARIF 2.1.0)\n * - Bandit \u2192 `bandit -f json -r . -q` (JSON object)\n * - Stryker \u2192 `npx stryker run` then read `reports/mutation/mutation.json`\n *\n * ESLint and Bandit exit non-zero when findings exist \u2014 that is\n * expected, not an error. The runner captures stdout regardless of\n * exit code for those scanners.\n *\n * Stryker is special: it writes to a file instead of stdout, so we\n * read the output file after the process exits.\n *\n * @module scanner/runner\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { KnownScanner } from \"../adapters/common.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Result of executing a single scanner.\n */\nexport interface ScannerRunResult {\n /** Which scanner was executed. */\n scanner: KnownScanner;\n /** Whether execution completed and produced parseable output. */\n success: boolean;\n /** The scanner's raw output (stdout or file contents). */\n rawOutput: string;\n /** Error message when `success` is false. */\n error?: string;\n /** Wall-clock execution time in milliseconds. */\n durationMs: number;\n}\n\n// \u2500\u2500 Scanner command definitions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface ScannerCommand {\n /** Binary or npx command. */\n command: string;\n /** CLI arguments. */\n args: string[];\n /** Maximum execution time in ms. */\n timeoutMs: number;\n /** If true, non-zero exit is expected when findings exist. */\n nonZeroIsNormal: boolean;\n /** If set, read output from this file instead of stdout. */\n outputFile?: string;\n}\n\nfunction getScannerCommand(\n scanner: KnownScanner,\n workspaceRoot: string,\n): ScannerCommand {\n switch (scanner) {\n case \"eslint\":\n return {\n command: \"npx\",\n args: [\"eslint\", \"-f\", \"json\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n };\n case \"semgrep\":\n return {\n command: \"semgrep\",\n args: [\"--sarif\", \"--quiet\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: false,\n };\n case \"bandit\":\n return {\n command: \"bandit\",\n args: [\"-f\", \"json\", \"-r\", \".\", \"-q\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n };\n case \"stryker\":\n return {\n command: \"npx\",\n args: [\"stryker\", \"run\"],\n timeoutMs: 300_000,\n nonZeroIsNormal: false,\n outputFile: join(workspaceRoot, \"reports\", \"mutation\", \"mutation.json\"),\n };\n case \"dart_analyze\":\n return {\n command: \"dart\",\n args: [\"analyze\", \"--format=json\", \".\"],\n timeoutMs: 120_000,\n nonZeroIsNormal: true, // exits 3 when findings exist\n };\n case \"dotnet_format\":\n return {\n command: \"dotnet\",\n args: [\n \"format\",\n \"--verify-no-changes\",\n \"--report\",\n join(workspaceRoot, \".claude-crap\", \"dotnet-report.json\"),\n ],\n timeoutMs: 120_000,\n nonZeroIsNormal: true,\n outputFile: join(workspaceRoot, \".claude-crap\", \"dotnet-report.json\"),\n };\n }\n}\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Execute a scanner CLI and return its raw output.\n *\n * @param scanner Which scanner to run.\n * @param workspaceRoot Absolute path to the project root (used as cwd).\n * @param options Optional overrides.\n * @returns A {@link ScannerRunResult} with stdout or file output.\n */\nexport function runScanner(\n scanner: KnownScanner,\n workspaceRoot: string,\n options?: { workingDir?: string },\n): Promise<ScannerRunResult> {\n const start = Date.now();\n const cwd = options?.workingDir ?? workspaceRoot;\n const cmd = getScannerCommand(scanner, cwd);\n\n return new Promise((resolve) => {\n execFile(\n cmd.command,\n cmd.args,\n {\n cwd,\n timeout: cmd.timeoutMs,\n maxBuffer: 50 * 1024 * 1024, // 50 MB \u2014 large codebases produce verbose output\n env: { ...process.env, FORCE_COLOR: \"0\" }, // suppress ANSI in output\n },\n (err, stdout, stderr) => {\n const durationMs = Date.now() - start;\n\n // For scanners where non-zero exit means \"findings exist\",\n // we still have valid output in stdout. But if the scanner\n // crashed (e.g. ESLint with no config file), treat it as a\n // real failure even when nonZeroIsNormal is set.\n const isFatalError = cmd.nonZeroIsNormal\n && err\n && (!stdout?.trim() || stderr?.includes(\"Oops!\") || stderr?.includes(\"couldn't find\"));\n\n if (err && (!cmd.nonZeroIsNormal || isFatalError)) {\n // Stryker: check if the output file was written despite the error\n if (cmd.outputFile && existsSync(cmd.outputFile)) {\n try {\n const fileOutput = readFileSync(cmd.outputFile, \"utf-8\");\n resolve({\n scanner,\n success: true,\n rawOutput: fileOutput,\n durationMs,\n });\n return;\n } catch {\n // Fall through to error path\n }\n }\n\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: stderr || (err as Error).message,\n durationMs,\n });\n return;\n }\n\n // For file-based output (Stryker), read from file\n if (cmd.outputFile) {\n if (existsSync(cmd.outputFile)) {\n try {\n const fileOutput = readFileSync(cmd.outputFile, \"utf-8\");\n resolve({\n scanner,\n success: true,\n rawOutput: fileOutput,\n durationMs,\n });\n return;\n } catch (readErr) {\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: `Failed to read output file: ${(readErr as Error).message}`,\n durationMs,\n });\n return;\n }\n }\n resolve({\n scanner,\n success: false,\n rawOutput: \"\",\n error: `Scanner completed but output file not found: ${cmd.outputFile}`,\n durationMs,\n });\n return;\n }\n\n // Stdout-based output\n const output = stdout.trim();\n if (!output) {\n resolve({\n scanner,\n success: true,\n rawOutput: \"[]\", // ESLint returns empty when no files match\n durationMs,\n });\n return;\n }\n\n resolve({\n scanner,\n success: true,\n rawOutput: output,\n durationMs,\n });\n },\n );\n });\n}\n\n// Exported for testing\nexport { getScannerCommand, type ScannerCommand };\n", "/**\n * Bootstrap a scanner for projects that don't have one configured.\n *\n * Detects the project type from workspace signals (package.json,\n * tsconfig.json, pyproject.toml, pom.xml, *.csproj, etc.), installs\n * the appropriate scanner, creates a minimal config file, and runs\n * `autoScan()` to verify and ingest findings immediately.\n *\n * Coverage maps to the five languages the tree-sitter engine supports:\n *\n * - JavaScript / TypeScript \u2192 ESLint (npm install + flat config)\n * - Python \u2192 Bandit (install instructions only \u2014 virtualenv boundary)\n * - Java \u2192 Semgrep (install instructions)\n * - C# \u2192 Semgrep (install instructions)\n * - Unknown \u2192 Semgrep (polyglot fallback)\n *\n * For JS/TS projects the tool runs `npm install --save-dev` and writes\n * an `eslint.config.mjs`. For all other languages it returns manual\n * install instructions rather than executing package managers whose\n * environment assumptions may not hold.\n *\n * @module scanner/bootstrap\n */\n\nimport { existsSync, writeFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport type { Logger } from \"pino\";\nimport type { KnownScanner } from \"../adapters/common.js\";\nimport { adaptScannerOutput } from \"../adapters/index.js\";\nimport { detectScanners } from \"./detector.js\";\nimport { runScanner } from \"./runner.js\";\nimport type { AutoScanResult, ScannerResult } from \"./auto-scan.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detected project type, aligned with tree-sitter supported languages.\n */\nexport type ProjectType =\n | \"javascript\"\n | \"typescript\"\n | \"python\"\n | \"java\"\n | \"csharp\"\n | \"dart\"\n | \"unknown\";\n\n/**\n * A single step in the bootstrap process.\n */\nexport interface BootstrapStep {\n /** What was attempted (e.g. \"install eslint\", \"create eslint.config.mjs\"). */\n action: string;\n /** Whether the step completed successfully. */\n success: boolean;\n /** Human-readable detail (command output, error message, or instruction). */\n detail: string;\n}\n\n/**\n * Complete result of a bootstrap_scanner invocation.\n */\nexport interface BootstrapResult {\n /** Detected project type based on workspace signals. */\n projectType: ProjectType;\n /** Whether a scanner was already configured (detected by detector.ts). */\n alreadyConfigured: boolean;\n /** Which scanners were already available, if any. */\n existingScanners: string[];\n /** Steps executed (or instructions returned) during bootstrap. */\n steps: BootstrapStep[];\n /** The auto-scan result after installation (null if skipped). */\n autoScanResult: AutoScanResult | null;\n /** Whether the overall bootstrap succeeded. */\n success: boolean;\n /** Summary message suitable for display. */\n summary: string;\n}\n\n// \u2500\u2500 Project type detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect the project type from workspace signals.\n *\n * Checks in priority order: TypeScript, JavaScript, Python, Java,\n * C#, then unknown. TypeScript wins over plain JavaScript because\n * `tsconfig.json` implies a superset.\n */\nexport function detectProjectType(workspaceRoot: string): ProjectType {\n const has = (file: string) => existsSync(join(workspaceRoot, file));\n\n // JS/TS detection \u2014 package.json is the anchor\n if (has(\"package.json\")) {\n if (has(\"tsconfig.json\")) return \"typescript\";\n return \"javascript\";\n }\n\n // Python detection\n if (has(\"pyproject.toml\") || has(\"setup.py\") || has(\"requirements.txt\")) {\n return \"python\";\n }\n\n // Java detection\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) {\n return \"java\";\n }\n\n // C# detection\n if (has(\"Directory.Build.props\")) return \"csharp\";\n try {\n const entries = readdirSync(workspaceRoot);\n if (entries.some((e) => e.endsWith(\".csproj\") || e.endsWith(\".sln\"))) {\n return \"csharp\";\n }\n } catch {\n // readdirSync can fail on permissions \u2014 fall through\n }\n\n // Dart / Flutter detection\n if (has(\"pubspec.yaml\")) return \"dart\";\n\n return \"unknown\";\n}\n\n// \u2500\u2500 ESLint config generation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Generate a minimal ESLint flat config (ESLint 9+).\n *\n * @param isTypeScript Include typescript-eslint when true.\n * @returns The config file content as a string.\n */\nexport function generateEslintConfig(isTypeScript: boolean): string {\n if (isTypeScript) {\n return `import js from \"@eslint/js\";\nimport tseslint from \"typescript-eslint\";\n\nexport default tseslint.config(\n js.configs.recommended,\n ...tseslint.configs.recommended,\n {\n ignores: [\n \"dist/\",\n \"node_modules/\",\n \"coverage/\",\n \"**/bundle/\",\n \"**/vendor/\",\n \"**/*.min.js\",\n ],\n },\n);\n`;\n }\n\n return `import js from \"@eslint/js\";\n\nexport default [\n js.configs.recommended,\n {\n ignores: [\n \"dist/\",\n \"node_modules/\",\n \"coverage/\",\n \"**/bundle/\",\n \"**/vendor/\",\n \"**/*.min.js\",\n ],\n },\n];\n`;\n}\n\n// \u2500\u2500 Installation helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run `npm install --save-dev` for the given packages.\n */\nfunction npmInstall(\n workspaceRoot: string,\n packages: string[],\n): Promise<BootstrapStep> {\n return new Promise((resolve) => {\n execFile(\n \"npm\",\n [\"install\", \"--save-dev\", ...packages],\n {\n cwd: workspaceRoot,\n timeout: 120_000,\n env: { ...process.env, FORCE_COLOR: \"0\" },\n },\n (err, stdout, stderr) => {\n if (err) {\n resolve({\n action: `npm install --save-dev ${packages.join(\" \")}`,\n success: false,\n detail: stderr || (err as Error).message,\n });\n return;\n }\n resolve({\n action: `npm install --save-dev ${packages.join(\" \")}`,\n success: true,\n detail: `installed ${packages.join(\", \")}`,\n });\n },\n );\n });\n}\n\n/**\n * Write the ESLint config file to the workspace root.\n * Returns failure if the file already exists.\n */\nfunction writeEslintConfigFile(\n workspaceRoot: string,\n isTypeScript: boolean,\n): BootstrapStep {\n const configPath = join(workspaceRoot, \"eslint.config.mjs\");\n if (existsSync(configPath)) {\n return {\n action: \"create eslint.config.mjs\",\n success: true,\n detail: \"eslint.config.mjs already exists \u2014 skipped\",\n };\n }\n\n try {\n writeFileSync(configPath, generateEslintConfig(isTypeScript), \"utf-8\");\n return {\n action: \"create eslint.config.mjs\",\n success: true,\n detail: `created eslint.config.mjs (${isTypeScript ? \"TypeScript\" : \"JavaScript\"} template)`,\n };\n } catch (err) {\n return {\n action: \"create eslint.config.mjs\",\n success: false,\n detail: (err as Error).message,\n };\n }\n}\n\n// \u2500\u2500 Scanner-to-language mapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Map project type \u2192 recommended scanner and install instructions.\n */\ninterface ScannerRecommendation {\n scanner: KnownScanner;\n canAutoInstall: boolean;\n installInstructions: string;\n}\n\nfunction getRecommendation(projectType: ProjectType): ScannerRecommendation {\n switch (projectType) {\n case \"javascript\":\n case \"typescript\":\n return {\n scanner: \"eslint\",\n canAutoInstall: true,\n installInstructions: \"npm install --save-dev eslint @eslint/js\",\n };\n case \"python\":\n return {\n scanner: \"bandit\",\n canAutoInstall: false,\n installInstructions:\n \"pip install bandit (or: pipx install bandit, poetry add --group dev bandit)\",\n };\n case \"java\":\n return {\n scanner: \"semgrep\",\n canAutoInstall: false,\n installInstructions:\n \"brew install semgrep (or: pip install semgrep, pipx install semgrep)\",\n };\n case \"csharp\":\n return {\n scanner: \"dotnet_format\",\n canAutoInstall: false,\n installInstructions:\n \"Install the .NET SDK: https://dotnet.microsoft.com/download\",\n };\n case \"dart\":\n return {\n scanner: \"dart_analyze\",\n canAutoInstall: false,\n installInstructions:\n \"Install the Dart SDK: https://dart.dev/get-dart (or Flutter SDK which includes Dart)\",\n };\n case \"unknown\":\n return {\n scanner: \"semgrep\",\n canAutoInstall: false,\n installInstructions:\n \"brew install semgrep (or: pip install semgrep, pipx install semgrep)\",\n };\n }\n}\n\n// \u2500\u2500 Main orchestrator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Bootstrap a scanner for the current workspace.\n *\n * 1. Check if a scanner is already configured (short-circuit if so)\n * 2. Detect the project type\n * 3. Install the recommended scanner (or return instructions)\n * 4. Run auto_scan to verify and ingest findings\n *\n * @param workspaceRoot Absolute path to the project root.\n * @param sarifStore Live SARIF store for auto-scan ingestion.\n * @param logger Pino logger for progress reporting.\n */\nexport async function bootstrapScanner(\n workspaceRoot: string,\n sarifStore: SarifStore,\n logger: Logger,\n): Promise<BootstrapResult> {\n // 1. Check existing scanners\n const detections = await detectScanners(workspaceRoot);\n const available = detections.filter((d) => d.available);\n\n // A scanner is truly \"configured\" only if it also has a config\n // file. ESLint in package.json without eslint.config.mjs will crash.\n const eslintNeedsConfig = available.some((d) => d.scanner === \"eslint\")\n && !detections.some((d) => d.scanner === \"eslint\" && d.configPath);\n\n if (available.length > 0 && !eslintNeedsConfig) {\n const existingScanners = available.map((d) => d.scanner);\n logger.info(\n { existingScanners },\n \"bootstrap: scanner(s) already configured \u2014 skipping\",\n );\n return {\n projectType: detectProjectType(workspaceRoot),\n alreadyConfigured: true,\n existingScanners,\n steps: [],\n autoScanResult: null,\n success: true,\n summary: `Scanner(s) already configured: ${existingScanners.join(\", \")}. Run auto_scan to ingest findings.`,\n };\n }\n\n // 2. Detect project type\n const projectType = detectProjectType(workspaceRoot);\n const recommendation = getRecommendation(projectType);\n const steps: BootstrapStep[] = [];\n\n logger.info(\n { projectType, scanner: recommendation.scanner },\n \"bootstrap: detected project type\",\n );\n\n // 3. Install scanner (skip npm install if already in package.json)\n if (recommendation.canAutoInstall) {\n const isTypeScript = projectType === \"typescript\";\n const eslintAlreadyInstalled = available.some((d) => d.scanner === \"eslint\");\n\n if (!eslintAlreadyInstalled) {\n const packages = isTypeScript\n ? [\"eslint\", \"@eslint/js\", \"typescript-eslint\"]\n : [\"eslint\", \"@eslint/js\"];\n const installStep = await npmInstall(workspaceRoot, packages);\n steps.push(installStep);\n if (!installStep.success) {\n // npm install failed \u2014 skip config creation, fall through to result\n return buildResult(projectType, steps, null);\n }\n } else {\n steps.push({\n action: \"npm install eslint\",\n success: true,\n detail: \"eslint already in package.json \u2014 skipped install\",\n });\n }\n\n // Always create config if missing\n const configStep = writeEslintConfigFile(workspaceRoot, isTypeScript);\n steps.push(configStep);\n } else {\n // Python / Java / C# / Unknown: return instructions\n steps.push({\n action: `suggest ${recommendation.scanner} install`,\n success: true,\n detail: recommendation.installInstructions,\n });\n }\n\n // 4. Run scanner directly if installation succeeded (inline scan\n // to avoid circular dependency \u2014 autoScan calls bootstrapScanner)\n const installSucceeded = steps.every((s) => s.success);\n let autoScanResult: AutoScanResult | null = null;\n\n if (installSucceeded && recommendation.canAutoInstall) {\n try {\n const scanStart = Date.now();\n const postDetections = await detectScanners(workspaceRoot);\n const postAvailable = postDetections.filter((d) => d.available);\n const scanResults: ScannerResult[] = [];\n let scanFindings = 0;\n\n const settled = await Promise.allSettled(\n postAvailable.map((d) => runScanner(d.scanner, workspaceRoot)),\n );\n\n for (let i = 0; i < postAvailable.length; i++) {\n const det = postAvailable[i]!;\n const res = settled[i]!;\n\n if (res.status === \"rejected\" || !res.value.success) {\n scanResults.push({\n scanner: det.scanner,\n success: false,\n findingsIngested: 0,\n durationMs: res.status === \"fulfilled\" ? res.value.durationMs : 0,\n error: res.status === \"rejected\"\n ? String(res.reason)\n : res.value.error ?? \"unknown error\",\n });\n continue;\n }\n\n const runResult = res.value;\n let parsed: unknown;\n try { parsed = JSON.parse(runResult.rawOutput); } catch { parsed = runResult.rawOutput; }\n const adapted = adaptScannerOutput(runResult.scanner, parsed);\n const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);\n scanFindings += stats.accepted;\n\n scanResults.push({\n scanner: runResult.scanner,\n success: true,\n findingsIngested: stats.accepted,\n durationMs: runResult.durationMs,\n });\n }\n\n if (scanFindings > 0) await sarifStore.persist();\n\n autoScanResult = {\n detected: postDetections,\n results: scanResults,\n totalFindings: scanFindings,\n totalDurationMs: Date.now() - scanStart,\n };\n } catch (err) {\n logger.warn(\n { err: (err as Error).message },\n \"bootstrap: scan after install failed\",\n );\n }\n }\n\n // 5. Build result\n return buildResult(projectType, steps, autoScanResult, recommendation);\n}\n\n/**\n * Build a BootstrapResult from the collected steps and optional scan result.\n */\nfunction buildResult(\n projectType: ProjectType,\n steps: BootstrapStep[],\n autoScanResult: AutoScanResult | null,\n recommendation?: { scanner: KnownScanner; canAutoInstall: boolean; installInstructions: string },\n): BootstrapResult {\n const success = steps.every((s) => s.success);\n const findings = autoScanResult?.totalFindings ?? 0;\n const scanner = recommendation?.scanner ?? \"unknown\";\n\n let summary: string;\n if (success && autoScanResult) {\n summary = `Configured ${scanner} for ${projectType} project. Scan found ${findings} finding(s).`;\n } else if (success && recommendation && !recommendation.canAutoInstall) {\n summary = `Detected ${projectType} project. Install ${scanner} manually: ${recommendation.installInstructions}`;\n } else if (success) {\n summary = `Configured ${scanner} for ${projectType} project.`;\n } else {\n summary = `Failed to configure ${scanner}. Check the error details in the steps.`;\n }\n\n return {\n projectType,\n alreadyConfigured: false,\n existingScanners: [],\n steps,\n autoScanResult,\n success,\n summary,\n };\n}\n", "/**\n * Cyclomatic complexity scanner.\n *\n * Walks the workspace, analyzes each supported source file with\n * tree-sitter, and emits SARIF findings for functions whose cyclomatic\n * complexity exceeds the configured threshold (`cyclomaticMax`).\n *\n * This scanner is an internal analyzer \u2014 it is NOT a \"known scanner\"\n * in the `KnownScanner` union (eslint/semgrep/bandit/stryker). It\n * bypasses the adapter pipeline and writes SARIF directly via\n * `wrapResultsInSarif()` from the common adapter helpers.\n *\n * Severity mapping:\n * - `warning` \u2014 CC > threshold but < 2\u00D7 threshold\n * - `error` \u2014 CC >= 2\u00D7 threshold (aligns with CRAP index hard block at CC >= 30)\n *\n * @module scanner/complexity-scanner\n */\n\nimport { promises as fs } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { Logger } from \"pino\";\n\nimport { TreeSitterEngine } from \"../ast/tree-sitter-engine.js\";\nimport { detectLanguageFromPath } from \"../ast/language-config.js\";\nimport { wrapResultsInSarif, estimateEffortMinutes } from \"../adapters/common.js\";\nimport { createExclusionFilter } from \"../shared/exclusions.js\";\nimport type { SarifStore } from \"../sarif/sarif-store.js\";\nimport type { SarifLevel } from \"../sarif/sarif-builder.js\";\n\n// Directory exclusions are now centralized in src/shared/exclusions.ts.\n\n/** Hard cap on files to prevent unbounded analysis. */\nconst MAX_FILES = 20_000;\n\n/** SARIF rule ID for cyclomatic complexity violations. */\nconst RULE_ID = \"complexity/cyclomatic-max\";\n\n/** Source tool identifier used in SARIF properties. */\nconst SOURCE_TOOL = \"complexity\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Result of a complexity scan run. */\nexport interface ComplexityScanResult {\n /** Number of source files successfully analyzed. */\n readonly filesScanned: number;\n /** Total number of functions found across all files. */\n readonly functionsAnalyzed: number;\n /** Number of functions that exceeded the threshold. */\n readonly violations: number;\n /** Wall-clock time for the entire scan. */\n readonly durationMs: number;\n}\n\n/** Configuration accepted by the scanner. */\nexport interface ComplexityScanConfig {\n /** Maximum cyclomatic complexity allowed per function. */\n readonly cyclomaticMax: number;\n /** User-defined exclusion patterns from .claude-crap.json. */\n readonly exclude?: ReadonlyArray<string>;\n}\n\n// \u2500\u2500 Scanner \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Scan a workspace for cyclomatic complexity violations.\n *\n * Walks the directory tree, analyzes each source file with the\n * tree-sitter engine, and emits SARIF findings for functions above\n * the configured threshold. Findings are ingested into the provided\n * `SarifStore` and persisted to disk.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @param engine Initialized tree-sitter engine instance.\n * @param sarifStore Live SARIF store to ingest findings into.\n * @param config Scanner configuration (threshold).\n * @param logger Pino logger for progress and error reporting.\n * @returns Summary of what was scanned and found.\n */\nexport async function scanComplexity(\n workspaceRoot: string,\n engine: TreeSitterEngine,\n sarifStore: SarifStore,\n config: ComplexityScanConfig,\n logger: Logger,\n): Promise<ComplexityScanResult> {\n const start = Date.now();\n const threshold = config.cyclomaticMax;\n const errorThreshold = threshold * 2;\n\n // 1. Collect supported source files\n const filter = createExclusionFilter(config.exclude);\n const files = await collectSourceFiles(workspaceRoot, filter);\n logger.info(\n { fileCount: files.length, threshold },\n \"complexity-scanner: starting analysis\",\n );\n\n // 2. Analyze each file and collect violations\n const sarifResults: object[] = [];\n let filesScanned = 0;\n let functionsAnalyzed = 0;\n let violations = 0;\n\n for (const filePath of files) {\n const language = detectLanguageFromPath(filePath);\n if (!language) continue;\n\n try {\n const metrics = await engine.analyzeFile({ filePath, language });\n filesScanned += 1;\n functionsAnalyzed += metrics.functions.length;\n\n for (const fn of metrics.functions) {\n if (fn.cyclomaticComplexity <= threshold) continue;\n\n const level: SarifLevel =\n fn.cyclomaticComplexity >= errorThreshold ? \"error\" : \"warning\";\n\n const relPath = relative(workspaceRoot, filePath);\n\n sarifResults.push({\n ruleId: RULE_ID,\n level,\n message: {\n text: `Function '${fn.name}' has cyclomatic complexity ${fn.cyclomaticComplexity} (threshold: ${threshold})`,\n },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: relPath },\n region: {\n startLine: fn.startLine,\n startColumn: 1,\n endLine: fn.endLine,\n endColumn: 1,\n },\n },\n },\n ],\n properties: {\n sourceTool: SOURCE_TOOL,\n effortMinutes: estimateEffortMinutes(level),\n cyclomaticComplexity: fn.cyclomaticComplexity,\n },\n });\n violations += 1;\n }\n } catch (err) {\n logger.warn(\n { filePath, err: (err as Error).message },\n \"complexity-scanner: failed to analyze file, skipping\",\n );\n }\n }\n\n // 3. Ingest findings into the SARIF store\n if (sarifResults.length > 0) {\n const document = wrapResultsInSarif(\n SOURCE_TOOL as never,\n \"0.1.0\",\n sarifResults,\n );\n sarifStore.ingestRun(document, SOURCE_TOOL);\n await sarifStore.persist();\n }\n\n const durationMs = Date.now() - start;\n logger.info(\n { filesScanned, functionsAnalyzed, violations, durationMs },\n \"complexity-scanner: analysis complete\",\n );\n\n return { filesScanned, functionsAnalyzed, violations, durationMs };\n}\n\n// \u2500\u2500 File walker \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Collect source files from the workspace that the tree-sitter engine\n * can analyze. Uses the shared exclusion filter for directory and file\n * filtering. Only returns files whose extension maps to a supported language.\n */\nasync function collectSourceFiles(\n workspaceRoot: string,\n filter: import(\"../shared/exclusions.js\").ExclusionFilter,\n): Promise<string[]> {\n const files: string[] = [];\n let truncated = false;\n\n async function walk(dir: string): Promise<void> {\n if (truncated) return;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (truncated) return;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (filter.shouldSkipDir(entry.name)) continue;\n await walk(full);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!detectLanguageFromPath(entry.name)) continue;\n const relPath = relative(workspaceRoot, full);\n if (filter.shouldSkipFile(relPath, entry.name)) continue;\n files.push(full);\n if (files.length >= MAX_FILES) {\n truncated = true;\n return;\n }\n }\n }\n\n await walk(workspaceRoot);\n return files;\n}\n", "/**\n * Monorepo project discovery and project-map generation.\n *\n * At plugin boot the host can call {@link discoverProjectMap} to walk\n * a workspace, detect every sub-project's language/framework, pick the\n * right scanner, and probe whether that scanner binary is available on\n * the host PATH. The resulting {@link ProjectMap} is optionally written\n * to `.claude-crap/projects.json` via {@link persistProjectMap} so\n * subsequent boot cycles can skip the discovery work by calling\n * {@link loadProjectMap} first.\n *\n * Detection priority per sub-directory (first match wins):\n * pubspec.yaml \u2192 dart\n * tsconfig.json + package.json \u2192 typescript\n * package.json (no tsconfig) \u2192 javascript\n * pyproject.toml / setup.py / requirements.txt \u2192 python\n * pom.xml / build.gradle* \u2192 java\n * *.csproj / *.sln / Directory.Build.props \u2192 csharp\n * (none of the above) \u2192 unknown\n *\n * Scanner mapping:\n * typescript / javascript \u2192 eslint\n * python \u2192 bandit\n * java / csharp \u2192 semgrep\n * dart \u2192 dart_analyze\n * unknown \u2192 null\n *\n * @module monorepo/project-map\n */\n\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { promises as fs } from \"node:fs\";\nimport { join, basename, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detected language / platform for a workspace sub-project.\n * Mirrors the set supported by the tree-sitter engine plus Dart.\n */\nexport type ProjectType =\n | \"typescript\"\n | \"javascript\"\n | \"python\"\n | \"java\"\n | \"csharp\"\n | \"dart\"\n | \"unknown\";\n\n/**\n * A discovered sub-project within a monorepo workspace.\n */\nexport interface ProjectEntry {\n /** Human-readable name \u2014 the directory's basename (e.g. \"www\", \"mobile\"). */\n readonly name: string;\n /** Relative path from the workspace root (e.g. \"apps/www\"). */\n readonly path: string;\n /** Detected project type based on marker files. */\n readonly type: ProjectType;\n /** Recommended scanner name, or null when the type is unknown. */\n readonly scanner: string | null;\n /** Whether the scanner binary is reachable on the system PATH. */\n readonly scannerAvailable: boolean;\n}\n\n/**\n * Complete snapshot of a workspace's sub-project layout.\n */\nexport interface ProjectMap {\n /** ISO 8601 timestamp when this map was generated. */\n readonly generatedAt: string;\n /** Absolute path to the workspace root that was scanned. */\n readonly workspaceRoot: string;\n /** True when at least one sub-project was discovered. */\n readonly isMonorepo: boolean;\n /** Discovered sub-projects. Empty for single-project workspaces. */\n readonly projects: ProjectEntry[];\n}\n\n// \u2500\u2500 Internal constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * First-level directories that conventionally contain sub-projects in\n * popular monorepo layouts (Nx, Turborepo, Rush, Lerna, custom).\n */\nconst MONOREPO_DIRS = [\"apps\", \"packages\", \"libs\", \"modules\", \"services\"] as const;\n\n/**\n * Scanner recommended for each project type. `null` means no scanner\n * mapping is defined for the type (only \"unknown\" falls here).\n */\nconst SCANNER_FOR_TYPE: Record<ProjectType, string | null> = {\n typescript: \"eslint\",\n javascript: \"eslint\",\n python: \"bandit\",\n java: \"semgrep\",\n csharp: \"dotnet_format\",\n dart: \"dart_analyze\",\n unknown: null,\n};\n\n/**\n * The binary name to probe for each scanner. Binary availability is\n * checked with `which` via `execFile`, the same approach used in\n * `scanner/detector.ts`.\n */\nconst BINARY_FOR_SCANNER: Record<string, string> = {\n eslint: \"eslint\",\n bandit: \"bandit\",\n semgrep: \"semgrep\",\n dart_analyze: \"dart\",\n dotnet_format: \"dotnet\",\n};\n\n// \u2500\u2500 Binary probe \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Resolve whether the given binary name is reachable on the system\n * PATH. Uses `which` via `execFile` with a short timeout so boot\n * latency stays bounded.\n *\n * @param binaryName The executable name to look up (e.g. \"eslint\").\n * @returns True when `which` exits with code 0.\n */\nfunction probeBinary(binaryName: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\"which\", [binaryName], { timeout: 5_000 }, (err) => {\n resolve(err === null);\n });\n });\n}\n\n// \u2500\u2500 Project type detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Detect the dominant project type of a single directory by inspecting\n * well-known marker files. Checks are ordered so the most specific\n * signal wins (pubspec.yaml before tsconfig.json, tsconfig.json before\n * bare package.json, etc.).\n *\n * The function is synchronous because it only performs `existsSync` and\n * one `readdirSync` call (for C# extension scanning), keeping the\n * discovery loop fast and free of unnecessary Promise allocation.\n *\n * @param dir Absolute path to the directory to inspect.\n * @returns The detected {@link ProjectType}.\n */\nfunction detectProjectType(dir: string): ProjectType {\n const has = (file: string): boolean => existsSync(join(dir, file));\n\n // Dart / Flutter \u2014 check before JS because some Flutter projects also\n // have a package.json for web sub-packages.\n if (has(\"pubspec.yaml\")) return \"dart\";\n\n // JS / TS \u2014 tsconfig.json implies TypeScript superset.\n if (has(\"package.json\")) {\n if (has(\"tsconfig.json\")) return \"typescript\";\n return \"javascript\";\n }\n\n // Python\n if (has(\"pyproject.toml\") || has(\"setup.py\") || has(\"requirements.txt\")) {\n return \"python\";\n }\n\n // Java (Gradle and Maven)\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) {\n return \"java\";\n }\n\n // C# \u2014 check the well-known single-file marker first, then scan for\n // per-project extension files (.csproj / .sln) at this level only.\n if (has(\"Directory.Build.props\")) return \"csharp\";\n try {\n const entries = readdirSync(dir);\n if (entries.some((e) => e.endsWith(\".csproj\") || e.endsWith(\".sln\"))) {\n return \"csharp\";\n }\n } catch {\n // Permission error or symlink loop \u2014 treat as unknown.\n }\n\n return \"unknown\";\n}\n\n// \u2500\u2500 Subdirectory collection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Normalise an npm workspaces value (which can be a plain string array\n * or an object `{ packages: string[] }`) into a flat array of patterns.\n *\n * @param workspaces The raw value of `package.json#workspaces`.\n * @returns Array of workspace glob patterns (may be empty).\n */\nfunction extractWorkspacePatterns(workspaces: unknown): string[] {\n if (Array.isArray(workspaces)) {\n return workspaces.filter((v): v is string => typeof v === \"string\");\n }\n if (\n workspaces !== null &&\n typeof workspaces === \"object\" &&\n \"packages\" in workspaces &&\n Array.isArray((workspaces as { packages: unknown }).packages)\n ) {\n return ((workspaces as { packages: unknown[] }).packages).filter(\n (v): v is string => typeof v === \"string\",\n );\n }\n return [];\n}\n\n/**\n * Expand a single workspace glob pattern into matching absolute paths.\n *\n * Only supports the common `dir/*` form (one trailing `*`) and plain\n * paths (no glob at all). Full glob engines are deliberately avoided to\n * keep the module dependency-free.\n *\n * @param workspaceRoot Absolute workspace root.\n * @param pattern A workspace pattern such as `\"packages/*\"` or `\"apps/web\"`.\n * @returns Absolute paths of matching directories that exist on disk.\n */\nfunction expandWorkspacePattern(\n workspaceRoot: string,\n pattern: string,\n): string[] {\n if (pattern.endsWith(\"/*\")) {\n // Glob: list one level of the parent directory.\n const parentDir = join(workspaceRoot, pattern.slice(0, -2));\n try {\n const entries = readdirSync(parentDir, { withFileTypes: true });\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith(\".\"))\n .map((e) => join(parentDir, e.name));\n } catch {\n return [];\n }\n }\n\n // Plain path \u2014 verify it exists and is a directory.\n const full = resolve(workspaceRoot, pattern);\n try {\n const entries = readdirSync(full, { withFileTypes: true });\n // readdirSync succeeds only for directories; if we got here it exists.\n void entries; // suppress unused-variable lint\n return [full];\n } catch {\n return [];\n }\n}\n\n/**\n * Collect all candidate sub-project absolute paths for the given\n * workspace root. Sources (deduplicated):\n *\n * 1. npm `workspaces` field in root `package.json` (both array and\n * object-with-packages formats; glob patterns are expanded one\n * level deep with `readdirSync`).\n * 2. One-level-deep subdirectories of conventional monorepo folders\n * (`apps/`, `packages/`, `libs/`, `modules/`, `services/`).\n *\n * Hidden directories (names starting with `.`) are always skipped.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns De-duplicated set of absolute sub-project paths.\n */\nfunction collectSubdirectories(\n workspaceRoot: string,\n extraDirs?: ReadonlyArray<string>,\n): Set<string> {\n const subdirs = new Set<string>();\n\n // 1. npm workspaces\n const pkgPath = join(workspaceRoot, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as Record<string, unknown>;\n const patterns = extractWorkspacePatterns(pkg[\"workspaces\"]);\n for (const pattern of patterns) {\n for (const absPath of expandWorkspacePattern(workspaceRoot, pattern)) {\n subdirs.add(absPath);\n }\n }\n } catch {\n // Malformed JSON or read error \u2014 skip npm workspaces source.\n }\n }\n\n // 2. User-configured projectDirs from .claude-crap.json (highest priority).\n // These can be parent directories scanned one level deep (e.g. \"apps\")\n // or direct project paths (e.g. \"tools/cli\").\n if (extraDirs && extraDirs.length > 0) {\n for (const dir of extraDirs) {\n const absDir = resolve(workspaceRoot, dir);\n if (!existsSync(absDir)) continue;\n\n // If the directory itself has a project marker, treat it as a project.\n const hasMarker = PROJECT_MARKERS.some((m) => existsSync(join(absDir, m)));\n if (hasMarker) {\n subdirs.add(absDir);\n continue;\n }\n\n // Otherwise scan one level deep (it's a parent directory like \"apps\").\n try {\n const entries = readdirSync(absDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(absDir, entry.name));\n }\n }\n } catch {\n // Not readable \u2014 skip.\n }\n }\n }\n\n // 3. Conventional monorepo directories scanned one level deep.\n // Skipped for directories already covered by user config.\n const configuredDirNames = new Set(extraDirs?.map((d) => d.split(\"/\")[0]) ?? []);\n for (const dir of MONOREPO_DIRS) {\n if (configuredDirNames.has(dir)) continue; // User config takes precedence\n const parentDir = join(workspaceRoot, dir);\n try {\n const entries = readdirSync(parentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n subdirs.add(join(parentDir, entry.name));\n }\n }\n } catch {\n // Directory absent \u2014 skip.\n }\n }\n\n return subdirs;\n}\n\n/** Files that indicate a directory is a project root. */\nconst PROJECT_MARKERS = [\n \"package.json\", \"pubspec.yaml\", \"pyproject.toml\", \"setup.py\",\n \"pom.xml\", \"build.gradle\", \"build.gradle.kts\", \"Directory.Build.props\",\n];\n\n// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Discover all sub-projects in the given workspace and return a fully\n * populated {@link ProjectMap}.\n *\n * The function:\n * 1. Reads `package.json#workspaces` (supports both array and object\n * `{ packages: [...] }` formats) and resolves glob patterns.\n * 2. Also scans `apps/`, `packages/`, `libs/`, `modules/`, and\n * `services/` one level deep (mirrors `detectMonorepoScanners`).\n * 3. De-duplicates the collected paths.\n * 4. Detects the project type for each subdirectory.\n * 5. Maps project type to a recommended scanner.\n * 6. Probes scanner binary availability via `which`.\n *\n * When no sub-projects are found (single-project workspace) `projects`\n * is an empty array and `isMonorepo` is false.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns The generated {@link ProjectMap}.\n */\nexport async function discoverProjectMap(\n workspaceRoot: string,\n options?: { projectDirs?: ReadonlyArray<string> },\n): Promise<ProjectMap> {\n const subdirs = collectSubdirectories(workspaceRoot, options?.projectDirs);\n\n // Cache binary probe results so each unique scanner is only probed once.\n const binaryCache = new Map<string, Promise<boolean>>();\n\n const probeScanner = (scanner: string): Promise<boolean> => {\n const binaryName = BINARY_FOR_SCANNER[scanner];\n if (binaryName === undefined) return Promise.resolve(false);\n\n const cached = binaryCache.get(scanner);\n if (cached !== undefined) return cached;\n\n const probe = probeBinary(binaryName);\n binaryCache.set(scanner, probe);\n return probe;\n };\n\n const projectEntries = await Promise.all(\n [...subdirs].map(async (absPath): Promise<ProjectEntry> => {\n const relPath = absPath.replace(workspaceRoot + \"/\", \"\");\n const type = detectProjectType(absPath);\n const scanner = SCANNER_FOR_TYPE[type];\n const scannerAvailable =\n scanner !== null ? await probeScanner(scanner) : false;\n\n return {\n name: basename(absPath),\n path: relPath,\n type,\n scanner,\n scannerAvailable,\n };\n }),\n );\n\n // Sort deterministically by relative path so the output is stable\n // across re-runs regardless of readdirSync ordering.\n projectEntries.sort((a, b) => a.path.localeCompare(b.path));\n\n return {\n generatedAt: new Date().toISOString(),\n workspaceRoot,\n isMonorepo: projectEntries.length > 0,\n projects: projectEntries,\n };\n}\n\n/**\n * Write the project map to `.claude-crap/projects.json` under the given\n * workspace root. The `.claude-crap/` directory is created if it does\n * not already exist.\n *\n * The file is written atomically via `fs.writeFile` (Node's default\n * behaviour on POSIX is to truncate-and-rewrite, which is safe for the\n * sizes expected here).\n *\n * @param map The {@link ProjectMap} to serialise.\n * @param workspaceRoot Absolute path to the workspace root.\n */\nexport async function persistProjectMap(\n map: ProjectMap,\n workspaceRoot: string,\n): Promise<void> {\n const dir = join(workspaceRoot, \".claude-crap\");\n await fs.mkdir(dir, { recursive: true });\n const filePath = join(dir, \"projects.json\");\n await fs.writeFile(filePath, JSON.stringify(map, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Read a previously persisted {@link ProjectMap} from\n * `.claude-crap/projects.json`. Returns `null` when the file is absent\n * or cannot be parsed, so callers can fall back to\n * {@link discoverProjectMap} without special-casing errors.\n *\n * This function is intentionally synchronous so it can be called during\n * plugin boot before the async event loop is fully initialised.\n *\n * @param workspaceRoot Absolute path to the workspace root.\n * @returns The cached {@link ProjectMap}, or `null`.\n */\nexport function loadProjectMap(workspaceRoot: string): ProjectMap | null {\n const filePath = join(workspaceRoot, \".claude-crap\", \"projects.json\");\n if (!existsSync(filePath)) return null;\n\n try {\n const raw = readFileSync(filePath, \"utf-8\");\n const parsed = JSON.parse(raw) as ProjectMap;\n\n // Minimal structural validation \u2014 guard against truncated writes.\n if (\n typeof parsed.generatedAt !== \"string\" ||\n typeof parsed.workspaceRoot !== \"string\" ||\n typeof parsed.isMonorepo !== \"boolean\" ||\n !Array.isArray(parsed.projects)\n ) {\n return null;\n }\n\n return parsed;\n } catch {\n return null;\n }\n}\n", "/**\n * JSON Schema (Draft-07) definitions for every tool exposed by the MCP server.\n *\n * Each schema uses `enum`, `pattern`, `minimum`, `maximum`, `oneOf` and\n * `additionalProperties: false` to eliminate schema hallucinations from the\n * LLM. The MCP SDK automatically validates tool-call inputs against these\n * schemas before invoking the handler \u2014 any drift produces a deterministic\n * error that the agent can consume and correct.\n *\n * These `description` fields are read by the LLM at tool-listing time and\n * become part of the agent's context, so they must be precise, imperative,\n * and never speculative. Keep them short but actionable.\n *\n * @module schemas/tool-schemas\n */\n\n// The MCP SDK consumes these as the `inputSchema` field of a Tool. We type\n// them with `as const` so TypeScript infers literal types and the MCP SDK\n// accepts them without runtime casting.\n\n/**\n * Schema for the `compute_crap` tool. Returns a CRAP score for a single\n * function and a block decision against the configured threshold.\n */\nexport const computeCrapSchema = {\n type: \"object\",\n description:\n \"Compute the CRAP (Change Risk Anti-Patterns) index for a single function. Returns the score and whether it exceeds the configured threshold. A blocked result means the function must be decomposed or covered by more tests before the Stop quality gate will pass.\",\n properties: {\n cyclomaticComplexity: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\n description: \"Cyclomatic complexity of the function (number of linearly independent paths).\",\n },\n coveragePercent: {\n type: \"number\",\n minimum: 0,\n maximum: 100,\n description: \"Test coverage percentage for the function, in the range [0, 100].\",\n },\n functionName: {\n type: \"string\",\n pattern: \"^[A-Za-z_$][A-Za-z0-9_$.:<>]*$\",\n minLength: 1,\n maxLength: 256,\n description: \"Fully qualified name of the function under analysis, used for SARIF traceability.\",\n },\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n description: \"Absolute or workspace-relative path to the source file that contains the function.\",\n },\n },\n required: [\"cyclomaticComplexity\", \"coveragePercent\", \"functionName\", \"filePath\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `compute_tdr` tool. Returns a Technical Debt Ratio and a\n * maintainability letter rating for a scope (project, module, or file).\n */\nexport const computeTdrSchema = {\n type: \"object\",\n description:\n \"Compute the Technical Debt Ratio (TDR) for a scope and return the maintainability letter rating (A..E). Rating E always halts the workflow regardless of the configured tolerance. Use this after aggregating remediation estimates from SARIF findings.\",\n properties: {\n remediationMinutes: {\n type: \"number\",\n minimum: 0,\n maximum: 10_000_000,\n description: \"Total estimated remediation effort in minutes, summed across every finding in the scope.\",\n },\n totalLinesOfCode: {\n type: \"integer\",\n minimum: 1,\n maximum: 100_000_000,\n description: \"Physical lines of code in the scope (project, module, or file).\",\n },\n scope: {\n type: \"string\",\n enum: [\"project\", \"module\", \"file\"],\n description: \"Aggregation scope for the TDR computation.\",\n },\n },\n required: [\"remediationMinutes\", \"totalLinesOfCode\", \"scope\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `analyze_file_ast` tool. Returns deterministic AST\n * metrics (LOC, cyclomatic complexity, node counts) for a source file.\n */\nexport const analyzeFileAstSchema = {\n type: \"object\",\n description:\n \"Parse a source file with tree-sitter and return deterministic metrics (lines of code, cyclomatic complexity per function, top-level node counts). Prefer this tool over reading the file directly \u2014 it is faster and will not bloat the agent context.\",\n properties: {\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n // The lookahead pattern rejects any path traversal (`../`) to prevent\n // the LLM from reading files outside the workspace. Any absolute path\n // that does not contain `../` is still allowed.\n pattern: \"^(?!.*\\\\.\\\\./).*$\",\n description: \"Path to the file to analyze. Paths containing `../` are rejected to prevent workspace escape.\",\n },\n language: {\n type: \"string\",\n enum: [\"csharp\", \"javascript\", \"typescript\", \"python\", \"java\"],\n description: \"Source language of the file. Determines which tree-sitter grammar to load.\",\n },\n },\n required: [\"filePath\", \"language\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `score_project` tool. Aggregates the latest SARIF\n * report and the workspace size into a single project score with\n * Maintainability / Reliability / Security letter grades, an overall\n * grade, the dashboard URL (when running), and the SARIF report path.\n */\nexport const scoreProjectSchema = {\n type: \"object\",\n description:\n \"Compute the aggregate project score (Maintainability / Reliability / Security / Overall A..E), and return both a chat-friendly Markdown summary and a structured JSON snapshot. Includes the local dashboard URL and the consolidated SARIF report path so the user can drill in without opening any extra tooling.\",\n properties: {\n format: {\n type: \"string\",\n enum: [\"markdown\", \"json\", \"both\"],\n description:\n \"Output format. `markdown` returns only the chat summary, `json` returns only the structured snapshot, `both` (default) returns both as separate content blocks.\",\n },\n scope: {\n type: \"string\",\n description: \"Optional project name from the project map. When provided, the score is computed only for files within that project's subtree. Omit to score the entire workspace.\",\n },\n },\n required: [],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `list_projects` tool. Returns the discovered sub-projects\n * in the workspace, or an empty list for single-project workspaces.\n */\nexport const listProjectsSchema = {\n type: \"object\",\n description: \"List all discovered sub-projects in the workspace. In a monorepo, returns each sub-project with its type, path, and recommended scanner. In a single-project workspace, returns an empty list.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `require_test_harness` tool. Checks whether a production\n * source file has an accompanying test file in any of the conventional\n * locations the resolver supports (sibling `.test.`, `__tests__/`, mirror\n * tree, Python `test_` prefix).\n */\nexport const requireTestHarnessSchema = {\n type: \"object\",\n description:\n \"Check whether a production source file has a matching test file. Returns the first existing test path, or the full list of paths the resolver probed when none exists. Use this BEFORE writing any functional code \u2014 the CLAUDE.md Golden Rule requires a test harness to exist first.\",\n properties: {\n filePath: {\n type: \"string\",\n minLength: 1,\n maxLength: 4096,\n pattern: \"^(?!.*\\\\.\\\\./).*$\",\n description:\n \"Path to the production file. Paths containing `../` are rejected to prevent workspace escape.\",\n },\n },\n required: [\"filePath\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `ingest_scanner_output` tool. Accepts a scanner\n * identifier (Semgrep, ESLint, Bandit, Stryker) plus that scanner's\n * native output (SARIF or JSON), routes the input through the\n * matching adapter in `src/adapters/`, and persists the normalized\n * SARIF 2.1.0 document in the store.\n *\n * This tool is the preferred path for ingesting scanner output that\n * is not already SARIF \u2014 `ingest_sarif` remains the right choice\n * when you already have a SARIF document and just need deduplication.\n */\nexport const ingestScannerOutputSchema = {\n type: \"object\",\n description:\n \"Ingest a scanner's native output (Semgrep SARIF, ESLint JSON, Bandit JSON, or Stryker JSON), route it through the matching adapter, enrich every finding with an effort estimate, and persist the normalized SARIF 2.1.0 document. Prefer this tool over `ingest_sarif` whenever the scanner does not emit SARIF natively.\",\n properties: {\n scanner: {\n type: \"string\",\n enum: [\"semgrep\", \"eslint\", \"bandit\", \"stryker\", \"dart_analyze\", \"dotnet_format\"],\n description: \"Identifier of the producing scanner.\",\n },\n rawOutput: {\n description:\n \"The scanner's native output. Accepts either a JSON string (as produced by the scanner's CLI) or a pre-parsed JSON object / array.\",\n oneOf: [{ type: \"string\" }, { type: \"object\" }, { type: \"array\" }],\n },\n },\n required: [\"scanner\", \"rawOutput\"],\n additionalProperties: false,\n} as const;\n\n/**\n * Schema for the `ingest_sarif` tool. Accepts a raw SARIF 2.1.0 document\n * from an external scanner, deduplicates against the internal store, and\n * normalizes the output into claude-crap's canonical format.\n */\n/**\n * Schema for the `auto_scan` tool. Auto-detects available scanners\n * in the workspace, runs them, and ingests findings into the SARIF store.\n */\n/**\n * Schema for the `bootstrap_scanner` tool. Detects project type,\n * installs the appropriate scanner, creates config files, and runs\n * auto_scan to verify.\n */\nexport const bootstrapScannerSchema = {\n type: \"object\",\n description:\n \"Detect the project type (JavaScript, TypeScript, Python, Java, C#), install the appropriate scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create a minimal config file, and run auto_scan to verify. Skips installation if a scanner is already configured. Use this when auto_scan finds no scanners and quality grades are vacuously A.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\nexport const autoScanSchema = {\n type: \"object\",\n description:\n \"Auto-detect available scanners (ESLint, Semgrep, Bandit, Stryker) in the workspace, execute them, and ingest findings into the SARIF store. Returns detection results, per-scanner execution stats, and total findings ingested. Call this to populate findings without manual scanner invocation.\",\n properties: {},\n required: [],\n additionalProperties: false,\n} as const;\n\nexport const ingestSarifSchema = {\n type: \"object\",\n description:\n \"Ingest a raw SARIF 2.1.0 report produced by an external scanner (Semgrep, ESLint, Bandit, Stryker, etc.), deduplicate it against the internal store, and return the normalized document. The agent should call this once per scanner invocation, not once per finding.\",\n properties: {\n sarifDocument: {\n type: \"object\",\n description: \"A full SARIF 2.1.0 document with `version` and `runs` keys.\",\n properties: {\n version: { type: \"string\", enum: [\"2.1.0\"] },\n $schema: { type: \"string\" },\n runs: { type: \"array\", minItems: 1 },\n },\n required: [\"version\", \"runs\"],\n },\n sourceTool: {\n type: \"string\",\n pattern: \"^[a-zA-Z0-9._-]{1,64}$\",\n description: \"Stable identifier of the tool that produced the report (`semgrep`, `eslint`, `bandit`, ...).\",\n },\n },\n required: [\"sarifDocument\", \"sourceTool\"],\n additionalProperties: false,\n} as const;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,QAAsB,cAAtB,MAAiC;;AAAjC,YAAA,cAAA;AAOa,YAAA,aAAa;AAE1B,QAAa,OAAb,cAA0B,YAAW;MAEnC,YAAY,GAAS;AACnB,cAAK;AACL,YAAI,CAAC,QAAA,WAAW,KAAK,CAAC;AAAG,gBAAM,IAAI,MAAM,0CAA0C;AACnF,aAAK,MAAM;MACb;MAEA,WAAQ;AACN,eAAO,KAAK;MACd;MAEA,WAAQ;AACN,eAAO;MACT;MAEA,IAAI,QAAK;AACP,eAAO,EAAC,CAAC,KAAK,GAAG,GAAG,EAAC;MACvB;;AAlBF,YAAA,OAAA;AAqBA,QAAa,QAAb,cAA2B,YAAW;MAKpC,YAAY,MAAkC;AAC5C,cAAK;AACL,aAAK,SAAS,OAAO,SAAS,WAAW,CAAC,IAAI,IAAI;MACpD;MAEA,WAAQ;AACN,eAAO,KAAK;MACd;MAEA,WAAQ;AACN,YAAI,KAAK,OAAO,SAAS;AAAG,iBAAO;AACnC,cAAM,OAAO,KAAK,OAAO,CAAC;AAC1B,eAAO,SAAS,MAAM,SAAS;MACjC;MAEA,IAAI,MAAG;;AACL,gBAAO,KAAC,KAAK,UAAI,QAAA,OAAA,SAAA,KAAT,KAAK,OAAS,KAAK,OAAO,OAAO,CAAC,GAAW,MAAgB,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE;MACrF;MAEA,IAAI,QAA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AAAA,CAAI;AACjF,MAAI,eAAe,SAAS,IAAI,OAAO;AACrC,YAAQ,OAAO,MAAM,IAAI,QAAQ,IAAI;AAAA,EACvC;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;",
6
6
  "names": ["UsedValueState", "Type", "DataType", "_a", "resolve", "resolve", "relative", "Ajv", "logger", "DiscrError", "Ajv", "mapSeverity", "buildSarifResult", "buildSarifResult", "mapSeverity", "fs", "dirname", "join", "resolve", "fileURLToPath", "fs", "resolve", "fs", "logger", "dirname", "fileURLToPath", "resolve", "fs", "join", "walk", "fs", "join", "walk", "fs", "join", "fs", "dirname", "isAbsolute", "join", "resolve", "isAbsolute", "resolve", "join", "fs", "dirname", "readFileSync", "join", "raw", "fs", "dirname", "isAbsolute", "join", "relative", "resolve", "sep", "existsSync", "join", "existsSync", "readFileSync", "join", "resolve", "execFile", "readFileSync", "existsSync", "join", "resolve", "existsSync", "writeFileSync", "readdirSync", "join", "execFile", "existsSync", "join", "readdirSync", "resolve", "execFile", "writeFileSync", "logger", "fs", "join", "relative", "logger", "relative", "walk", "fs", "join", "logger", "existsSync", "join", "existsSync", "readFileSync", "readdirSync", "fs", "join", "basename", "resolve", "execFile", "MONOREPO_DIRS", "probeBinary", "detectProjectType", "join", "logger"]
7
7
  }