diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/pattern.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..f8ccdf295021293823614c88977e2e5708e8f601 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/pattern.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const code_1 = require("../code"); +const codegen_1 = require("../../compile/codegen"); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, +}; +const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); + }, +}; +exports.default = def; +//# sourceMappingURL=pattern.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/required.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/required.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9ec186fa1db430cb146a3b7588d74453d259e238 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/required.js.map @@ -0,0 +1 @@ +{"version":3,"file":"required.js","sourceRoot":"","sources":["../../../lib/vocabularies/validation/required.ts"],"names":[],"mappings":";;AAEA,kCAMgB;AAChB,mDAAkE;AAClE,6CAAkD;AAQlD,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,aAAG,EAAA,gCAAgC,eAAe,GAAG;IAC/F,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,eAAe,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,qBAAqB,eAAe,GAAG;CAClF,CAAA;AAED,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,UAAU;IACnB,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,IAAI;IACX,KAAK;IACL,IAAI,CAAC,GAAe;QAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;QACtD,MAAM,EAAC,IAAI,EAAC,GAAG,EAAE,CAAA;QACjB,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAM;QACzC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,CAAA;QAClD,IAAI,EAAE,CAAC,SAAS;YAAE,aAAa,EAAE,CAAA;;YAC5B,eAAe,EAAE,CAAA;QAEtB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,CAAC,UAAU,CAAA;YACzC,MAAM,EAAC,iBAAiB,EAAC,GAAG,GAAG,CAAC,EAAE,CAAA;YAClC,KAAK,MAAM,WAAW,IAAI,MAAM,EAAE,CAAC;gBACjC,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,WAAW,CAAC,MAAK,SAAS,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;oBAC9E,MAAM,UAAU,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,GAAG,EAAE,CAAC,aAAa,CAAA;oBACzD,MAAM,GAAG,GAAG,sBAAsB,WAAW,wBAAwB,UAAU,oBAAoB,CAAA;oBACnG,IAAA,sBAAe,EAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;gBAClD,CAAC;YACH,CAAC;QACH,CAAC;QAED,SAAS,aAAa;YACpB,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;gBACrB,GAAG,CAAC,UAAU,CAAC,aAAG,EAAE,eAAe,CAAC,CAAA;YACtC,CAAC;iBAAM,CAAC;gBACN,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;oBAC1B,IAAA,6BAAsB,EAAC,GAAG,EAAE,IAAI,CAAC,CAAA;gBACnC,CAAC;YACH,CAAC;QACH,CAAC;QAED,SAAS,eAAe;YACtB,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;YAClC,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;gBACrB,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;gBACpC,GAAG,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAA;gBAC7D,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;YACf,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,EAAE,CAAC,IAAA,uBAAgB,EAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;gBAC9C,IAAA,wBAAiB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAA;gBAC/B,GAAG,CAAC,IAAI,EAAE,CAAA;YACZ,CAAC;QACH,CAAC;QAED,SAAS,eAAe;YACtB,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,UAAkB,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC7C,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,IAAI,EAAC,CAAC,CAAA;gBACtC,GAAG,CAAC,EAAE,CAAC,IAAA,uBAAgB,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;YAClF,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,SAAS,gBAAgB,CAAC,OAAa,EAAE,KAAW;YAClD,GAAG,CAAC,SAAS,CAAC,EAAC,eAAe,EAAE,OAAO,EAAC,CAAC,CAAA;YACzC,GAAG,CAAC,KAAK,CACP,OAAO,EACP,UAAkB,EAClB,GAAG,EAAE;gBACH,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,qBAAc,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAA;gBACzE,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,KAAK,CAAC,EAAE,GAAG,EAAE;oBACtB,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,KAAK,EAAE,CAAA;gBACb,CAAC,CAAC,CAAA;YACJ,CAAC,EACD,aAAG,CACJ,CAAA;QACH,CAAC;IACH,CAAC;CACF,CAAA;AAED,kBAAe,GAAG,CAAA"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7c241b984a6b32f02aab471e5e7e378c61891b7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/dist/vocabularies/validation/uniqueItems.d.ts @@ -0,0 +1,9 @@ +import type { CodeKeywordDefinition, ErrorObject } from "../../types"; +export type UniqueItemsError = ErrorObject<"uniqueItems", { + i: number; + j: number; +}, boolean | { + $data: string; +}>; +declare const def: CodeKeywordDefinition; +export default def; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/code.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d4de6149f9451273ae7e3ca547cb69baed7877c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/code.ts @@ -0,0 +1,169 @@ +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export abstract class _CodeOrName { + abstract readonly str: string + abstract readonly names: UsedNames + abstract toString(): string + abstract emptyStr(): boolean +} + +export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i + +export class Name extends _CodeOrName { + readonly str: string + constructor(s: string) { + super() + if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") + this.str = s + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + return false + } + + get names(): UsedNames { + return {[this.str]: 1} + } +} + +export class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[] + private _str?: string + private _names?: UsedNames + + constructor(code: string | readonly CodeItem[]) { + super() + this._items = typeof code === "string" ? [code] : code + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + if (this._items.length > 1) return false + const item = this._items[0] + return item === "" || item === '""' + } + + get str(): string { + return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, "")) + } + + get names(): UsedNames { + return (this._names ??= this._items.reduce((names: UsedNames, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 + return names + }, {})) + } +} + +export type CodeItem = Name | string | number | boolean | null + +export type UsedNames = Record + +export type Code = _Code | Name + +export type SafeExpr = Code | number | boolean | null + +export const nil = new _Code("") + +type CodeArg = SafeExpr | string | undefined + +export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code { + const code: CodeItem[] = [strs[0]] + let i = 0 + while (i < args.length) { + addCodeArg(code, args[i]) + code.push(strs[++i]) + } + return new _Code(code) +} + +const plus = new _Code("+") + +export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code { + const expr: CodeItem[] = [safeStringify(strs[0])] + let i = 0 + while (i < args.length) { + expr.push(plus) + addCodeArg(expr, args[i]) + expr.push(plus, safeStringify(strs[++i])) + } + optimize(expr) + return new _Code(expr) +} + +export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void { + if (arg instanceof _Code) code.push(...arg._items) + else if (arg instanceof Name) code.push(arg) + else code.push(interpolate(arg)) +} + +function optimize(expr: CodeItem[]): void { + let i = 1 + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]) + if (res !== undefined) { + expr.splice(i - 1, 3, res) + continue + } + expr[i++] = "+" + } + i++ + } +} + +function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { + if (b === '""') return a + if (a === '""') return b + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') return + if (typeof b != "string") return `${a.slice(0, -1)}${b}"` + if (b[0] === '"') return a.slice(0, -1) + b.slice(1) + return + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` + return +} + +export function strConcat(c1: Code, c2: Code): Code { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` +} + +// TODO do not allow arrays here +function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x) +} + +export function stringify(x: unknown): Code { + return new _Code(safeStringify(x)) +} + +export function safeStringify(x: unknown): string { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029") +} + +export function getProperty(key: Code | string | number): Code { + return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]` +} + +//Does best effort to format the name properly +export function getEsmExportName(key: Code | string | number): Code { + if (typeof key == "string" && IDENTIFIER.test(key)) { + return new _Code(`${key}`) + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`) +} + +export function regexpCode(rx: RegExp): Code { + return new _Code(rx.toString()) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a6d1ee58c106245ba8a1b56f929fe3a23f337b8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/index.ts @@ -0,0 +1,852 @@ +import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope" +import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code" +import {Scope, varKinds} from "./scope" + +export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code" +export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope" + +// type for expressions that can be safely inserted in code without quotes +export type SafeExpr = Code | number | boolean | null + +// type that is either Code of function that adds code to CodeGen instance using its methods +export type Block = Code | (() => void) + +export const operators = { + GT: new _Code(">"), + GTE: new _Code(">="), + LT: new _Code("<"), + LTE: new _Code("<="), + EQ: new _Code("==="), + NEQ: new _Code("!=="), + NOT: new _Code("!"), + OR: new _Code("||"), + AND: new _Code("&&"), + ADD: new _Code("+"), +} + +abstract class Node { + abstract readonly names: UsedNames + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + return this + } + + optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { + return this + } + + // get count(): number { + // return 1 + // } +} + +class Def extends Node { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private rhs?: SafeExpr + ) { + super() + } + + render({es5, _n}: CGOptions): string { + const varKind = es5 ? varKinds.var : this.varKind + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` + return `${varKind} ${this.name}${rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!names[this.name.str]) return + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + return this.rhs instanceof _CodeOrName ? this.rhs.names : {} + } +} + +class Assign extends Node { + constructor( + readonly lhs: Code, + public rhs: SafeExpr, + private readonly sideEffects?: boolean + ) { + super() + } + + render({_n}: CGOptions): string { + return `${this.lhs} = ${this.rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return + this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + const names = this.lhs instanceof Name ? {} : {...this.lhs.names} + return addExprNames(names, this.rhs) + } +} + +class AssignOp extends Assign { + constructor( + lhs: Code, + private readonly op: Code, + rhs: SafeExpr, + sideEffects?: boolean + ) { + super(lhs, rhs, sideEffects) + } + + render({_n}: CGOptions): string { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n + } +} + +class Label extends Node { + readonly names: UsedNames = {} + constructor(readonly label: Name) { + super() + } + + render({_n}: CGOptions): string { + return `${this.label}:` + _n + } +} + +class Break extends Node { + readonly names: UsedNames = {} + constructor(readonly label?: Code) { + super() + } + + render({_n}: CGOptions): string { + const label = this.label ? ` ${this.label}` : "" + return `break${label};` + _n + } +} + +class Throw extends Node { + constructor(readonly error: Code) { + super() + } + + render({_n}: CGOptions): string { + return `throw ${this.error};` + _n + } + + get names(): UsedNames { + return this.error.names + } +} + +class AnyCode extends Node { + constructor(private code: SafeExpr) { + super() + } + + render({_n}: CGOptions): string { + return `${this.code};` + _n + } + + optimizeNodes(): this | undefined { + return `${this.code}` ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this { + this.code = optimizeExpr(this.code, names, constants) + return this + } + + get names(): UsedNames { + return this.code instanceof _CodeOrName ? this.code.names : {} + } +} + +abstract class ParentNode extends Node { + constructor(readonly nodes: ChildNode[] = []) { + super() + } + + render(opts: CGOptions): string { + return this.nodes.reduce((code, n) => code + n.render(opts), "") + } + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + const n = nodes[i].optimizeNodes() + if (Array.isArray(n)) nodes.splice(i, 1, ...n) + else if (n) nodes[i] = n + else nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i] + if (n.optimizeNames(names, constants)) continue + subtractNames(names, n.names) + nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + get names(): UsedNames { + return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {}) + } + + // get count(): number { + // return this.nodes.reduce((c, n) => c + n.count, 1) + // } +} + +abstract class BlockNode extends ParentNode { + render(opts: CGOptions): string { + return "{" + opts._n + super.render(opts) + "}" + opts._n + } +} + +class Root extends ParentNode {} + +class Else extends BlockNode { + static readonly kind = "else" +} + +class If extends BlockNode { + static readonly kind = "if" + else?: If | Else + constructor( + private condition: Code | boolean, + nodes?: ChildNode[] + ) { + super(nodes) + } + + render(opts: CGOptions): string { + let code = `if(${this.condition})` + super.render(opts) + if (this.else) code += "else " + this.else.render(opts) + return code + } + + optimizeNodes(): If | ChildNode[] | undefined { + super.optimizeNodes() + const cond = this.condition + if (cond === true) return this.nodes // else is ignored here + let e = this.else + if (e) { + const ns = e.optimizeNodes() + e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined) + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes + if (this.nodes.length) return this + return new If(not(cond), e instanceof If ? [e] : e.nodes) + } + if (cond === false || !this.nodes.length) return undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + this.else = this.else?.optimizeNames(names, constants) + if (!(super.optimizeNames(names, constants) || this.else)) return + this.condition = optimizeExpr(this.condition, names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + addExprNames(names, this.condition) + if (this.else) addNames(names, this.else.names) + return names + } + + // get count(): number { + // return super.count + (this.else?.count || 0) + // } +} + +abstract class For extends BlockNode { + static readonly kind = "for" +} + +class ForLoop extends For { + constructor(private iteration: Code) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.iteration})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iteration = optimizeExpr(this.iteration, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iteration.names) + } +} + +class ForRange extends For { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private readonly from: SafeExpr, + private readonly to: SafeExpr + ) { + super() + } + + render(opts: CGOptions): string { + const varKind = opts.es5 ? varKinds.var : this.varKind + const {name, from, to} = this + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) + } + + get names(): UsedNames { + const names = addExprNames(super.names, this.from) + return addExprNames(names, this.to) + } +} + +class ForIter extends For { + constructor( + private readonly loop: "of" | "in", + private readonly varKind: Name, + private readonly name: Name, + private iterable: Code + ) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iterable = optimizeExpr(this.iterable, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iterable.names) + } +} + +class Func extends BlockNode { + static readonly kind = "func" + constructor( + public name: Name, + public args: Code, + public async?: boolean + ) { + super() + } + + render(opts: CGOptions): string { + const _async = this.async ? "async " : "" + return `${_async}function ${this.name}(${this.args})` + super.render(opts) + } +} + +class Return extends ParentNode { + static readonly kind = "return" + + render(opts: CGOptions): string { + return "return " + super.render(opts) + } +} + +class Try extends BlockNode { + catch?: Catch + finally?: Finally + + render(opts: CGOptions): string { + let code = "try" + super.render(opts) + if (this.catch) code += this.catch.render(opts) + if (this.finally) code += this.finally.render(opts) + return code + } + + optimizeNodes(): this { + super.optimizeNodes() + this.catch?.optimizeNodes() as Catch | undefined + this.finally?.optimizeNodes() as Finally | undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this { + super.optimizeNames(names, constants) + this.catch?.optimizeNames(names, constants) + this.finally?.optimizeNames(names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + if (this.catch) addNames(names, this.catch.names) + if (this.finally) addNames(names, this.finally.names) + return names + } + + // get count(): number { + // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0) + // } +} + +class Catch extends BlockNode { + static readonly kind = "catch" + constructor(readonly error: Name) { + super() + } + + render(opts: CGOptions): string { + return `catch(${this.error})` + super.render(opts) + } +} + +class Finally extends BlockNode { + static readonly kind = "finally" + render(opts: CGOptions): string { + return "finally" + super.render(opts) + } +} + +type StartBlockNode = If | For | Func | Return | Try + +type LeafNode = Def | Assign | Label | Break | Throw | AnyCode + +type ChildNode = StartBlockNode | LeafNode + +type EndBlockNodeType = + | typeof If + | typeof Else + | typeof For + | typeof Func + | typeof Return + | typeof Catch + | typeof Finally + +type Constants = Record + +export interface CodeGenOptions { + es5?: boolean + lines?: boolean + ownProperties?: boolean +} + +interface CGOptions extends CodeGenOptions { + _n: "\n" | "" +} + +export class CodeGen { + readonly _scope: Scope + readonly _extScope: ValueScope + readonly _values: ScopeValueSets = {} + private readonly _nodes: ParentNode[] + private readonly _blockStarts: number[] = [] + private readonly _constants: Constants = {} + private readonly opts: CGOptions + + constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { + this.opts = {...opts, _n: opts.lines ? "\n" : ""} + this._extScope = extScope + this._scope = new Scope({parent: extScope}) + this._nodes = [new Root()] + } + + toString(): string { + return this._root.render(this.opts) + } + + // returns unique name in the internal scope + name(prefix: string): Name { + return this._scope.name(prefix) + } + + // reserves unique name in the external scope + scopeName(prefix: string): ValueScopeName { + return this._extScope.name(prefix) + } + + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { + const name = this._extScope.value(prefixOrName, value) + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) + vs.add(name) + return name + } + + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + return this._extScope.getValue(prefix, keyOrRef) + } + + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName: Name): Code { + return this._extScope.scopeRefs(scopeName, this._values) + } + + scopeCode(): Code { + return this._extScope.scopeCode(this._values) + } + + private _def( + varKind: Name, + nameOrPrefix: Name | string, + rhs?: SafeExpr, + constant?: boolean + ): Name { + const name = this._scope.toName(nameOrPrefix) + if (rhs !== undefined && constant) this._constants[name.str] = rhs + this._leafNode(new Def(varKind, name, rhs)) + return name + } + + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.const, nameOrPrefix, rhs, _constant) + } + + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.let, nameOrPrefix, rhs, _constant) + } + + // `var` declaration with optional assignment + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.var, nameOrPrefix, rhs, _constant) + } + + // assignment code + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { + return this._leafNode(new Assign(lhs, rhs, sideEffects)) + } + + // `+=` code + add(lhs: Code, rhs: SafeExpr): CodeGen { + return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) + } + + // appends passed SafeExpr to code or executes Block + code(c: Block | SafeExpr): CodeGen { + if (typeof c == "function") c() + else if (c !== nil) this._leafNode(new AnyCode(c)) + return this + } + + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues: [Name | string, SafeExpr | string][]): _Code { + const code: CodeItem[] = ["{"] + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(",") + code.push(key) + if (key !== value || this.opts.es5) { + code.push(":") + addCodeArg(code, value) + } + } + code.push("}") + return new _Code(code) + } + + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { + this._blockNode(new If(condition)) + + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf() + } else if (thenBody) { + this.code(thenBody).endIf() + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body') + } + return this + } + + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition: Code | boolean): CodeGen { + return this._elseNode(new If(condition)) + } + + // `else` clause - only valid after `if` or `else if` clauses + else(): CodeGen { + return this._elseNode(new Else()) + } + + // end `if` statement (needed if gen.if was used only with condition) + endIf(): CodeGen { + return this._endBlockNode(If, Else) + } + + private _for(node: For, forBody?: Block): CodeGen { + this._blockNode(node) + if (forBody) this.code(forBody).endFor() + return this + } + + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration: Code, forBody?: Block): CodeGen { + return this._for(new ForLoop(iteration), forBody) + } + + // `for` statement for a range of values + forRange( + nameOrPrefix: Name | string, + from: SafeExpr, + to: SafeExpr, + forBody: (index: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) + } + + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf( + nameOrPrefix: Name | string, + iterable: Code, + forBody: (item: Name) => void, + varKind: Code = varKinds.const + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + if (this.opts.es5) { + const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) + return this.forRange("_i", 0, _`${arr}.length`, (i) => { + this.var(name, _`${arr}[${i}]`) + forBody(name) + }) + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) + } + + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn( + nameOrPrefix: Name | string, + obj: Code, + forBody: (item: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const + ): CodeGen { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) + } + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) + } + + // end `for` loop + endFor(): CodeGen { + return this._endBlockNode(For) + } + + // `label` statement + label(label: Name): CodeGen { + return this._leafNode(new Label(label)) + } + + // `break` statement + break(label?: Code): CodeGen { + return this._leafNode(new Break(label)) + } + + // `return` statement + return(value: Block | SafeExpr): CodeGen { + const node = new Return() + this._blockNode(node) + this.code(value) + if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') + return this._endBlockNode(Return) + } + + // `try` statement + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { + if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') + const node = new Try() + this._blockNode(node) + this.code(tryBody) + if (catchCode) { + const error = this.name("e") + this._currNode = node.catch = new Catch(error) + catchCode(error) + } + if (finallyCode) { + this._currNode = node.finally = new Finally() + this.code(finallyCode) + } + return this._endBlockNode(Catch, Finally) + } + + // `throw` statement + throw(error: Code): CodeGen { + return this._leafNode(new Throw(error)) + } + + // start self-balancing block + block(body?: Block, nodeCount?: number): CodeGen { + this._blockStarts.push(this._nodes.length) + if (body) this.code(body).endBlock(nodeCount) + return this + } + + // end the current self-balancing block + endBlock(nodeCount?: number): CodeGen { + const len = this._blockStarts.pop() + if (len === undefined) throw new Error("CodeGen: not in self-balancing block") + const toClose = this._nodes.length - len + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) + } + this._nodes.length = len + return this + } + + // `function` heading (or definition if funcBody is passed) + func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { + this._blockNode(new Func(name, args, async)) + if (funcBody) this.code(funcBody).endFunc() + return this + } + + // end function definition + endFunc(): CodeGen { + return this._endBlockNode(Func) + } + + optimize(n = 1): void { + while (n-- > 0) { + this._root.optimizeNodes() + this._root.optimizeNames(this._root.names, this._constants) + } + } + + private _leafNode(node: LeafNode): CodeGen { + this._currNode.nodes.push(node) + return this + } + + private _blockNode(node: StartBlockNode): void { + this._currNode.nodes.push(node) + this._nodes.push(node) + } + + private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { + const n = this._currNode + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop() + return this + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) + } + + private _elseNode(node: If | Else): CodeGen { + const n = this._currNode + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"') + } + this._currNode = n.else = node + return this + } + + private get _root(): Root { + return this._nodes[0] as Root + } + + private get _currNode(): ParentNode { + const ns = this._nodes + return ns[ns.length - 1] + } + + private set _currNode(node: ParentNode) { + const ns = this._nodes + ns[ns.length - 1] = node + } + + // get nodeCount(): number { + // return this._root.count + // } +} + +function addNames(names: UsedNames, from: UsedNames): UsedNames { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0) + return names +} + +function addExprNames(names: UsedNames, from: SafeExpr): UsedNames { + return from instanceof _CodeOrName ? addNames(names, from.names) : names +} + +function optimizeExpr(expr: T, names: UsedNames, constants: Constants): T +function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr { + if (expr instanceof Name) return replaceName(expr) + if (!canOptimize(expr)) return expr + return new _Code( + expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => { + if (c instanceof Name) c = replaceName(c) + if (c instanceof _Code) items.push(...c._items) + else items.push(c) + return items + }, []) + ) + + function replaceName(n: Name): SafeExpr { + const c = constants[n.str] + if (c === undefined || names[n.str] !== 1) return n + delete names[n.str] + return c + } + + function canOptimize(e: SafeExpr): e is _Code { + return ( + e instanceof _Code && + e._items.some( + (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined + ) + ) + } +} + +function subtractNames(names: UsedNames, from: UsedNames): void { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0) +} + +export function not(x: T): T +export function not(x: Code | SafeExpr): Code | SafeExpr { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}` +} + +const andCode = mappend(operators.AND) + +// boolean AND (&&) expression with the passed arguments +export function and(...args: Code[]): Code { + return args.reduce(andCode) +} + +const orCode = mappend(operators.OR) + +// boolean OR (||) expression with the passed arguments +export function or(...args: Code[]): Code { + return args.reduce(orCode) +} + +type MAppend = (x: Code, y: Code) => Code + +function mappend(op: Code): MAppend { + return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`) +} + +function par(x: Code): Code { + return x instanceof Name ? x : _`(${x})` +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/scope.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/scope.ts new file mode 100644 index 0000000000000000000000000000000000000000..511992297d08f661ef4cf826eba9fbdbf0854db0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/codegen/scope.ts @@ -0,0 +1,215 @@ +import {_, nil, Code, Name} from "./code" + +interface NameGroup { + prefix: string + index: number +} + +export interface NameValue { + ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure + key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used + 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`) +} + +export type ValueReference = unknown // possibly make CodeGen parameterized type on this type + +class ValueError extends Error { + readonly value?: NameValue + constructor(name: ValueScopeName) { + super(`CodeGen: "code" for ${name} not defined`) + this.value = name.value + } +} + +interface ScopeOptions { + prefixes?: Set + parent?: Scope +} + +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore + es5?: boolean + lines?: boolean +} + +export type ScopeStore = Record + +type ScopeValues = { + [Prefix in string]?: Map +} + +export type ScopeValueSets = { + [Prefix in string]?: Set +} + +export enum UsedValueState { + Started, + Completed, +} + +export type UsedScopeValues = { + [Prefix in string]?: Map +} + +export const varKinds = { + const: new Name("const"), + let: new Name("let"), + var: new Name("var"), +} + +export class Scope { + protected readonly _names: {[Prefix in string]?: NameGroup} = {} + protected readonly _prefixes?: Set + protected readonly _parent?: Scope + + constructor({prefixes, parent}: ScopeOptions = {}) { + this._prefixes = prefixes + this._parent = parent + } + + toName(nameOrPrefix: Name | string): Name { + return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix) + } + + name(prefix: string): Name { + return new Name(this._newName(prefix)) + } + + protected _newName(prefix: string): string { + const ng = this._names[prefix] || this._nameGroup(prefix) + return `${prefix}${ng.index++}` + } + + private _nameGroup(prefix: string): NameGroup { + if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`) + } + return (this._names[prefix] = {prefix, index: 0}) + } +} + +interface ScopePath { + property: string + itemIndex: number +} + +export class ValueScopeName extends Name { + readonly prefix: string + value?: NameValue + scopePath?: Code + + constructor(prefix: string, nameStr: string) { + super(nameStr) + this.prefix = prefix + } + + setValue(value: NameValue, {property, itemIndex}: ScopePath): void { + this.value = value + this.scopePath = _`.${new Name(property)}[${itemIndex}]` + } +} + +interface VSOptions extends ValueScopeOptions { + _n: Code +} + +const line = _`\n` + +export class ValueScope extends Scope { + protected readonly _values: ScopeValues = {} + protected readonly _scope: ScopeStore + readonly opts: VSOptions + + constructor(opts: ValueScopeOptions) { + super(opts) + this._scope = opts.scope + this.opts = {...opts, _n: opts.lines ? line : nil} + } + + get(): ScopeStore { + return this._scope + } + + name(prefix: string): ValueScopeName { + return new ValueScopeName(prefix, this._newName(prefix)) + } + + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName { + if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value") + const name = this.toName(nameOrPrefix) as ValueScopeName + const {prefix} = name + const valueKey = value.key ?? value.ref + let vs = this._values[prefix] + if (vs) { + const _name = vs.get(valueKey) + if (_name) return _name + } else { + vs = this._values[prefix] = new Map() + } + vs.set(valueKey, name) + + const s = this._scope[prefix] || (this._scope[prefix] = []) + const itemIndex = s.length + s[itemIndex] = value.ref + name.setValue(value, {property: prefix, itemIndex}) + return name + } + + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + const vs = this._values[prefix] + if (!vs) return + return vs.get(keyOrRef) + } + + scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code { + return this._reduceValues(values, (name: ValueScopeName) => { + if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return _`${scopeName}${name.scopePath}` + }) + } + + scopeCode( + values: ScopeValues | ScopeValueSets = this._values, + usedValues?: UsedScopeValues, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + return this._reduceValues( + values, + (name: ValueScopeName) => { + if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return name.value.code + }, + usedValues, + getCode + ) + } + + private _reduceValues( + values: ScopeValues | ScopeValueSets, + valueCode: (n: ValueScopeName) => Code | undefined, + usedValues: UsedScopeValues = {}, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + let code: Code = nil + for (const prefix in values) { + const vs = values[prefix] + if (!vs) continue + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()) + vs.forEach((name: ValueScopeName) => { + if (nameSet.has(name)) return + nameSet.set(name, UsedValueState.Started) + let c = valueCode(name) + if (c) { + const def = this.opts.es5 ? varKinds.var : varKinds.const + code = _`${code}${def} ${name} = ${c};${this.opts._n}` + } else if ((c = getCode?.(name))) { + code = _`${code}${c}${this.opts._n}` + } else { + throw new ValueError(name) + } + nameSet.set(name, UsedValueState.Completed) + }) + } + return code + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/errors.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..18424a0fc62917fa720aee28e97280865f8bf1f5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/errors.ts @@ -0,0 +1,184 @@ +import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types" +import type {SchemaCxt} from "./index" +import {CodeGen, _, str, strConcat, Code, Name} from "./codegen" +import {SafeExpr} from "./codegen/code" +import {getErrorPath, Type} from "./util" +import N from "./names" + +export const keywordError: KeywordErrorDefinition = { + message: ({keyword}) => str`must pass "${keyword}" keyword validation`, +} + +export const keyword$DataError: KeywordErrorDefinition = { + message: ({keyword, schemaType}) => + schemaType + ? str`"${keyword}" keyword must be ${schemaType} ($data)` + : str`"${keyword}" keyword is invalid ($data)`, +} + +export interface ErrorPaths { + instancePath?: Code + schemaPath?: string + parentSchema?: boolean +} + +export function reportError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths, + overrideAllErrors?: boolean +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + if (overrideAllErrors ?? (compositeRule || allErrors)) { + addError(gen, errObj) + } else { + returnErrors(it, _`[${errObj}]`) + } +} + +export function reportExtraError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + addError(gen, errObj) + if (!(compositeRule || allErrors)) { + returnErrors(it, N.vErrors) + } +} + +export function resetErrorsCount(gen: CodeGen, errsCount: Name): void { + gen.assign(N.errors, errsCount) + gen.if(_`${N.vErrors} !== null`, () => + gen.if( + errsCount, + () => gen.assign(_`${N.vErrors}.length`, errsCount), + () => gen.assign(N.vErrors, null) + ) + ) +} + +export function extendErrors({ + gen, + keyword, + schemaValue, + data, + errsCount, + it, +}: KeywordErrorCxt): void { + /* istanbul ignore if */ + if (errsCount === undefined) throw new Error("ajv implementation error") + const err = gen.name("err") + gen.forRange("i", errsCount, N.errors, (i) => { + gen.const(err, _`${N.vErrors}[${i}]`) + gen.if(_`${err}.instancePath === undefined`, () => + gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath)) + ) + gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`) + if (it.opts.verbose) { + gen.assign(_`${err}.schema`, schemaValue) + gen.assign(_`${err}.data`, data) + } + }) +} + +function addError(gen: CodeGen, errObj: Code): void { + const err = gen.const("err", errObj) + gen.if( + _`${N.vErrors} === null`, + () => gen.assign(N.vErrors, _`[${err}]`), + _`${N.vErrors}.push(${err})` + ) + gen.code(_`${N.errors}++`) +} + +function returnErrors(it: SchemaCxt, errs: Code): void { + const {gen, validateName, schemaEnv} = it + if (schemaEnv.$async) { + gen.throw(_`new ${it.ValidationError as Name}(${errs})`) + } else { + gen.assign(_`${validateName}.errors`, errs) + gen.return(false) + } +} + +const E = { + keyword: new Name("keyword"), + schemaPath: new Name("schemaPath"), // also used in JTD errors + params: new Name("params"), + propertyName: new Name("propertyName"), + message: new Name("message"), + schema: new Name("schema"), + parentSchema: new Name("parentSchema"), +} + +function errorObjectCode( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths?: ErrorPaths +): Code { + const {createErrors} = cxt.it + if (createErrors === false) return _`{}` + return errorObject(cxt, error, errorPaths) +} + +function errorObject( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths: ErrorPaths = {} +): Code { + const {gen, it} = cxt + const keyValues: [Name, SafeExpr | string][] = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ] + extraErrorProps(cxt, error, keyValues) + return gen.object(...keyValues) +} + +function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] { + const instPath = instancePath + ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}` + : errorPath + return [N.instancePath, strConcat(N.instancePath, instPath)] +} + +function errorSchemaPath( + {keyword, it: {errSchemaPath}}: KeywordErrorCxt, + {schemaPath, parentSchema}: ErrorPaths +): [Name, string | Code] { + let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}` + if (schemaPath) { + schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}` + } + return [E.schemaPath, schPath] +} + +function extraErrorProps( + cxt: KeywordErrorCxt, + {params, message}: KeywordErrorDefinition, + keyValues: [Name, SafeExpr | string][] +): void { + const {keyword, data, schemaValue, it} = cxt + const {opts, propertyName, topSchemaRef, schemaPath} = it + keyValues.push( + [E.keyword, keyword], + [E.params, typeof params == "function" ? params(cxt) : params || _`{}`] + ) + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]) + } + if (opts.verbose) { + keyValues.push( + [E.schema, schemaValue], + [E.parentSchema, _`${topSchemaRef}${schemaPath}`], + [N.data, data] + ) + } + if (propertyName) keyValues.push([E.propertyName, propertyName]) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfc39345526afe62f8c1d52eabf5b25b7959537f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/index.ts @@ -0,0 +1,324 @@ +import type { + AnySchema, + AnySchemaObject, + AnyValidateFunction, + AsyncValidateFunction, + EvaluatedProperties, + EvaluatedItems, +} from "../types" +import type Ajv from "../core" +import type {InstanceOptions} from "../core" +import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen" +import ValidationError from "../runtime/validation_error" +import N from "./names" +import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve" +import {schemaHasRulesButRef, unescapeFragment} from "./util" +import {validateFunctionCode} from "./validate" +import {URIComponent} from "fast-uri" +import {JSONType} from "./rules" + +export type SchemaRefs = { + [Ref in string]?: SchemaEnv | AnySchema +} + +export interface SchemaCxt { + readonly gen: CodeGen + readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error + readonly data: Name // Name with reference to the current part of data instance + readonly parentData: Name // should be used in keywords modifying data + readonly parentDataProperty: Code | number // should be used in keywords modifying data + readonly dataNames: Name[] + readonly dataPathArr: (Code | number)[] + readonly dataLevel: number // the level of the currently validated data, + // it can be used to access both the property names and the data on all levels from the top. + dataTypes: JSONType[] // data types applied to the current part of data instance + definedProperties: Set // set of properties to keep track of for required checks + readonly topSchemaRef: Code + readonly validateName: Name + evaluated?: Name + readonly ValidationError?: Name + readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt + readonly schemaEnv: SchemaEnv + readonly rootId: string + baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref) + readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema + readonly errSchemaPath: string // this is actual string, should not be changed to Code + readonly errorPath: Code + readonly propertyName?: Name + readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword, + // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`). + // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true. + // You only need to use it if you have many steps in your keywords and potentially can define multiple errors. + props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function + items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function + jtdDiscriminator?: string + jtdMetadata?: boolean + readonly createErrors?: boolean + readonly opts: InstanceOptions // Ajv instance option. + readonly self: Ajv // current Ajv instance +} + +export interface SchemaObjCxt extends SchemaCxt { + readonly schema: AnySchemaObject +} +interface SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root?: SchemaEnv + readonly baseId?: string + readonly schemaPath?: string + readonly localRefs?: LocalRefs + readonly meta?: boolean +} + +export class SchemaEnv implements SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root: SchemaEnv + baseId: string // TODO possibly, it should be readonly + schemaPath?: string + localRefs?: LocalRefs + readonly meta?: boolean + readonly $async?: boolean // true if the current schema is asynchronous. + readonly refs: SchemaRefs = {} + readonly dynamicAnchors: {[Ref in string]?: true} = {} + validate?: AnyValidateFunction + validateName?: ValueScopeName + serialize?: (data: unknown) => string + serializeName?: ValueScopeName + parse?: (data: string) => unknown + parseName?: ValueScopeName + + constructor(env: SchemaEnvArgs) { + let schema: AnySchemaObject | undefined + if (typeof env.schema == "object") schema = env.schema + this.schema = env.schema + this.schemaId = env.schemaId + this.root = env.root || this + this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) + this.schemaPath = env.schemaPath + this.localRefs = env.localRefs + this.meta = env.meta + this.$async = schema?.$async + this.refs = {} + } +} + +// let codeSize = 0 +// let nodeCount = 0 + +// Compiles schema in SchemaEnv +export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + let _ValidationError + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: ValidationError, + code: _`require("ajv/dist/runtime/validation_error").default`, + }) + } + + const validateName = gen.scopeName("validate") + sch.validateName = validateName + + const schemaCxt: SchemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: N.data, + parentData: N.parentData, + parentDataProperty: N.parentDataProperty, + dataNames: [N.data], + dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue( + "schema", + this.opts.code.source === true + ? {ref: sch.schema, code: stringify(sch.schema)} + : {ref: sch.schema} + ), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: _`""`, + opts: this.opts, + self: this, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + validateFunctionCode(schemaCxt) + gen.optimize(this.opts.code.optimize) + // gen.optimize(1) + const validateCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) + const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) + this.scope.value(validateName, {ref: validate}) + + validate.errors = null + validate.schema = sch.schema + validate.schemaEnv = sch + if (sch.$async) (validate as AsyncValidateFunction).$async = true + if (this.opts.code.source === true) { + validate.source = {validateName, validateCode, scopeValues: gen._values} + } + if (this.opts.unevaluated) { + const {props, items} = schemaCxt + validate.evaluated = { + props: props instanceof Name ? undefined : props, + items: items instanceof Name ? undefined : items, + dynamicProps: props instanceof Name, + dynamicItems: items instanceof Name, + } + if (validate.source) validate.source.evaluated = stringify(validate.evaluated) + } + sch.validate = validate + return sch + } catch (e) { + delete sch.validate + delete sch.validateName + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e + } finally { + this._compilations.delete(sch) + } +} + +export function resolveRef( + this: Ajv, + root: SchemaEnv, + baseId: string, + ref: string +): AnySchema | SchemaEnv | undefined { + ref = resolveUrl(this.opts.uriResolver, baseId, ref) + const schOrFunc = root.refs[ref] + if (schOrFunc) return schOrFunc + + let _sch = resolve.call(this, root, ref) + if (_sch === undefined) { + const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv + const {schemaId} = this.opts + if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) + } + + if (_sch === undefined) return + return (root.refs[ref] = inlineOrCompile.call(this, _sch)) +} + +function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { + if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema + return sch.validate ? sch : compileSchema.call(this, sch) +} + +// Index of schema compilation in the currently compiled list +export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) return sch + } +} + +function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId +} + +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve( + this: Ajv, + root: SchemaEnv, // information about the root schema for the current schema + ref: string // reference to resolve +): SchemaEnv | undefined { + let sch + while (typeof (sch = this.refs[ref]) == "string") ref = sch + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) +} + +// Resolve schema, its root and baseId +export function resolveSchema( + this: Ajv, + root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it + ref: string // reference to resolve +): SchemaEnv | undefined { + const p = this.opts.uriResolver.parse(ref) + const refPath = _getFullPath(this.opts.uriResolver, p) + let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined) + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root) + } + + const id = normalizeId(refPath) + const schOrRef = this.refs[id] || this.schemas[id] + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef) + if (typeof sch?.schema !== "object") return + return getJsonPointer.call(this, p, sch) + } + + if (typeof schOrRef?.schema !== "object") return + if (!schOrRef.validate) compileSchema.call(this, schOrRef) + if (id === normalizeId(ref)) { + const {schema} = schOrRef + const {schemaId} = this.opts + const schId = schema[schemaId] + if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + return new SchemaEnv({schema, schemaId, root, baseId}) + } + return getJsonPointer.call(this, p, schOrRef) +} + +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]) + +function getJsonPointer( + this: Ajv, + parsedRef: URIComponent, + {baseId, schema, root}: SchemaEnv +): SchemaEnv | undefined { + if (parsedRef.fragment?.[0] !== "/") return + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return + const partSchema = schema[unescapeFragment(part)] + if (partSchema === undefined) return + schema = partSchema + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId] + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + } + } + let env: SchemaEnv | undefined + if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) { + const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref) + env = resolveSchema.call(this, root, $ref) + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const {schemaId} = this.opts + env = env || new SchemaEnv({schema, schemaId, root, baseId}) + if (env.schema !== env.root.schema) return env + return undefined +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/parse.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0141c770c7029ce1d41db61bcd9a19fbd0c08d5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/parse.ts @@ -0,0 +1,411 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {hasPropFunc} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {intRange, IntType} from "../../vocabularies/jtd/type" +import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson" +import {useFunc} from "../util" +import validTimestamp from "../../runtime/timestamp" + +type GenParse = (cxt: ParseCxt) => void + +const genParse: {[F in JTDForm]: GenParse} = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +} + +interface ParseCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code + parseName: Name + char: Name +} + +export default function compileParser( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const parseName = gen.scopeName("parse") + const cxt: ParseCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + parseName, + char: gen.name("c"), + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.parseName = parseName + parserFunction(cxt) + gen.optimize(this.opts.code.optimize) + const parseFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}` + const makeParse = new Function(`${N.scope}`, sourceCode) + const parse: (json: string) => unknown = makeParse(this.scope.get()) + this.scope.value(parseName, {ref: parse}) + sch.parse = parse + } catch (e) { + if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode) + delete sch.parse + delete sch.parseName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +const undef = _`undefined` + +function parserFunction(cxt: ParseCxt): void { + const {gen, parseName, char} = cxt + gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { + gen.let(N.data) + gen.let(char) + gen.assign(_`${parseName}.message`, undef) + gen.assign(_`${parseName}.position`, undef) + gen.assign(N.jsonPos, _`${N.jsonPos} || 0`) + gen.const(N.jsonLen, _`${N.json}.length`) + parseCode(cxt) + skipWhitespace(cxt) + gen.if(N.jsonPart, () => { + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(N.data) + }) + gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data)) + jsonSyntaxError(cxt) + }) +} + +function parseCode(cxt: ParseCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + if (form) parseNullable(cxt, genParse[form]) + else parseEmpty(cxt) +} + +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)) + +function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return parseForm(cxt) + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) +} + +function parseElements(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "[") + const ix = gen.let("i", 0) + gen.assign(data, _`[]`) + parseItems(cxt, "]", () => { + const el = gen.let("el") + parseCode({...cxt, schema: schema.elements, data: el}) + gen.assign(_`${data}[${ix}++]`, el) + }) +} + +function parseValues(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) +} + +function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + tryParseItems(cxt, endToken, block) + parseToken(cxt, endToken) +} + +function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + const {gen} = cxt + gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block() + tryParseToken(cxt, ",", () => gen.break(), hasItem) + }) + + function hasItem(): void { + tryParseToken(cxt, endToken, () => {}, jsonSyntaxError) + } +} + +function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { + const {gen} = cxt + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + parsePropertyValue(cxt, key, schema) +} + +function parseDiscriminator(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const {discriminator, mapping} = schema + parseToken(cxt, "{") + gen.assign(data, _`{}`) + const startPos = gen.const("pos", N.jsonPos) + const value = gen.let("value") + const tag = gen.let("tag") + tryParseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if( + _`${key} === ${discriminator}`, + () => { + parseString({...cxt, data: tag}) + gen.assign(_`${data}[${key}]`, tag) + gen.break() + }, + () => parseEmpty({...cxt, data: value}) // can be discarded/skipped + ) + }) + gen.assign(N.jsonPos, startPos) + gen.if(_`${tag} === undefined`) + parsingError(cxt, str`discriminator tag not found`) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator) + } + gen.else() + parsingError(cxt, str`discriminator value not in schema`) + gen.endIf() +} + +function parseProperties(cxt: ParseCxt): void { + const {gen, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseSchemaProperties(cxt) +} + +function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties, additionalProperties} = schema + parseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if(false) + parseDefinedProperty(cxt, key, properties) + parseDefinedProperty(cxt, key, optionalProperties) + if (discriminator) { + gen.elseIf(_`${key} === ${discriminator}`) + const tag = gen.let("tag") + parseString({...cxt, data: tag}) // can be discarded, it is already assigned + } + gen.else() + if (additionalProperties) { + parseEmpty({...cxt, data: _`${data}[${key}]`}) + } else { + parsingError(cxt, str`property ${key} not allowed`) + } + gen.endIf() + }) + if (properties) { + const hasProp = hasPropFunc(gen) + const allProps: Code = and( + ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`) + ) + gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`)) + } +} + +function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { + const {gen} = cxt + for (const prop in schemas) { + gen.elseIf(_`${key} === ${prop}`) + parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) + } +} + +function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { + parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) +} + +function parseType(cxt: ParseCxt): void { + const {gen, schema, data, self} = cxt + switch (schema.type) { + case "boolean": + parseBoolean(cxt) + break + case "string": + parseString(cxt) + break + case "timestamp": { + parseString(cxt) + const vts = useFunc(gen, validTimestamp) + const {allowDate, parseDate} = self.opts + const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` + const fail: Code = parseDate + ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) + : notValid + gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) + break + } + case "float32": + case "float64": + parseNumber(cxt) + break + default: { + const t = schema.type as IntType + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16) // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) + } + } else { + const [min, max, maxDigits] = intRange[t] + parseNumber(cxt, maxDigits) + gen.if(_`${data} < ${min} || ${data} > ${max}`, () => + parsingError(cxt, str`integer out of range`) + ) + } + } + } +} + +function parseString(cxt: ParseCxt): void { + parseToken(cxt, '"') + parseWith(cxt, parseJsonString) +} + +function parseEnum(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const enumSch = schema.enum + parseToken(cxt, '"') + // TODO loopEnum + gen.if(false) + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1) // remove starting quote + gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) + gen.assign(data, str`${value}`) + gen.add(N.jsonPos, valueStr.length) + } + gen.else() + jsonSyntaxError(cxt) + gen.endIf() +} + +function parseNumber(cxt: ParseCxt, maxDigits?: number): void { + const {gen} = cxt + skipWhitespace(cxt) + gen.if( + _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, + () => jsonSyntaxError(cxt), + () => parseWith(cxt, parseJsonNumber, maxDigits) + ) +} + +function parseBooleanToken(bool: boolean, fail: GenParse): GenParse { + return (cxt) => { + const {gen, data} = cxt + tryParseToken( + cxt, + `${bool}`, + () => fail(cxt), + () => gen.assign(data, bool) + ) + } +} + +function parseRef(cxt: ParseCxt): void { + const {gen, self, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + partialParse(cxt, getParser(gen, sch), true) +} + +function getParser(gen: CodeGen, sch: SchemaEnv): Code { + return sch.parse + ? gen.scopeValue("parse", {ref: sch.parse}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` +} + +function parseEmpty(cxt: ParseCxt): void { + parseWith(cxt, parseJson) +} + +function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { + partialParse(cxt, useFunc(cxt.gen, parseFunc), args) +} + +function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { + const {gen, data} = cxt + gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) + gen.assign(N.jsonPos, _`${parseFunc}.position`) + gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) +} + +function parseToken(cxt: ParseCxt, tok: string): void { + tryParseToken(cxt, tok, jsonSyntaxError) +} + +function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { + const {gen} = cxt + const n = tok.length + skipWhitespace(cxt) + gen.if( + _`${jsonSlice(n)} === ${tok}`, + () => { + gen.add(N.jsonPos, n) + success?.(cxt) + }, + () => fail(cxt) + ) +} + +function skipWhitespace({gen, char: c}: ParseCxt): void { + gen.code( + _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` + ) +} + +function jsonSlice(len: number | Name): Code { + return len === 1 + ? _`${N.json}[${N.jsonPos}]` + : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})` +} + +function jsonSyntaxError(cxt: ParseCxt): void { + parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) +} + +function parsingError({gen, parseName}: ParseCxt, msg: Code): void { + gen.assign(_`${parseName}.message`, msg) + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(undef) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/serialize.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/serialize.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d228826d4344cfb4e64f20f494ff9102b736d33 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/serialize.ts @@ -0,0 +1,266 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {isOwnProperty} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {useFunc} from "../util" +import quote from "../../runtime/quote" + +const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +} + +interface SerializeCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code +} + +export default function compileSerializer( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const serializeName = gen.scopeName("serialize") + const cxt: SerializeCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.serializeName = serializeName + gen.func(serializeName, N.data, false, () => { + gen.let(N.json, str``) + serializeCode(cxt) + gen.return(N.json) + }) + gen.optimize(this.opts.code.optimize) + const serializeFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` + const makeSerialize = new Function(`${N.scope}`, sourceCode) + const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) + this.scope.value(serializeName, {ref: serialize}) + sch.serialize = serialize + } catch (e) { + if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) + delete sch.serialize + delete sch.serializeName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +function serializeCode(cxt: SerializeCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) +} + +function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return serializeForm(cxt) + gen.if( + _`${data} === undefined || ${data} === null`, + () => gen.add(N.json, _`"null"`), + () => serializeForm(cxt) + ) +} + +function serializeElements(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`[`) + const first = gen.let("first", true) + gen.forOf("el", data, (el) => { + addComma(cxt, first) + serializeCode({...cxt, schema: schema.elements, data: el}) + }) + gen.add(N.json, str`]`) +} + +function serializeValues(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`{`) + const first = gen.let("first", true) + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) + gen.add(N.json, str`}`) +} + +function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { + const {gen, data} = cxt + addComma(cxt, first) + serializeString({...cxt, data: key}) + gen.add(N.json, str`:`) + const value = gen.const("value", _`${data}${getProperty(key)}`) + serializeCode({...cxt, schema, data: value}) +} + +function serializeDiscriminator(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + const {discriminator} = schema + gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) + const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) + serializeString({...cxt, data: tag}) + gen.if(false) + for (const tagValue in schema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + const sch = schema.mapping[tagValue] + serializeSchemaProperties({...cxt, schema: sch}, discriminator) + } + gen.endIf() + gen.add(N.json, str`}`) +} + +function serializeProperties(cxt: SerializeCxt): void { + const {gen} = cxt + gen.add(N.json, str`{`) + serializeSchemaProperties(cxt) + gen.add(N.json, str`}`) +} + +function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties} = schema + const props = keys(properties) + const optProps = keys(optionalProperties) + const allProps = allProperties(props.concat(optProps)) + let first = !discriminator + let firstProp: Name | undefined + + for (const key of props) { + if (first) first = false + else gen.add(N.json, str`,`) + serializeProperty(key, properties[key], keyValue(key)) + } + if (first) firstProp = gen.let("first", true) + for (const key of optProps) { + const value = keyValue(key) + gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { + addComma(cxt, firstProp) + serializeProperty(key, optionalProperties[key], value) + }) + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => + gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) + ) + } + + function keys(ps?: SchemaObjectMap): string[] { + return ps ? Object.keys(ps) : [] + } + + function allProperties(ps: string[]): string[] { + if (discriminator) ps.push(discriminator) + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap") + } + return ps + } + + function keyValue(key: string): Name { + return gen.const("value", _`${data}${getProperty(key)}`) + } + + function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { + gen.add(N.json, str`${JSON.stringify(key)}:`) + serializeCode({...cxt, schema: propSchema, data: value}) + } + + function isAdditional(key: Name, ps: string[]): Code | true { + return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true + } +} + +function serializeType(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + switch (schema.type) { + case "boolean": + gen.add(N.json, _`${data} ? "true" : "false"`) + break + case "string": + serializeString(cxt) + break + case "timestamp": + gen.if( + _`${data} instanceof Date`, + () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), + () => serializeString(cxt) + ) + break + default: + serializeNumber(cxt) + } +} + +function serializeString({gen, data}: SerializeCxt): void { + gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) +} + +function serializeNumber({gen, data}: SerializeCxt): void { + gen.add(N.json, _`"" + ${data}`) +} + +function serializeRef(cxt: SerializeCxt): void { + const {gen, self, data, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) +} + +function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { + return sch.serialize + ? gen.scopeValue("serialize", {ref: sch.serialize}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` +} + +function serializeEmpty({gen, data}: SerializeCxt): void { + gen.add(N.json, _`JSON.stringify(${data})`) +} + +function addComma({gen}: SerializeCxt, first?: Name): void { + if (first) { + gen.if( + first, + () => gen.assign(first, false), + () => gen.add(N.json, str`,`) + ) + } else { + gen.add(N.json, str`,`) + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/types.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..1258050fdf426a085097c3858c513b95447ded94 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/jtd/types.ts @@ -0,0 +1,16 @@ +import type {SchemaObject} from "../../types" + +export type SchemaObjectMap = {[Ref in string]?: SchemaObject} + +export const jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +] as const + +export type JTDForm = (typeof jtdForms)[number] diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/ref_error.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/ref_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..386bf04995827ca2e6653fee7d4095049a753955 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/ref_error.ts @@ -0,0 +1,13 @@ +import {resolveUrl, normalizeId, getFullPath} from "./resolve" +import type {UriResolver} from "../types" + +export default class MissingRefError extends Error { + readonly missingRef: string + readonly missingSchema: string + + constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`) + this.missingRef = resolveUrl(resolver, baseId, ref) + this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef)) + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/resolve.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/resolve.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8c4aca394a7a3f46f7977c2e66a7ab570213e80 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/resolve.ts @@ -0,0 +1,149 @@ +import type {AnySchema, AnySchemaObject, UriResolver} from "../types" +import type Ajv from "../ajv" +import type {URIComponent} from "fast-uri" +import {eachItem} from "./util" +import * as equal from "fast-deep-equal" +import * as traverse from "json-schema-traverse" + +// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution +export type LocalRefs = {[Ref in string]?: AnySchemaObject} + +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]) + +export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean { + if (typeof schema == "boolean") return true + if (limit === true) return !hasRef(schema) + if (!limit) return false + return countKeys(schema) <= limit +} + +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]) + +function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true + const sch = schema[key] + if (Array.isArray(sch) && sch.some(hasRef)) return true + if (typeof sch == "object" && hasRef(sch)) return true + } + return false +} + +function countKeys(schema: AnySchemaObject): number { + let count = 0 + for (const key in schema) { + if (key === "$ref") return Infinity + count++ + if (SIMPLE_INLINED.has(key)) continue + if (typeof schema[key] == "object") { + eachItem(schema[key], (sch) => (count += countKeys(sch))) + } + if (count === Infinity) return Infinity + } + return count +} + +export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string { + if (normalize !== false) id = normalizeId(id) + const p = resolver.parse(id) + return _getFullPath(resolver, p) +} + +export function _getFullPath(resolver: UriResolver, p: URIComponent): string { + const serialized = resolver.serialize(p) + return serialized.split("#")[0] + "#" +} + +const TRAILING_SLASH_HASH = /#\/?$/ +export function normalizeId(id: string | undefined): string { + return id ? id.replace(TRAILING_SLASH_HASH, "") : "" +} + +export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string { + id = normalizeId(id) + return resolver.resolve(baseId, id) +} + +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i + +export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs { + if (typeof schema == "boolean") return {} + const {schemaId, uriResolver} = this.opts + const schId = normalizeId(schema[schemaId] || baseId) + const baseIds: {[JsonPtr in string]?: string} = {"": schId} + const pathPrefix = getFullPath(uriResolver, schId, false) + const localRefs: LocalRefs = {} + const schemaRefs: Set = new Set() + + traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) return + const fullPath = pathPrefix + jsonPtr + let innerBaseId = baseIds[parentJsonPtr] + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]) + addAnchor.call(this, sch.$anchor) + addAnchor.call(this, sch.$dynamicAnchor) + baseIds[jsonPtr] = innerBaseId + + function addRef(this: Ajv, ref: string): string { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref) + if (schemaRefs.has(ref)) throw ambiguos(ref) + schemaRefs.add(ref) + let schOrRef = this.refs[ref] + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef] + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref) + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref) + localRefs[ref] = sch + } else { + this.refs[ref] = fullPath + } + } + return ref + } + + function addAnchor(this: Ajv, anchor: unknown): void { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`) + addRef.call(this, `#${anchor}`) + } + } + }) + + return localRefs + + function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void { + if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref) + } + + function ambiguos(ref: string): Error { + return new Error(`reference "${ref}" resolves to more than one schema`) + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/applicability.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/applicability.ts new file mode 100644 index 0000000000000000000000000000000000000000..478b704ac571d7b34deb19ef84aa0e2dd08973e3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/applicability.ts @@ -0,0 +1,22 @@ +import type {AnySchemaObject} from "../../types" +import type {SchemaObjCxt} from ".." +import type {JSONType, RuleGroup, Rule} from "../rules" + +export function schemaHasRulesForType( + {schema, self}: SchemaObjCxt, + type: JSONType +): boolean | undefined { + const group = self.RULES.types[type] + return group && group !== true && shouldUseGroup(schema, group) +} + +export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { + return group.rules.some((rule) => shouldUseRule(schema, rule)) +} + +export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { + return ( + schema[rule.keyword] !== undefined || + rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) + ) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/boolSchema.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/boolSchema.ts new file mode 100644 index 0000000000000000000000000000000000000000..156355016d62249d16c6dc19a89c28b5ff6972c7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/boolSchema.ts @@ -0,0 +1,47 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types" +import type {SchemaCxt} from ".." +import {reportError} from "../errors" +import {_, Name} from "../codegen" +import N from "../names" + +const boolError: KeywordErrorDefinition = { + message: "boolean schema is false", +} + +export function topBoolOrEmptySchema(it: SchemaCxt): void { + const {gen, schema, validateName} = it + if (schema === false) { + falseSchemaError(it, false) + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(N.data) + } else { + gen.assign(_`${validateName}.errors`, null) + gen.return(true) + } +} + +export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void { + const {gen, schema} = it + if (schema === false) { + gen.var(valid, false) // TODO var + falseSchemaError(it) + } else { + gen.var(valid, true) // TODO var + } +} + +function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void { + const {gen, data} = it + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt: KeywordErrorCxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + } + reportError(cxt, boolError, undefined, overrideAllErrors) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/dataType.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/dataType.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8142b3e1f55194a06de0ab489ee01e00136df25 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/dataType.ts @@ -0,0 +1,230 @@ +import type { + KeywordErrorDefinition, + KeywordErrorCxt, + ErrorObject, + AnySchemaObject, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {isJSONType, JSONType} from "../rules" +import {schemaHasRulesForType} from "./applicability" +import {reportError} from "../errors" +import {_, nil, and, not, operators, Code, Name} from "../codegen" +import {toHash, schemaRefOrVal} from "../util" + +export enum DataType { + Correct, + Wrong, +} + +export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { + const types = getJSONTypes(schema.type) + const hasNull = types.includes("null") + if (hasNull) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") + } else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"') + } + if (schema.nullable === true) types.push("null") + } + return types +} + +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { + const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] + if (types.every(isJSONType)) return types + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")) +} + +export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { + const {gen, data, opts} = it + const coerceTo = coerceToTypes(types, opts.coerceTypes) + const checkTypes = + types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong) + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo) + else reportTypeError(it) + }) + } + return checkTypes +} + +const COERCIBLE: Set = new Set(["string", "number", "integer", "boolean", "null"]) +function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : [] +} + +function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { + const {gen, data, opts} = it + const dataType = gen.let("dataType", _`typeof ${data}`) + const coerced = gen.let("coerced", _`undefined`) + if (opts.coerceTypes === "array") { + gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => + gen + .assign(data, _`${data}[0]`) + .assign(dataType, _`typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)) + ) + } + gen.if(_`${coerced} !== undefined`) + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t) + } + } + gen.else() + reportTypeError(it) + gen.endIf() + + gen.if(_`${coerced} !== undefined`, () => { + gen.assign(data, coerced) + assignParentData(it, coerced) + }) + + function coerceSpecificType(t: string): void { + switch (t) { + case "string": + gen + .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, _`"" + ${data}`) + .elseIf(_`${data} === null`) + .assign(coerced, _`""`) + return + case "number": + gen + .elseIf( + _`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})` + ) + .assign(coerced, _`+${data}`) + return + case "integer": + gen + .elseIf( + _`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))` + ) + .assign(coerced, _`+${data}`) + return + case "boolean": + gen + .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf(_`${data} === "true" || ${data} === 1`) + .assign(coerced, true) + return + case "null": + gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`) + gen.assign(coerced, null) + return + + case "array": + gen + .elseIf( + _`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null` + ) + .assign(coerced, _`[${data}]`) + } + } +} + +function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { + // TODO use gen.property + gen.if(_`${parentData} !== undefined`, () => + gen.assign(_`${parentData}[${parentDataProperty}]`, expr) + ) +} + +export function checkDataType( + dataType: JSONType, + data: Name, + strictNums?: boolean | "log", + correct = DataType.Correct +): Code { + const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ + let cond: Code + switch (dataType) { + case "null": + return _`${data} ${EQ} null` + case "array": + cond = _`Array.isArray(${data})` + break + case "object": + cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})` + break + case "integer": + cond = numCond(_`!(${data} % 1) && !isNaN(${data})`) + break + case "number": + cond = numCond() + break + default: + return _`typeof ${data} ${EQ} ${dataType}` + } + return correct === DataType.Correct ? cond : not(cond) + + function numCond(_cond: Code = nil): Code { + return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) + } +} + +export function checkDataTypes( + dataTypes: JSONType[], + data: Name, + strictNums?: boolean | "log", + correct?: DataType +): Code { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct) + } + let cond: Code + const types = toHash(dataTypes) + if (types.array && types.object) { + const notObj = _`typeof ${data} != "object"` + cond = types.null ? notObj : _`!${data} || ${notObj}` + delete types.null + delete types.array + delete types.object + } else { + cond = nil + } + if (types.number) delete types.integer + for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct)) + return cond +} + +export type TypeError = ErrorObject<"type", {type: string}> + +const typeError: KeywordErrorDefinition = { + message: ({schema}) => `must be ${schema}`, + params: ({schema, schemaValue}) => + typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`, +} + +export function reportTypeError(it: SchemaObjCxt): void { + const cxt = getTypeErrorContext(it) + reportError(cxt, typeError) +} + +function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { + const {gen, data, schema} = it + const schemaCode = schemaRefOrVal(it, schema, "type") + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/defaults.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ad3d4df8291bdfd7aec74833bec4b0b4c91f36f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/defaults.ts @@ -0,0 +1,32 @@ +import type {SchemaObjCxt} from ".." +import {_, getProperty, stringify} from "../codegen" +import {checkStrictMode} from "../util" + +export function assignDefaults(it: SchemaObjCxt, ty?: string): void { + const {properties, items} = it.schema + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default) + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i: number) => assignDefault(it, i, sch.default)) + } +} + +function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { + const {gen, compositeRule, data, opts} = it + if (defaultValue === undefined) return + const childData = _`${data}${getProperty(prop)}` + if (compositeRule) { + checkStrictMode(it, `default is ignored for: ${childData}`) + return + } + + let condition = _`${childData} === undefined` + if (opts.useDefaults === "empty") { + condition = _`${condition} || ${childData} === null || ${childData} === ""` + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, _`${childData} = ${stringify(defaultValue)}`) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..15ecabd85169e3f19b56b7547982643383068552 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/index.ts @@ -0,0 +1,582 @@ +import type { + AddedKeywordDefinition, + AnySchema, + AnySchemaObject, + KeywordErrorCxt, + KeywordCxtParams, +} from "../../types" +import type {SchemaCxt, SchemaObjCxt} from ".." +import type {InstanceOptions} from "../../core" +import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" +import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" +import {shouldUseGroup, shouldUseRule} from "./applicability" +import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" +import {assignDefaults} from "./defaults" +import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" +import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" +import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import {resolveUrl} from "../resolve" +import { + schemaRefOrVal, + schemaHasRulesButRef, + checkUnknownRules, + checkStrictMode, + unescapeJsonPointer, + mergeEvaluated, +} from "../util" +import type {JSONType, Rule, RuleGroup} from "../rules" +import { + ErrorPaths, + reportError, + reportExtraError, + resetErrorsCount, + keyword$DataError, +} from "../errors" + +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +export function validateFunctionCode(it: SchemaCxt): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it) + return + } + } + validateFunction(it, () => topBoolOrEmptySchema(it)) +} + +function validateFunction( + {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, + body: Block +): void { + if (opts.code.es5) { + gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { + gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) + destructureValCxtES5(gen, opts) + gen.code(body) + }) + } else { + gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => + gen.code(funcSourceUrl(schema, opts)).code(body) + ) + } +} + +function destructureValCxt(opts: InstanceOptions): Code { + return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ + N.data + }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` +} + +function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { + gen.if( + N.valCxt, + () => { + gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) + gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) + gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) + gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) + }, + () => { + gen.var(N.instancePath, _`""`) + gen.var(N.parentData, _`undefined`) + gen.var(N.parentDataProperty, _`undefined`) + gen.var(N.rootData, N.data) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) + } + ) +} + +function topSchemaObjCode(it: SchemaObjCxt): void { + const {schema, opts, gen} = it + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it) + checkNoDefault(it) + gen.let(N.vErrors, null) + gen.let(N.errors, 0) + if (opts.unevaluated) resetEvaluated(it) + typeAndKeywords(it) + returnResults(it) + }) + return +} + +function resetEvaluated(it: SchemaObjCxt): void { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const {gen, validateName} = it + it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) + gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) + gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) +} + +function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { + const schId = typeof schema == "object" && schema[opts.schemaId] + return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil +} + +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it: SchemaCxt, valid: Name): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid) + return + } + } + boolOrEmptySchema(it, valid) +} + +function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (self.RULES.all[key]) return true + return false +} + +function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { + return typeof it.schema != "boolean" +} + +function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { + const {schema, gen, opts} = it + if (opts.$comment && schema.$comment) commentKeyword(it) + updateContext(it) + checkAsyncSchema(it) + const errsCount = gen.const("_errs", N.errors) + typeAndKeywords(it, errsCount) + // TODO var + gen.var(valid, _`${errsCount} === ${N.errors}`) +} + +function checkKeywords(it: SchemaObjCxt): void { + checkUnknownRules(it) + checkRefsAndKeywords(it) +} + +function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) + const types = getSchemaTypes(it.schema) + const checkedTypes = coerceAndCheckDataType(it, types) + schemaKeywords(it, types, !checkedTypes, errsCount) +} + +function checkRefsAndKeywords(it: SchemaObjCxt): void { + const {schema, errSchemaPath, opts, self} = it + if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) + } +} + +function checkNoDefault(it: SchemaObjCxt): void { + const {schema, opts} = it + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + checkStrictMode(it, "default is ignored in the schema root") + } +} + +function updateContext(it: SchemaObjCxt): void { + const schId = it.schema[it.opts.schemaId] + if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId) +} + +function checkAsyncSchema(it: SchemaObjCxt): void { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") +} + +function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { + const msg = schema.$comment + if (opts.$comment === true) { + gen.code(_`${N.self}.logger.log(${msg})`) + } else if (typeof opts.$comment == "function") { + const schemaPath = str`${errSchemaPath}/$comment` + const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) + gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) + } +} + +function returnResults(it: SchemaCxt): void { + const {gen, schemaEnv, validateName, ValidationError, opts} = it + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if( + _`${N.errors} === 0`, + () => gen.return(N.data), + () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) + ) + } else { + gen.assign(_`${validateName}.errors`, N.vErrors) + if (opts.unevaluated) assignEvaluated(it) + gen.return(_`${N.errors} === 0`) + } +} + +function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { + if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) + if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) +} + +function schemaKeywords( + it: SchemaObjCxt, + types: JSONType[], + typeErrors: boolean, + errsCount?: Name +): void { + const {gen, schema, data, allErrors, opts, self} = it + const {RULES} = self + if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast + return + } + if (!opts.jtd) checkStrictTypes(it, types) + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group) + groupKeywords(RULES.post) + }) + + function groupKeywords(group: RuleGroup): void { + if (!shouldUseGroup(schema, group)) return + if (group.type) { + gen.if(checkDataType(group.type, data, opts.strictNumbers)) + iterateKeywords(it, group) + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else() + reportTypeError(it) + } + gen.endIf() + } else { + iterateKeywords(it, group) + } + // TODO make it "ok" call? + if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) + } +} + +function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { + const { + gen, + schema, + opts: {useDefaults}, + } = it + if (useDefaults) assignDefaults(it, group.type) + gen.block(() => { + for (const rule of group.rules) { + if (shouldUseRule(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type) + } + } + }) +} + +function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (it.schemaEnv.meta || !it.opts.strictTypes) return + checkContextTypes(it, types) + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) + checkKeywordTypes(it, it.dataTypes) +} + +function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (!types.length) return + if (!it.dataTypes.length) { + it.dataTypes = types + return + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) + } + }) + narrowSchemaTypes(it, types) +} + +function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword") + } +} + +function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { + const rules = it.self.RULES.all + for (const keyword in rules) { + const rule = rules[keyword] + if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { + const {type} = rule.definition + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) + } + } + } +} + +function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) +} + +function includesType(ts: JSONType[], t: JSONType): boolean { + return ts.includes(t) || (t === "integer" && ts.includes("number")) +} + +function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { + const ts: JSONType[] = [] + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) ts.push(t) + else if (withTypes.includes("integer") && t === "number") ts.push("integer") + } + it.dataTypes = ts +} + +function strictTypesError(it: SchemaObjCxt, msg: string): void { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + msg += ` at "${schemaPath}" (strictTypes)` + checkStrictMode(it, msg, it.opts.strictTypes) +} + +export class KeywordCxt implements KeywordErrorCxt { + readonly gen: CodeGen + readonly allErrors?: boolean + readonly keyword: string + readonly data: Name // Name referencing the current level of the data instance + readonly $data?: string | false + schema: any // keyword value in the schema + readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value + readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) + readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema + readonly parentSchema: AnySchemaObject + readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, + // requires option trackErrors in keyword definition + params: KeywordCxtParams // object to pass parameters to error messages from keyword code + readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) + readonly def: AddedKeywordDefinition + + constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { + validateKeywordUsage(it, def, keyword) + this.gen = it.gen + this.allErrors = it.allErrors + this.keyword = keyword + this.data = it.data + this.schema = it.schema[keyword] + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data + this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) + this.schemaType = def.schemaType + this.parentSchema = it.schema + this.params = {} + this.it = it + this.def = def + + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) + } else { + this.schemaCode = this.schemaValue + if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) + } + } + + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", N.errors) + } + } + + result(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.failResult(not(condition), successAction, failAction) + } + + failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.gen.if(condition) + if (failAction) failAction() + else this.error() + if (successAction) { + this.gen.else() + successAction() + if (this.allErrors) this.gen.endIf() + } else { + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + } + + pass(condition: Code, failAction?: () => void): void { + this.failResult(not(condition), undefined, failAction) + } + + fail(condition?: Code): void { + if (condition === undefined) { + this.error() + if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize + return + } + this.gen.if(condition) + this.error() + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + + fail$data(condition: Code): void { + if (!this.$data) return this.fail(condition) + const {schemaCode} = this + this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) + } + + error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { + if (errorParams) { + this.setParams(errorParams) + this._error(append, errorPaths) + this.setParams({}) + return + } + this._error(append, errorPaths) + } + + private _error(append?: boolean, errorPaths?: ErrorPaths): void { + ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) + } + + $dataError(): void { + reportError(this, this.def.$dataError || keyword$DataError) + } + + reset(): void { + if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') + resetErrorsCount(this.gen, this.errsCount) + } + + ok(cond: Code | boolean): void { + if (!this.allErrors) this.gen.if(cond) + } + + setParams(obj: KeywordCxtParams, assign?: true): void { + if (assign) Object.assign(this.params, obj) + else this.params = obj + } + + block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { + this.gen.block(() => { + this.check$data(valid, $dataValid) + codeBlock() + }) + } + + check$data(valid: Name = nil, $dataValid: Code = nil): void { + if (!this.$data) return + const {gen, schemaCode, schemaType, def} = this + gen.if(or(_`${schemaCode} === undefined`, $dataValid)) + if (valid !== nil) gen.assign(valid, true) + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()) + this.$dataError() + if (valid !== nil) gen.assign(valid, false) + } + gen.else() + } + + invalid$data(): Code { + const {gen, schemaCode, schemaType, def, it} = this + return or(wrong$DataType(), invalid$DataSchema()) + + function wrong$DataType(): Code { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") + const st = Array.isArray(schemaType) ? schemaType : [schemaType] + return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` + } + return nil + } + + function invalid$DataSchema(): Code { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone + return _`!${validateSchemaRef}(${schemaCode})` + } + return nil + } + } + + subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { + const subschema = getSubschema(this.it, appl) + extendSubschemaData(subschema, this.it, appl) + extendSubschemaMode(subschema, appl) + const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} + subschemaCode(nextContext, valid) + return nextContext + } + + mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { + const {it, gen} = this + if (!it.opts.unevaluated) return + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) + } + } + + mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { + const {it, gen} = this + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) + return true + } + } +} + +function keywordCode( + it: SchemaObjCxt, + keyword: string, + def: AddedKeywordDefinition, + ruleType?: JSONType +): void { + const cxt = new KeywordCxt(it, def, keyword) + if ("code" in def) { + def.code(cxt, ruleType) + } else if (cxt.$data && def.validate) { + funcKeywordCode(cxt, def) + } else if ("macro" in def) { + macroKeywordCode(cxt, def) + } else if (def.compile || def.validate) { + funcKeywordCode(cxt, def) + } +} + +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ +export function getData( + $data: string, + {dataLevel, dataNames, dataPathArr}: SchemaCxt +): Code | number { + let jsonPointer + let data: Code + if ($data === "") return N.rootData + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) + jsonPointer = $data + data = N.rootData + } else { + const matches = RELATIVE_JSON_POINTER.exec($data) + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) + const up: number = +matches[1] + jsonPointer = matches[2] + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) + return dataPathArr[dataLevel - up] + } + if (up > dataLevel) throw new Error(errorMsg("data", up)) + data = dataNames[dataLevel - up] + if (!jsonPointer) return data + } + + let expr = data + const segments = jsonPointer.split("/") + for (const segment of segments) { + if (segment) { + data = _`${data}${getProperty(unescapeJsonPointer(segment))}` + expr = _`${expr} && ${data}` + } + } + return expr + + function errorMsg(pointerType: string, up: number): string { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/keyword.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/keyword.ts new file mode 100644 index 0000000000000000000000000000000000000000..f854aa71083ca28c01f8064fdca177a847e6f308 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/keyword.ts @@ -0,0 +1,171 @@ +import type {KeywordCxt} from "." +import type { + AnySchema, + SchemaValidateFunction, + AnyValidateFunction, + AddedKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import type {JSONType} from "../rules" +import {callValidateCode} from "../../vocabularies/code" +import {extendErrors} from "../errors" + +type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction + +export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, it} = cxt + const macroSchema = def.macro.call(it.self, schema, parentSchema, it) + const schemaRef = useKeyword(gen, keyword, macroSchema) + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true) + + const valid = gen.name("valid") + cxt.subschema( + { + schema: macroSchema, + schemaPath: nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, + valid + ) + cxt.pass(valid, () => cxt.error(true)) +} + +export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, $data, it} = cxt + checkAsyncKeyword(it, def) + const validate = + !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate + const validateRef = useKeyword(gen, keyword, validate) + const valid = gen.let("valid") + cxt.block$data(valid, validateKeyword) + cxt.ok(def.valid ?? valid) + + function validateKeyword(): void { + if (def.errors === false) { + assignValid() + if (def.modifying) modifyData(cxt) + reportErrs(() => cxt.error()) + } else { + const ruleErrs = def.async ? validateAsync() : validateSync() + if (def.modifying) modifyData(cxt) + reportErrs(() => addErrs(cxt, ruleErrs)) + } + } + + function validateAsync(): Name { + const ruleErrs = gen.let("ruleErrs", null) + gen.try( + () => assignValid(_`await `), + (e) => + gen.assign(valid, false).if( + _`${e} instanceof ${it.ValidationError as Name}`, + () => gen.assign(ruleErrs, _`${e}.errors`), + () => gen.throw(e) + ) + ) + return ruleErrs + } + + function validateSync(): Code { + const validateErrs = _`${validateRef}.errors` + gen.assign(validateErrs, null) + assignValid(nil) + return validateErrs + } + + function assignValid(_await: Code = def.async ? _`await ` : nil): void { + const passCxt = it.opts.passContext ? N.this : N.self + const passSchema = !(("compile" in def && !$data) || def.schema === false) + gen.assign( + valid, + _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, + def.modifying + ) + } + + function reportErrs(errors: () => void): void { + gen.if(not(def.valid ?? valid), errors) + } +} + +function modifyData(cxt: KeywordCxt): void { + const {gen, data, it} = cxt + gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) +} + +function addErrs(cxt: KeywordCxt, errs: Code): void { + const {gen} = cxt + gen.if( + _`Array.isArray(${errs})`, + () => { + gen + .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) + .assign(N.errors, _`${N.vErrors}.length`) + extendErrors(cxt) + }, + () => cxt.error() + ) +} + +function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") +} + +function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { + if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) + return gen.scopeValue( + "keyword", + typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} + ) +} + +export function validSchemaType( + schema: unknown, + schemaType: JSONType[], + allowUndefined = false +): boolean { + // TODO add tests + return ( + !schemaType.length || + schemaType.some((st) => + st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined") + ) + ) +} + +export function validateKeywordUsage( + {schema, opts, self, errSchemaPath}: SchemaObjCxt, + def: AddedKeywordDefinition, + keyword: string +): void { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error") + } + + const deps = def.dependencies + if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`) + } + + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]) + if (!valid) { + const msg = + `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors) + if (opts.validateSchema === "log") self.logger.error(msg) + else throw new Error(msg) + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/subschema.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/subschema.ts new file mode 100644 index 0000000000000000000000000000000000000000..9072ed7743decf23950a40033cb2c2f6ec1845e4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/compile/validate/subschema.ts @@ -0,0 +1,135 @@ +import type {AnySchema} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, str, getProperty, Code, Name} from "../codegen" +import {escapeFragment, getErrorPath, Type} from "../util" +import type {JSONType} from "../rules" + +export interface SubschemaContext { + // TODO use Optional? align with SchemCxt property types + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef?: Code + errorPath?: Code + dataLevel?: number + dataTypes?: JSONType[] + data?: Name + parentData?: Name + parentDataProperty?: Code | number + dataNames?: Name[] + dataPathArr?: (Code | number)[] + propertyName?: Name + jtdDiscriminator?: string + jtdMetadata?: boolean + compositeRule?: true + createErrors?: boolean + allErrors?: boolean +} + +export type SubschemaArgs = Partial<{ + keyword: string + schemaProp: string | number + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef: Code + data: Name | Code + dataProp: Code | string | number + dataTypes: JSONType[] + definedProperties: Set + propertyName: Name + dataPropType: Type + jtdDiscriminator: string + jtdMetadata: boolean + compositeRule: true + createErrors: boolean + allErrors: boolean +}> + +export function getSubschema( + it: SchemaObjCxt, + {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs +): SubschemaContext { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed') + } + + if (keyword !== undefined) { + const sch = it.schema[keyword] + return schemaProp === undefined + ? { + schema: sch, + schemaPath: _`${it.schemaPath}${getProperty(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`, + } + } + + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"') + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + } + } + + throw new Error('either "keyword" or "schema" must be passed') +} + +export function extendSubschemaData( + subschema: SubschemaContext, + it: SchemaObjCxt, + {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs +): void { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed') + } + + const {gen} = it + + if (dataProp !== undefined) { + const {errorPath, dataPathArr, opts} = it + const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true) + dataContextProps(nextData) + subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}` + subschema.parentDataProperty = _`${dataProp}` + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty] + } + + if (data !== undefined) { + const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once? + dataContextProps(nextData) + if (propertyName !== undefined) subschema.propertyName = propertyName + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + + if (dataTypes) subschema.dataTypes = dataTypes + + function dataContextProps(_nextData: Name): void { + subschema.data = _nextData + subschema.dataLevel = it.dataLevel + 1 + subschema.dataTypes = [] + it.definedProperties = new Set() + subschema.parentData = it.data + subschema.dataNames = [...it.dataNames, _nextData] + } +} + +export function extendSubschemaMode( + subschema: SubschemaContext, + {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs +): void { + if (compositeRule !== undefined) subschema.compositeRule = compositeRule + if (createErrors !== undefined) subschema.createErrors = createErrors + if (allErrors !== undefined) subschema.allErrors = allErrors + subschema.jtdDiscriminator = jtdDiscriminator // not inherited + subschema.jtdMetadata = jtdMetadata // not inherited +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/data.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/data.json new file mode 100644 index 0000000000000000000000000000000000000000..9ffc9f5ce05484799308bc4c78fd3a8822e9af53 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/data.json @@ -0,0 +1,13 @@ +{ + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { + "$data": { + "type": "string", + "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] + } + }, + "additionalProperties": false +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6ea7195f019ef1b91c45517db08f42daa2f0673 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts @@ -0,0 +1,28 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..c5e91cf2ac8469eccf444cf6501dba80dccb5c63 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f63734343046b3d4b74bf8a59f2380dbc67fc3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..f71adbff04fe9ecc6a828823ad5dfa7366f1a60f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 0000000000000000000000000000000000000000..03ccfce26efeaff5a6e223be5154f238f633c16e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..0e194326fa133b077af409486ebe1e2dca83feff --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..7027a1279a014a74c170a2558100d2ca37eecac0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..54eb7157afed6957bd7074068d7ad99498c668f3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e850d08b5cdc8ec9f41ff69581c11844c9c60af --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts @@ -0,0 +1,30 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as unevaluated from "./meta/unevaluated.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format-annotation.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..674c913dab00c66865d82027bdf7748e157365fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..2ae23ddb5cc30cce43646dc58b86f61b1dc7fc4c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8e5cb61657ff226186dd96e5dea6e15eb102e1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 0000000000000000000000000000000000000000..83c26e35f0042ebada16aba9b0c42bedd46bcb24 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..11946fb5019a3564afb38270af3d7806af39978c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4b203b2c26905ccef5ab90c627aaa19ee708bb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..e0ae13d9d2063403c60e88282701b4b8f6ccd5f5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1c68270fdc6e4fa807c75bb32391ce8cb530a497 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-06.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-06.json new file mode 100644 index 0000000000000000000000000000000000000000..5410064ba8df9315d61a34a66245311f1d18db8e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-06.json @@ -0,0 +1,137 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": {} + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": {} +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-07.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-07.json new file mode 100644 index 0000000000000000000000000000000000000000..6a74851043623c67cbe2e1cd206da447aff752c3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-draft-07.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": true + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": true +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-secure.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-secure.json new file mode 100644 index 0000000000000000000000000000000000000000..3968abd5d97e7b2cf87db34d5eb211c090b8700f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/json-schema-secure.json @@ -0,0 +1,88 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", + "title": "Meta-schema for the security assessment of JSON Schemas", + "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + } + }, + "dependencies": { + "patternProperties": { + "description": "prevent slow validation of large property names", + "required": ["propertyNames"], + "properties": { + "propertyNames": { + "required": ["maxLength"] + } + } + }, + "uniqueItems": { + "description": "prevent slow validation of large non-scalar arrays", + "if": { + "properties": { + "uniqueItems": {"const": true}, + "items": { + "properties": { + "type": { + "anyOf": [ + { + "enum": ["object", "array"] + }, + { + "type": "array", + "contains": {"enum": ["object", "array"]} + } + ] + } + } + } + } + }, + "then": { + "required": ["maxItems"] + } + }, + "pattern": { + "description": "prevent slow pattern matching of large strings", + "required": ["maxLength"] + }, + "format": { + "description": "prevent slow format validation of large strings", + "required": ["maxLength"] + } + }, + "properties": { + "additionalItems": {"$ref": "#"}, + "additionalProperties": {"$ref": "#"}, + "dependencies": { + "additionalProperties": { + "anyOf": [{"type": "array"}, {"$ref": "#"}] + } + }, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] + }, + "definitions": { + "additionalProperties": {"$ref": "#"} + }, + "patternProperties": { + "additionalProperties": {"$ref": "#"} + }, + "properties": { + "additionalProperties": {"$ref": "#"} + }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"}, + "contains": {"$ref": "#"}, + "propertyNames": {"$ref": "#"} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/jtd-schema.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0198128985137b24b13e40e6f41431f37b86647 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/refs/jtd-schema.ts @@ -0,0 +1,130 @@ +import {SchemaObject} from "../types" + +type MetaSchema = (root: boolean) => SchemaObject + +const shared: MetaSchema = (root) => { + const sch: SchemaObject = { + nullable: {type: "boolean"}, + metadata: { + optionalProperties: { + union: {elements: {ref: "schema"}}, + }, + additionalProperties: true, + }, + } + if (root) sch.definitions = {values: {ref: "schema"}} + return sch +} + +const emptyForm: MetaSchema = (root) => ({ + optionalProperties: shared(root), +}) + +const refForm: MetaSchema = (root) => ({ + properties: { + ref: {type: "string"}, + }, + optionalProperties: shared(root), +}) + +const typeForm: MetaSchema = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + ], + }, + }, + optionalProperties: shared(root), +}) + +const enumForm: MetaSchema = (root) => ({ + properties: { + enum: {elements: {type: "string"}}, + }, + optionalProperties: shared(root), +}) + +const elementsForm: MetaSchema = (root) => ({ + properties: { + elements: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const propertiesForm: MetaSchema = (root) => ({ + properties: { + properties: {values: {ref: "schema"}}, + }, + optionalProperties: { + optionalProperties: {values: {ref: "schema"}}, + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const optionalPropertiesForm: MetaSchema = (root) => ({ + properties: { + optionalProperties: {values: {ref: "schema"}}, + }, + optionalProperties: { + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const discriminatorForm: MetaSchema = (root) => ({ + properties: { + discriminator: {type: "string"}, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)], + }, + }, + }, + }, + optionalProperties: shared(root), +}) + +const valuesForm: MetaSchema = (root) => ({ + properties: { + values: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const schema: MetaSchema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm, + ].map((s) => s(root)), + }, +}) + +const jtdMetaSchema: SchemaObject = { + definitions: { + schema: schema(false), + }, + ...schema(true), +} + +export default jtdMetaSchema diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/equal.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/equal.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cb00631a2363720e822255d0911a54439512c3c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/equal.ts @@ -0,0 +1,7 @@ +// https://github.com/ajv-validator/ajv/issues/889 +import * as equal from "fast-deep-equal" + +type Equal = typeof equal & {code: string} +;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default' + +export default equal as Equal diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/parseJson.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/parseJson.ts new file mode 100644 index 0000000000000000000000000000000000000000..472e5e50786f2cff1092ac1353508ac0fcebce9e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/parseJson.ts @@ -0,0 +1,177 @@ +const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/ + +export function parseJson(s: string, pos: number): unknown { + let endPos: number | undefined + parseJson.message = undefined + let matches: RegExpExecArray | null + if (pos) s = s.slice(pos) + try { + parseJson.position = pos + s.length + return JSON.parse(s) + } catch (e) { + matches = rxParseJson.exec((e as Error).message) + if (!matches) { + parseJson.message = "unexpected end" + return undefined + } + endPos = +matches[1] + const c = s[endPos] + s = s.slice(0, endPos) + parseJson.position = pos + endPos + try { + return JSON.parse(s) + } catch (e1) { + parseJson.message = `unexpected token ${c}` + return undefined + } + } +} + +parseJson.message = undefined as string | undefined +parseJson.position = 0 as number +parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson' + +export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined { + let numStr = "" + let c: string + parseJsonNumber.message = undefined + if (s[pos] === "-") { + numStr += "-" + pos++ + } + if (s[pos] === "0") { + numStr += "0" + pos++ + } else { + if (!parseDigits(maxDigits)) { + errorMessage() + return undefined + } + } + if (maxDigits) { + parseJsonNumber.position = pos + return +numStr + } + if (s[pos] === ".") { + numStr += "." + pos++ + if (!parseDigits()) { + errorMessage() + return undefined + } + } + if (((c = s[pos]), c === "e" || c === "E")) { + numStr += "e" + pos++ + if (((c = s[pos]), c === "+" || c === "-")) { + numStr += c + pos++ + } + if (!parseDigits()) { + errorMessage() + return undefined + } + } + parseJsonNumber.position = pos + return +numStr + + function parseDigits(maxLen?: number): boolean { + let digit = false + while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { + digit = true + numStr += c + pos++ + } + return digit + } + + function errorMessage(): void { + parseJsonNumber.position = pos + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end" + } +} + +parseJsonNumber.message = undefined as string | undefined +parseJsonNumber.position = 0 as number +parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber' + +const escapedChars: {[X in string]?: string} = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + '"': '"', + "/": "/", + "\\": "\\", +} + +const CODE_A: number = "a".charCodeAt(0) +const CODE_0: number = "0".charCodeAt(0) + +export function parseJsonString(s: string, pos: number): string | undefined { + let str = "" + let c: string | undefined + parseJsonString.message = undefined + // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition + while (true) { + c = s[pos++] + if (c === '"') break + if (c === "\\") { + c = s[pos] + if (c in escapedChars) { + str += escapedChars[c] + pos++ + } else if (c === "u") { + pos++ + let count = 4 + let code = 0 + while (count--) { + code <<= 4 + c = s[pos] + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (c === undefined) { + errorMessage("unexpected end") + return undefined + } + c = c.toLowerCase() + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10 + } else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0 + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + pos++ + } + str += String.fromCharCode(code) + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + } else if (c === undefined) { + errorMessage("unexpected end") + return undefined + } else { + if (c.charCodeAt(0) >= 0x20) { + str += c + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + } + } + parseJsonString.position = pos + return str + + function errorMessage(msg: string): void { + parseJsonString.position = pos + parseJsonString.message = msg + } +} + +parseJsonString.message = undefined as string | undefined +parseJsonString.position = 0 as number +parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/quote.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/quote.ts new file mode 100644 index 0000000000000000000000000000000000000000..1160e6a23807cf7fc0f4d036ddc45bd962562275 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/quote.ts @@ -0,0 +1,31 @@ +const rxEscapable = + // eslint-disable-next-line no-control-regex, no-misleading-character-class + /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + +const escaped: {[K in string]?: string} = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\", +} + +export default function quote(s: string): string { + rxEscapable.lastIndex = 0 + return ( + '"' + + (rxEscapable.test(s) + ? s.replace(rxEscapable, (a) => { + const c = escaped[a] + return typeof c === "string" + ? c + : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) + }) + : s) + + '"' + ) +} + +quote.code = 'require("ajv/dist/runtime/quote").default' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/re2.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/re2.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c769bc7aefc5aa1924e2be877d39bc59670ab3f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/re2.ts @@ -0,0 +1,6 @@ +import * as re2 from "re2" + +type Re2 = typeof re2 & {code: string} +;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default' + +export default re2 as Re2 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/timestamp.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/timestamp.ts new file mode 100644 index 0000000000000000000000000000000000000000..1625f9a40f4443fde14743a6a8ecb6c1dc8fb819 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/timestamp.ts @@ -0,0 +1,46 @@ +const DT_SEPARATOR = /t|\s/i +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +export default function validTimestamp(str: string, allowDate: boolean): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dt: string[] = str.split(DT_SEPARATOR) + return ( + (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || + (allowDate && dt.length === 1 && validDate(dt[0])) + ) +} + +function validDate(str: string): boolean { + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const y: number = +matches[1] + const m: number = +matches[2] + const d: number = +matches[3] + return ( + m >= 1 && + m <= 12 && + d >= 1 && + (d <= DAYS[m] || + // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) + ) +} + +function validTime(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tzH: number = +(matches[4] || 0) + const tzM: number = +(matches[5] || 0) + return ( + (hr <= 23 && min <= 59 && sec <= 59) || + // leap second + (hr - tzH === 23 && min - tzM === 59 && sec === 60) + ) +} + +validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/ucs2length.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/ucs2length.ts new file mode 100644 index 0000000000000000000000000000000000000000..47d8292b83fde4619bdbf28b89e6720824a97164 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/ucs2length.ts @@ -0,0 +1,20 @@ +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +export default function ucs2length(str: string): number { + const len = str.length + let length = 0 + let pos = 0 + let value: number + while (pos < len) { + length++ + value = str.charCodeAt(pos++) + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos) + if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate + } + } + return length +} + +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/uri.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/uri.ts new file mode 100644 index 0000000000000000000000000000000000000000..5450549cd5a3968f163460d3c0fb1aeb7ffc2b2c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/uri.ts @@ -0,0 +1,6 @@ +import * as uri from "fast-uri" + +type URI = typeof uri & {code: string} +;(uri as URI).code = 'require("ajv/dist/runtime/uri").default' + +export default uri as URI diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/validation_error.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/validation_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d19a46a2245c667f479d7ee51d1d9558cd9ae90 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/runtime/validation_error.ts @@ -0,0 +1,13 @@ +import type {ErrorObject} from "../types" + +export default class ValidationError extends Error { + readonly errors: Partial[] + readonly ajv: true + readonly validation: true + + constructor(errors: Partial[]) { + super("validation failed") + this.errors = errors + this.ajv = this.validation = true + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6129ce9e5ebab51fe4f53ffa86dbacd12878ed9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/index.ts @@ -0,0 +1,100 @@ +import type AjvCore from "../core" +import type {AnyValidateFunction, SourceCode} from "../types" +import type {SchemaEnv} from "../compile" +import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope" +import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code" + +function standaloneCode( + ajv: AjvCore, + refsOrFunc?: {[K in string]?: string} | AnyValidateFunction +): string { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option") + } + const {_n} = ajv.scope.opts + return typeof refsOrFunc == "function" + ? funcExportCode(refsOrFunc.source) + : refsOrFunc !== undefined + ? multiExportsCode(refsOrFunc, getValidate) + : multiExportsCode(ajv.schemas, (sch) => + sch.meta ? undefined : ajv.compile(sch.schema) + ) + + function getValidate(id: string): AnyValidateFunction { + const v = ajv.getSchema(id) + if (!v) throw new Error(`moduleCode: no schema with id ${id}`) + return v + } + + function funcExportCode(source?: SourceCode): string { + const usedValues: UsedScopeValues = {} + const n = source?.validateName + const vCode = validateCode(usedValues, source) + if (ajv.opts.code.esm) { + // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}` + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}` + } + + function multiExportsCode( + schemas: {[K in string]?: T}, + getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined + ): string { + const usedValues: UsedScopeValues = {} + let code = _`"use strict";` + for (const name in schemas) { + const v = getValidateFunc(schemas[name] as T) + if (v) { + const vCode = validateCode(usedValues, v.source) + const exportSyntax = ajv.opts.code.esm + ? _`export const ${getEsmExportName(name)}` + : _`exports${getProperty(name)}` + code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}` + } + } + return `${code}` + } + + function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code { + if (!s) throw new Error('moduleCode: function does not have "source" property') + if (usedState(s.validateName) === UsedValueState.Completed) return nil + setUsedState(s.validateName, UsedValueState.Started) + + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode) + const code = new _Code(`${scopeCode}${_n}${s.validateCode}`) + return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code + + function refValidateCode(n: ValueScopeName): Code | undefined { + const vRef = n.value?.ref + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef as AnyValidateFunction + return validateCode(usedValues, v.source) + } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const {validate, validateName} = vRef as SchemaEnv + if (!validateName) throw new Error("ajv internal error") + const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const + const wrapper = _`${def} ${n} = {validate: ${validateName}};` + if (usedState(validateName) === UsedValueState.Started) return wrapper + const vCode = validateCode(usedValues, validate?.source) + return _`${wrapper}${_n}${vCode}` + } + return undefined + } + + function usedState(name: ValueScopeName): UsedValueState | undefined { + return usedValues[name.prefix]?.get(name) + } + + function setUsedState(name: ValueScopeName, state: UsedValueState): void { + const {prefix} = name + const names = (usedValues[prefix] = usedValues[prefix] || new Map()) + names.set(name, state) + } + } +} + +module.exports = exports = standaloneCode +Object.defineProperty(exports, "__esModule", {value: true}) + +export default standaloneCode diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/instance.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/instance.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4b2c30b58f0ebc89b4c8e1010e5976216c0042f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/standalone/instance.ts @@ -0,0 +1,36 @@ +import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core" +import standaloneCode from "." +import * as requireFromString from "require-from-string" + +export default class AjvPack { + errors?: ErrorObject[] | null // errors from the last validation + constructor(readonly ajv: Ajv) {} + + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise { + return Ajv.prototype.validate.call(this, schemaKeyRef, data) + } + + compile(schema: AnySchema, meta?: boolean): AnyValidateFunction { + return this.getStandalone(this.ajv.compile(schema, meta)) + } + + getSchema(keyRef: string): AnyValidateFunction | undefined { + const v = this.ajv.getSchema(keyRef) + if (!v) return undefined + return this.getStandalone(v) + } + + private getStandalone(v: AnyValidateFunction): AnyValidateFunction { + return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction + } + + addSchema(...args: Parameters): AjvPack { + this.ajv.addSchema.call(this.ajv, ...args) + return this + } + + addKeyword(...args: Parameters): AjvPack { + this.ajv.addKeyword.call(this.ajv, ...args) + return this + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..39bc51b0b99d79b09e3e5f0e2d0d48e7bf37c069 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/index.ts @@ -0,0 +1,244 @@ +import {URIComponent} from "fast-uri" +import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen" +import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile" +import type {JSONType} from "../compile/rules" +import type {KeywordCxt} from "../compile/validate" +import type Ajv from "../core" + +interface _SchemaObject { + id?: string + $id?: string + $schema?: string + [x: string]: any // TODO +} + +export interface SchemaObject extends _SchemaObject { + id?: string + $id?: string + $schema?: string + $async?: false + [x: string]: any // TODO +} + +export interface AsyncSchema extends _SchemaObject { + $async: true +} + +export type AnySchemaObject = SchemaObject | AsyncSchema + +export type Schema = SchemaObject | boolean + +export type AnySchema = Schema | AsyncSchema + +export type SchemaMap = {[Key in string]?: AnySchema} + +export interface SourceCode { + validateName: ValueScopeName + validateCode: string + scopeValues: ScopeValueSets + evaluated?: Code +} + +export interface DataValidationCxt { + instancePath: string + parentData: {[K in T]: any} // object or array + parentDataProperty: T // string or number + rootData: Record | any[] + dynamicAnchors: {[Ref in string]?: ValidateFunction} +} + +export interface ValidateFunction { + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T + errors?: null | ErrorObject[] + evaluated?: Evaluated + schema: AnySchema + schemaEnv: SchemaEnv + source?: SourceCode +} + +export interface JTDParser { + (json: string): T | undefined + message?: string + position?: number +} + +export type EvaluatedProperties = {[K in string]?: true} | true + +export type EvaluatedItems = number | true + +export interface Evaluated { + // determined at compile time if staticProps/Items is true + props?: EvaluatedProperties + items?: EvaluatedItems + // whether props/items determined at compile time + dynamicProps: boolean + dynamicItems: boolean +} + +export interface AsyncValidateFunction extends ValidateFunction { + (...args: Parameters>): Promise + $async: true +} + +export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction + +export interface ErrorObject, S = unknown> { + keyword: K + instancePath: string + schemaPath: string + params: P + // Added to validation errors of "propertyNames" keyword schema + propertyName?: string + // Excluded if option `messages` set to false. + message?: string + // These are added with the `verbose` option. + schema?: S + parentSchema?: AnySchemaObject + data?: unknown +} + +export type ErrorNoParams = ErrorObject, S> + +interface _KeywordDef { + keyword: string | string[] + type?: JSONType | JSONType[] // data types that keyword applies to + schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema + allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema + $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference) + implements?: string[] // other schema keywords that this keyword implements + before?: string // keyword should be executed before this keyword (should be applicable to the same type) + post?: boolean // keyword should be executed after other keywords without post flag + metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable + validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed + dependencies?: string[] // keywords that must be present in the same schema + error?: KeywordErrorDefinition + $dataError?: KeywordErrorDefinition +} + +export interface CodeKeywordDefinition extends _KeywordDef { + code: (cxt: KeywordCxt, ruleType?: string) => void + trackErrors?: boolean +} + +export type MacroKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaCxt +) => AnySchema + +export type CompileKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaObjCxt +) => DataValidateFunction + +export interface DataValidateFunction { + (...args: Parameters): boolean | Promise + errors?: Partial[] +} + +export interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: AnySchemaObject, + dataCxt?: DataValidationCxt + ): boolean | Promise + errors?: Partial[] +} + +export interface FuncKeywordDefinition extends _KeywordDef { + validate?: SchemaValidateFunction | DataValidateFunction + compile?: CompileKeywordFunc + // schema: false makes validate not to expect schema (DataValidateFunction) + schema?: boolean // requires "validate" + modifying?: boolean + async?: boolean + valid?: boolean + errors?: boolean | "full" +} + +export interface MacroKeywordDefinition extends FuncKeywordDefinition { + macro: MacroKeywordFunc +} + +export type KeywordDefinition = + | CodeKeywordDefinition + | FuncKeywordDefinition + | MacroKeywordDefinition + +export type AddedKeywordDefinition = KeywordDefinition & { + type: JSONType[] + schemaType: JSONType[] +} + +export interface KeywordErrorDefinition { + message: string | Code | ((cxt: KeywordErrorCxt) => string | Code) + params?: Code | ((cxt: KeywordErrorCxt) => Code) +} + +export type Vocabulary = (KeywordDefinition | string)[] + +export interface KeywordErrorCxt { + gen: CodeGen + keyword: string + data: Name + $data?: string | false + schema: any // TODO + parentSchema?: AnySchemaObject + schemaCode: Code | number | boolean + schemaValue: Code | number | boolean + schemaType?: JSONType[] + errsCount?: Name + params: KeywordCxtParams + it: SchemaCxt +} + +export type KeywordCxtParams = {[P in string]?: Code | string | number} + +export type FormatValidator = (data: T) => boolean + +export type FormatCompare = (data1: T, data2: T) => number | undefined + +export type AsyncFormatValidator = (data: T) => Promise + +export interface FormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: FormatValidator | (T extends string ? string | RegExp : never) + async?: false | undefined + compare?: FormatCompare +} + +export interface AsyncFormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: AsyncFormatValidator + async: true + compare?: FormatCompare +} + +export type AddedFormat = + | true + | RegExp + | FormatValidator + | FormatDefinition + | FormatDefinition + | AsyncFormatDefinition + | AsyncFormatDefinition + +export type Format = AddedFormat | string + +export interface RegExpEngine { + (pattern: string, u: string): RegExpLike + code: string +} + +export interface RegExpLike { + test: (s: string) => boolean +} + +export interface UriResolver { + parse(uri: string): URIComponent + resolve(base: string, path: string): string + serialize(component: URIComponent): string +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/json-schema.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/json-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..065c972e54a179b74e9dee48fdea8a1c2d45c8a1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/json-schema.ts @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-empty-interface */ +type StrictNullChecksWrapper = undefined extends null + ? `strictNullChecks must be true in tsconfig to use ${Name}` + : Type + +type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void + ? I + : never + +export type SomeJSONSchema = UncheckedJSONSchemaType + +type UncheckedPartialSchema = Partial> + +export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema> + +type JSONType = IsPartial extends true + ? T | undefined + : T + +interface NumberKeywords { + minimum?: number + maximum?: number + exclusiveMinimum?: number + exclusiveMaximum?: number + multipleOf?: number + format?: string +} + +interface StringKeywords { + minLength?: number + maxLength?: number + pattern?: string + format?: string +} + +type UncheckedJSONSchemaType = ( + | // these two unions allow arbitrary unions of types + { + anyOf: readonly UncheckedJSONSchemaType[] + } + | { + oneOf: readonly UncheckedJSONSchemaType[] + } + // this union allows for { type: (primitive)[] } style schemas + | ({ + type: readonly (T extends number + ? JSONType<"number" | "integer", IsPartial> + : T extends string + ? JSONType<"string", IsPartial> + : T extends boolean + ? JSONType<"boolean", IsPartial> + : never)[] + } & UnionToIntersection< + T extends number + ? NumberKeywords + : T extends string + ? StringKeywords + : T extends boolean + ? // eslint-disable-next-line @typescript-eslint/ban-types + {} + : never + >) + // this covers "normal" types; it's last so typescript looks to it first for errors + | ((T extends number + ? { + type: JSONType<"number" | "integer", IsPartial> + } & NumberKeywords + : T extends string + ? { + type: JSONType<"string", IsPartial> + } & StringKeywords + : T extends boolean + ? { + type: JSONType<"boolean", IsPartial> + } + : T extends readonly [any, ...any[]] + ? { + // JSON AnySchema for tuple + type: JSONType<"array", IsPartial> + items: { + readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable + } & {length: T["length"]} + minItems: T["length"] + } & ({maxItems: T["length"]} | {additionalItems: false}) + : T extends readonly any[] + ? { + type: JSONType<"array", IsPartial> + items: UncheckedJSONSchemaType + contains?: UncheckedPartialSchema + minItems?: number + maxItems?: number + minContains?: number + maxContains?: number + uniqueItems?: true + additionalItems?: never + } + : T extends Record + ? { + // JSON AnySchema for records and dictionaries + // "required" is not optional because it is often forgotten + // "properties" are optional for more concise dictionary schemas + // "patternProperties" and can be only used with interfaces that have string index + type: JSONType<"object", IsPartial> + additionalProperties?: boolean | UncheckedJSONSchemaType + unevaluatedProperties?: boolean | UncheckedJSONSchemaType + properties?: IsPartial extends true + ? Partial> + : UncheckedPropertiesSchema + patternProperties?: Record> + propertyNames?: Omit, "type"> & {type?: "string"} + dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema} + dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]} + dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema} + minProperties?: number + maxProperties?: number + } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties + ? {required: readonly (keyof T)[]} + : [UncheckedRequiredMembers] extends [never] + ? {required?: readonly UncheckedRequiredMembers[]} + : {required: readonly UncheckedRequiredMembers[]}) + : T extends null + ? { + type: JSONType<"null", IsPartial> + nullable: true + } + : never) & { + allOf?: readonly UncheckedPartialSchema[] + anyOf?: readonly UncheckedPartialSchema[] + oneOf?: readonly UncheckedPartialSchema[] + if?: UncheckedPartialSchema + then?: UncheckedPartialSchema + else?: UncheckedPartialSchema + not?: UncheckedPartialSchema + }) +) & { + [keyword: string]: any + $id?: string + $ref?: string + $defs?: Record> + definitions?: Record> +} + +export type JSONSchemaType = StrictNullChecksWrapper< + "JSONSchemaType", + UncheckedJSONSchemaType +> + +type Known = + | {[key: string]: Known} + | [Known, ...Known[]] + | Known[] + | number + | string + | boolean + | null + +type UncheckedPropertiesSchema = { + [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | {$ref: string} +} + +export type PropertiesSchema = StrictNullChecksWrapper< + "PropertiesSchema", + UncheckedPropertiesSchema +> + +type UncheckedRequiredMembers = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +export type RequiredMembers = StrictNullChecksWrapper< + "RequiredMembers", + UncheckedRequiredMembers +> + +type Nullable = undefined extends T + ? { + nullable: true + const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const + enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass + default?: T | null + } + : { + nullable?: false + const?: T + enum?: readonly T[] + default?: T + } diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/jtd-schema.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..61b2bde81d5f5d407971855d0a2c8125aeb53463 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/types/jtd-schema.ts @@ -0,0 +1,273 @@ +/** numeric strings */ +type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +/** string strings */ +type StringType = "string" | "timestamp" + +/** Generic JTD Schema without inference of the represented type */ +export type SomeJTDSchemaType = ( + | // ref + {ref: string} + // primitives + | {type: NumberType | StringType | "boolean"} + // enum + | {enum: string[]} + // elements + | {elements: SomeJTDSchemaType} + // values + | {values: SomeJTDSchemaType} + // properties + | { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + | { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + // discriminator + | {discriminator: string; mapping: Record} + // empty + // NOTE see the end of + // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492 + // eslint-disable-next-line @typescript-eslint/ban-types + | {} +) & { + nullable?: boolean + metadata?: Record + definitions?: Record +} + +/** required keys of an object, not undefined */ +type RequiredKeys = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +/** optional or undifined-able keys of an object */ +type OptionalKeys = { + [K in keyof T]-?: undefined extends T[K] ? K : never +}[keyof T] + +/** type is true if T is a union type */ +type IsUnion_ = false extends ( + T extends unknown ? ([U] extends [T] ? false : true) : never +) + ? false + : true +type IsUnion = IsUnion_ + +/** type is true if T is identically E */ +type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false + +/** type is true if T or null is identically E or null*/ +type NullTypeEquality = TypeEquality + +/** gets only the string literals of a type or null if a type isn't a string literal */ +type EnumString = [T] extends [never] + ? null + : T extends string + ? string extends T + ? null + : T + : null + +/** true if type is a union of string literals */ +type IsEnum = null extends EnumString ? false : true + +/** true only if all types are array types (not tuples) */ +// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays +// have an index at every number +type IsElements = false extends IsUnion + ? [T] extends [readonly unknown[]] + ? undefined extends T[0.5] + ? false + : true + : false + : false + +/** true if the the type is a values type */ +type IsValues = false extends IsUnion ? TypeEquality : false + +/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ +type IsRecord = Union extends IsUnion + ? null extends EnumString + ? false + : true + : false + +/** true if type represents an empty record */ +type IsEmptyRecord = [T] extends [Record] + ? [T] extends [never] + ? false + : true + : false + +/** actual schema */ +export type JTDSchemaType = Record> = ( + | // refs - where null wasn't specified, must match exactly + (null extends EnumString + ? never + : + | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false}) + // nulled refs - if ref is nullable and nullable is specified, then it can + // match either null or non-null definitions + | (null extends T + ? { + [K in keyof D]: [Exclude] extends [Exclude] + ? {ref: K} + : never + }[keyof D] & {nullable: true} + : never)) + // empty - empty schemas also treat nullable differently in that it's now fully ignored + | (unknown extends T ? {nullable?: boolean} : never) + // all other types // numbers - only accepts the type number + | ((true extends NullTypeEquality + ? {type: NumberType} + : // booleans - accepts the type boolean + true extends NullTypeEquality + ? {type: "boolean"} + : // strings - only accepts the type string + true extends NullTypeEquality + ? {type: StringType} + : // strings - only accepts the type Date + true extends NullTypeEquality + ? {type: "timestamp"} + : // enums - only accepts union of string literals + // TODO we can't actually check that everything in the union was specified + true extends IsEnum> + ? {enum: EnumString>[]} + : // arrays - only accepts arrays, could be array of unions to be resolved later + true extends IsElements> + ? T extends readonly (infer E)[] + ? { + elements: JTDSchemaType + } + : never + : // empty properties + true extends IsEmptyRecord> + ? + | {properties: Record; optionalProperties?: Record} + | {optionalProperties: Record} + : // values + true extends IsValues> + ? T extends Record + ? { + values: JTDSchemaType + } + : never + : // properties + true extends IsRecord, false> + ? ([RequiredKeys>] extends [never] + ? { + properties?: Record + } + : { + properties: {[K in RequiredKeys]: JTDSchemaType} + }) & + ([OptionalKeys>] extends [never] + ? { + optionalProperties?: Record + } + : { + optionalProperties: { + [K in OptionalKeys]: JTDSchemaType, D> + } + }) & { + additionalProperties?: boolean + } + : // discriminator + true extends IsRecord, true> + ? { + [K in keyof Exclude]-?: Exclude[K] extends string + ? { + discriminator: K + mapping: { + // TODO currently allows descriminator to be present in schema + [M in Exclude[K]]: JTDSchemaType< + Omit ? T : never, K>, + D + > + } + } + : never + }[keyof Exclude] + : never) & + (null extends T + ? { + nullable: true + } + : {nullable?: false})) +) & { + // extra properties + metadata?: Record + // TODO these should only be allowed at the top level + definitions?: {[K in keyof D]: JTDSchemaType} +} + +type JTDDataDef> = + | // ref + (S extends {ref: string} + ? D extends {[K in S["ref"]]: infer V} + ? JTDDataDef + : never + : // type + S extends {type: NumberType} + ? number + : S extends {type: "boolean"} + ? boolean + : S extends {type: "string"} + ? string + : S extends {type: "timestamp"} + ? string | Date + : // enum + S extends {enum: readonly (infer E)[]} + ? string extends E + ? never + : [E] extends [string] + ? E + : never + : // elements + S extends {elements: infer E} + ? JTDDataDef[] + : // properties + S extends { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : S extends { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : // values + S extends {values: infer V} + ? Record> + : // discriminator + S extends {discriminator: infer M; mapping: Record} + ? [M] extends [string] + ? { + [K in keyof S["mapping"]]: JTDDataDef & {[KM in M]: K} + }[keyof S["mapping"]] + : never + : // empty + unknown) + | (S extends {nullable: true} ? null : never) + +export type JTDDataType = S extends {definitions: Record} + ? JTDDataDef + : JTDDataDef> diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..755e5b3daf551d68ffbe3bd45884ee650094a46d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts @@ -0,0 +1,56 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "additionalItems" as const, + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {parentSchema, it} = cxt + const {items} = parentSchema + if (!Array.isArray(items)) { + checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') + return + } + validateAdditionalItems(cxt, items) + }, +} + +export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { + const {gen, schema, data, keyword, it} = cxt + it.items = true + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items.length}) + cxt.pass(_`${len} <= ${items.length}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var + gen.if(not(valid), () => validateItems(valid)) + cxt.ok(valid) + } + + function validateItems(valid: Name): void { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb511ce5100f4902f0f9c17ce7d7886e95fcabc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts @@ -0,0 +1,118 @@ +import type { + CodeKeywordDefinition, + AddedKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import {allSchemaProperties, usePattern, isOwnProperty} from "../code" +import {_, nil, or, not, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import type {SubschemaArgs} from "../../compile/validate/subschema" +import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util" + +export type AdditionalPropertiesError = ErrorObject< + "additionalProperties", + {additionalProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have additional properties", + params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +} + +const def: CodeKeywordDefinition & AddedKeywordDefinition = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const {gen, schema, parentSchema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, opts} = it + it.props = true + if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return + const props = allSchemaProperties(parentSchema.properties) + const patProps = allSchemaProperties(parentSchema.patternProperties) + checkAdditionalProperties() + cxt.ok(_`${errsCount} === ${N.errors}`) + + function checkAdditionalProperties(): void { + gen.forIn("key", data, (key: Name) => { + if (!props.length && !patProps.length) additionalPropertyCode(key) + else gen.if(isAdditional(key), () => additionalPropertyCode(key)) + }) + } + + function isAdditional(key: Name): Code { + let definedProp: Code + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") + definedProp = isOwnProperty(gen, propsSchema as Code, key) + } else if (props.length) { + definedProp = or(...props.map((p) => _`${key} === ${p}`)) + } else { + definedProp = nil + } + if (patProps.length) { + definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) + } + return not(definedProp) + } + + function deleteAdditional(key: Name): void { + gen.code(_`delete ${data}[${key}]`) + } + + function additionalPropertyCode(key: Name): void { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key) + return + } + + if (schema === false) { + cxt.setParams({additionalProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false) + gen.if(not(valid), () => { + cxt.reset() + deleteAdditional(key) + }) + } else { + applyAdditionalSchema(key, valid) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + } + + function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { + const subschema: SubschemaArgs = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: Type.Str, + } + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }) + } + cxt.subschema(subschema, valid) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/allOf.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/allOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdfa86ff431396a7cf68b937cb9baa69d4e79f29 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/allOf.ts @@ -0,0 +1,22 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "allOf", + schemaType: "array", + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const valid = gen.name("valid") + schema.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) + cxt.ok(valid) + cxt.mergeEvaluated(schCxt) + }) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd331b5ae98a72f1a6d79aacdf2d4babd16bde35 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import {validateUnion} from "../code" + +export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]> + +const def: CodeKeywordDefinition = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in anyOf"}, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/contains.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/contains.ts new file mode 100644 index 0000000000000000000000000000000000000000..d88675c6c2a21db9fa9e0ce497646fda1bf5d5a6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/contains.ts @@ -0,0 +1,109 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type ContainsError = ErrorObject< + "contains", + {minContains: number; maxContains?: number}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: ({params: {min, max}}) => + max === undefined + ? str`must contain at least ${min} valid item(s)` + : str`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({params: {min, max}}) => + max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + let min: number + let max: number | undefined + const {minContains, maxContains} = parentSchema + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains + max = maxContains + } else { + min = 1 + } + const len = gen.const("len", _`${data}.length`) + cxt.setParams({min, max}) + if (max === undefined && min === 0) { + checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) + return + } + if (max !== undefined && min > max) { + checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) + cxt.fail() + return + } + if (alwaysValidSchema(it, schema)) { + let cond = _`${len} >= ${min}` + if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` + cxt.pass(cond) + return + } + + it.items = true + const valid = gen.name("valid") + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())) + } else if (min === 0) { + gen.let(valid, true) + if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) + } else { + gen.let(valid, false) + validateItemsWithCount() + } + cxt.result(valid, () => cxt.reset()) + + function validateItemsWithCount(): void { + const schValid = gen.name("_valid") + const count = gen.let("count", 0) + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) + } + + function validateItems(_valid: Name, block: () => void): void { + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword: "contains", + dataProp: i, + dataPropType: Type.Num, + compositeRule: true, + }, + _valid + ) + block() + }) + } + + function checkLimits(count: Name): void { + gen.code(_`${count}++`) + if (max === undefined) { + gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) + } else { + gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) + if (min === 1) gen.assign(valid, true) + else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) + } + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6761128698689ce1d4699c33a3b128516157eeb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts @@ -0,0 +1,112 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaMap, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code" + +export type PropertyDependencies = {[K in string]?: string[]} + +export interface DependenciesErrorParams { + property: string + missingProperty: string + depsCount: number + deps: string // TODO change to string[] +} + +type SchemaDependencies = SchemaMap + +export type DependenciesError = ErrorObject< + "dependencies", + DependenciesErrorParams, + {[K in string]?: string[] | AnySchema} +> + +export const error: KeywordErrorDefinition = { + message: ({params: {property, depsCount, deps}}) => { + const property_ies = depsCount === 1 ? "property" : "properties" + return str`must have ${property_ies} ${deps} when property ${property} is present` + }, + params: ({params: {property, depsCount, deps, missingProperty}}) => + _`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +} + +const def: CodeKeywordDefinition = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const [propDeps, schDeps] = splitDependencies(cxt) + validatePropertyDeps(cxt, propDeps) + validateSchemaDeps(cxt, schDeps) + }, +} + +function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { + const propertyDeps: PropertyDependencies = {} + const schemaDeps: SchemaDependencies = {} + for (const key in schema) { + if (key === "__proto__") continue + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps + deps[key] = schema[key] + } + return [propertyDeps, schemaDeps] +} + +export function validatePropertyDeps( + cxt: KeywordCxt, + propertyDeps: {[K in string]?: string[]} = cxt.schema +): void { + const {gen, data, it} = cxt + if (Object.keys(propertyDeps).length === 0) return + const missing = gen.let("missing") + for (const prop in propertyDeps) { + const deps = propertyDeps[prop] as string[] + if (deps.length === 0) continue + const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }) + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + checkReportMissingProp(cxt, depProp) + } + }) + } else { + gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) + reportMissingProp(cxt, missing) + gen.else() + } + } +} + +export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + for (const prop in schemaDeps) { + if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) + cxt.mergeValidEvaluated(schCxt, valid) + }, + () => gen.var(valid, true) // TODO var + ) + cxt.ok(valid) + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbd3ae45c38f2e0a4c958a83694eaf5844440e7e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts @@ -0,0 +1,11 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateSchemaDeps} from "./dependencies" + +const def: CodeKeywordDefinition = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => validateSchemaDeps(cxt), +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/if.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/if.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a40d5e3ad2ca0ee8bffb0bc10c361580a15378f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/if.ts @@ -0,0 +1,80 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {SchemaObjCxt} from "../../compile" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" + +export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params}) => str`must match "${params.ifClause}" schema`, + params: ({params}) => _`{failingKeyword: ${params.ifClause}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, parentSchema, it} = cxt + if (parentSchema.then === undefined && parentSchema.else === undefined) { + checkStrictMode(it, '"if" without "then" and "else" is ignored') + } + const hasThen = hasSchema(it, "then") + const hasElse = hasSchema(it, "else") + if (!hasThen && !hasElse) return + + const valid = gen.let("valid", true) + const schValid = gen.name("_valid") + validateIf() + cxt.reset() + + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause") + cxt.setParams({ifClause}) + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) + } else if (hasThen) { + gen.if(schValid, validateClause("then")) + } else { + gen.if(not(schValid), validateClause("else")) + } + + cxt.pass(valid, () => cxt.error(true)) + + function validateIf(): void { + const schCxt = cxt.subschema( + { + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + schValid + ) + cxt.mergeEvaluated(schCxt) + } + + function validateClause(keyword: string, ifClause?: Name): () => void { + return () => { + const schCxt = cxt.subschema({keyword}, schValid) + gen.assign(valid, schValid) + cxt.mergeValidEvaluated(schCxt, valid) + if (ifClause) gen.assign(ifClause, _`${keyword}`) + else cxt.setParams({ifClause: keyword}) + } + } + }, +} + +function hasSchema(it: SchemaObjCxt, keyword: string): boolean { + const schema = it.schema[keyword] + return schema !== undefined && !alwaysValidSchema(it, schema) +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc527169967c8e3ae32b13ee19c9ad20dc5794cc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/index.ts @@ -0,0 +1,53 @@ +import type {ErrorNoParams, Vocabulary} from "../../types" +import additionalItems, {AdditionalItemsError} from "./additionalItems" +import prefixItems from "./prefixItems" +import items from "./items" +import items2020, {ItemsError} from "./items2020" +import contains, {ContainsError} from "./contains" +import dependencies, {DependenciesError} from "./dependencies" +import propertyNames, {PropertyNamesError} from "./propertyNames" +import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties" +import properties from "./properties" +import patternProperties from "./patternProperties" +import notKeyword, {NotKeywordError} from "./not" +import anyOf, {AnyOfError} from "./anyOf" +import oneOf, {OneOfError} from "./oneOf" +import allOf from "./allOf" +import ifKeyword, {IfKeywordError} from "./if" +import thenElse from "./thenElse" + +export default function getApplicator(draft2020 = false): Vocabulary { + const applicator = [ + // any + notKeyword, + anyOf, + oneOf, + allOf, + ifKeyword, + thenElse, + // object + propertyNames, + additionalProperties, + dependencies, + properties, + patternProperties, + ] + // array + if (draft2020) applicator.push(prefixItems, items2020) + else applicator.push(additionalItems, items) + applicator.push(contains) + return applicator +} + +export type ApplicatorKeywordError = + | ErrorNoParams<"false schema"> + | AdditionalItemsError + | ItemsError + | ContainsError + | AdditionalPropertiesError + | DependenciesError + | IfKeywordError + | AnyOfError + | OneOfError + | NotKeywordError + | PropertyNamesError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items.ts new file mode 100644 index 0000000000000000000000000000000000000000..033cb3977342222bc90a44251bc9366b151cff9f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items.ts @@ -0,0 +1,59 @@ +import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util" +import {validateArray} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt: KeywordCxt) { + const {schema, it} = cxt + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) + it.items = true + if (alwaysValidSchema(it, schema)) return + cxt.ok(validateArray(cxt)) + }, +} + +export function validateTuple( + cxt: KeywordCxt, + extraItems: string, + schArr: AnySchema[] = cxt.schema +): void { + const {gen, parentSchema, data, keyword, it} = cxt + checkStrictTuple(parentSchema) + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = mergeEvaluated.items(gen, schArr.length, it.items) + } + const valid = gen.name("valid") + const len = gen.const("len", _`${data}.length`) + schArr.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + gen.if(_`${len} > ${i}`, () => + cxt.subschema( + { + keyword, + schemaProp: i, + dataProp: i, + }, + valid + ) + ) + cxt.ok(valid) + }) + + function checkStrictTuple(sch: AnySchemaObject): void { + const {opts, errSchemaPath} = it + const l = schArr.length + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` + checkStrictMode(it, msg, opts.strictTuples) + } + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items2020.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a99b08d59adc2ce8fc6c785a5ccc34c0960c1f9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/items2020.ts @@ -0,0 +1,36 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {validateAdditionalItems} from "./additionalItems" + +export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {schema, parentSchema, it} = cxt + const {prefixItems} = parentSchema + it.items = true + if (alwaysValidSchema(it, schema)) return + if (prefixItems) validateAdditionalItems(cxt, prefixItems) + else cxt.ok(validateArray(cxt)) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/not.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/not.ts new file mode 100644 index 0000000000000000000000000000000000000000..8691db0bf229b778f88a373110311dff1c69c1dc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/not.ts @@ -0,0 +1,38 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +export type NotKeywordError = ErrorNoParams<"not", AnySchema> + +const def: CodeKeywordDefinition = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) { + cxt.fail() + return + } + + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + valid + ) + + cxt.failResult( + valid, + () => cxt.reset(), + () => cxt.error() + ) + }, + error: {message: "must NOT be valid"}, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25353ffd648c45dce2433c14cb27841763d5435 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts @@ -0,0 +1,82 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, Name} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {SchemaCxt} from "../../compile" + +export type OneOfError = ErrorObject< + "oneOf", + {passingSchemas: [number, number] | null}, + AnySchema[] +> + +const error: KeywordErrorDefinition = { + message: "must match exactly one schema in oneOf", + params: ({params}) => _`{passingSchemas: ${params.passing}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + if (it.opts.discriminator && parentSchema.discriminator) return + const schArr: AnySchema[] = schema + const valid = gen.let("valid", false) + const passing = gen.let("passing", null) + const schValid = gen.name("_valid") + cxt.setParams({passing}) + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + + gen.block(validateOneOf) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) + + function validateOneOf(): void { + schArr.forEach((sch: AnySchema, i: number) => { + let schCxt: SchemaCxt | undefined + if (alwaysValidSchema(it, sch)) { + gen.var(schValid, true) + } else { + schCxt = cxt.subschema( + { + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, + schValid + ) + } + + if (i > 0) { + gen + .if(_`${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, _`[${passing}, ${i}]`) + .else() + } + + gen.if(schValid, () => { + gen.assign(valid, true) + gen.assign(passing, i) + if (schCxt) cxt.mergeEvaluated(schCxt, Name) + }) + }) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea624e230dddb3d71320eb5255a2b89bae5f20b0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts @@ -0,0 +1,91 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {allSchemaProperties, usePattern} from "../code" +import {_, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" +import {evaluatedPropsToName, Type} from "../../compile/util" +import {AnySchema} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, data, parentSchema, it} = cxt + const {opts} = it + const patterns = allSchemaProperties(schema) + const alwaysValidPatterns = patterns.filter((p) => + alwaysValidSchema(it, schema[p] as AnySchema) + ) + + if ( + patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true)) + ) { + return + } + + const checkProperties = + opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties + const valid = gen.name("valid") + if (it.props !== true && !(it.props instanceof Name)) { + it.props = evaluatedPropsToName(gen, it.props) + } + const {props} = it + validatePatternProperties() + + function validatePatternProperties(): void { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat) + if (it.allErrors) { + validateProperties(pat) + } else { + gen.var(valid, true) // TODO var + validateProperties(pat) + gen.if(valid) + } + } + } + + function checkMatchingProperties(pat: string): void { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + checkStrictMode( + it, + `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` + ) + } + } + } + + function validateProperties(pat: string): void { + gen.forIn("key", data, (key) => { + gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat) + if (!alwaysValid) { + cxt.subschema( + { + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + } + + if (it.opts.unevaluated && props !== true) { + gen.assign(_`${props}[${key}]`, true) + } else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if(not(valid), () => gen.break()) + } + }) + }) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..008fb2db1d8dd898fa79226d118530af2628c2c8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateTuple} from "./items" + +const def: CodeKeywordDefinition = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => validateTuple(cxt, "items"), +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/properties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..a55b19ce5b77d180ce94cb063946a08d22824bd1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/properties.ts @@ -0,0 +1,57 @@ +import type {CodeKeywordDefinition} from "../../types" +import {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties} from "../code" +import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util" +import apDef from "./additionalProperties" + +const def: CodeKeywordDefinition = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) + } + const allProps = allSchemaProperties(schema) + for (const prop of allProps) { + it.definedProperties.add(prop) + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) + } + const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) + if (properties.length === 0) return + const valid = gen.name("valid") + + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop) + } else { + gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) + applyPropertySchema(prop) + if (!it.allErrors) gen.else().var(valid, true) + gen.endIf() + } + cxt.it.definedProperties.add(prop) + cxt.ok(valid) + } + + function hasDefault(prop: string): boolean | undefined { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined + } + + function applyPropertySchema(prop: string): void { + cxt.subschema( + { + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, + valid + ) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c54d605258600f3e98d4eeb17e87256be6b9f3f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts @@ -0,0 +1,50 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" + +export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: "property name must be valid", + params: ({params}) => _`{propertyName: ${params.propertyName}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + + gen.forIn("key", data, (key) => { + cxt.setParams({propertyName: key}) + cxt.subschema( + { + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, + valid + ) + gen.if(not(valid), () => { + cxt.error(true) + if (!it.allErrors) gen.break() + }) + }) + + cxt.ok(valid) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts new file mode 100644 index 0000000000000000000000000000000000000000..5055182e89141a257630516d96a52ec2917f72b6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts @@ -0,0 +1,13 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/code.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..92cdd5b04ef30e0ed6f3c9025752f0acf59370eb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/code.ts @@ -0,0 +1,168 @@ +import type {AnySchema, SchemaMap} from "../types" +import type {SchemaCxt} from "../compile" +import type {KeywordCxt} from "../compile/validate" +import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen" +import {alwaysValidSchema, Type} from "../compile/util" +import N from "../compile/names" +import {useFunc} from "../compile/util" +export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void { + const {gen, data, it} = cxt + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({missingProperty: _`${prop}`}, true) + cxt.error() + }) +} + +export function checkMissingProp( + {gen, data, it: {opts}}: KeywordCxt, + properties: string[], + missing: Name +): Code { + return or( + ...properties.map((prop) => + and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`) + ) + ) +} + +export function reportMissingProp(cxt: KeywordCxt, missing: Name): void { + cxt.setParams({missingProperty: missing}, true) + cxt.error() +} + +export function hasPropFunc(gen: CodeGen): Name { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: _`Object.prototype.hasOwnProperty`, + }) +} + +export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code { + return _`${hasPropFunc(gen)}.call(${data}, ${property})` +} + +export function propertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} !== undefined` + return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond +} + +export function noPropertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} === undefined` + return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond +} + +export function allSchemaProperties(schemaMap?: SchemaMap): string[] { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [] +} + +export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] { + return allSchemaProperties(schemaMap).filter( + (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema) + ) +} + +export function callValidateCode( + {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt, + func: Code, + context: Code, + passSchema?: boolean +): Code { + const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data + const valCxt: [Name, Code | number][] = [ + [N.instancePath, strConcat(N.instancePath, errorPath)], + [N.parentData, it.parentData], + [N.parentDataProperty, it.parentDataProperty], + [N.rootData, N.rootData], + ] + if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors]) + const args = _`${dataAndSchema}, ${gen.object(...valCxt)}` + return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})` +} + +const newRegExp = _`new RegExp` + +export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name { + const u = opts.unicodeRegExp ? "u" : "" + const {regExp} = opts.code + const rx = regExp(pattern, u) + + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`, + }) +} + +export function validateArray(cxt: KeywordCxt): Name { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + if (it.allErrors) { + const validArr = gen.let("valid", true) + validateItems(() => gen.assign(validArr, false)) + return validArr + } + gen.var(valid, true) + validateItems(() => gen.break()) + return valid + + function validateItems(notValid: () => void): void { + const len = gen.const("len", _`${data}.length`) + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword, + dataProp: i, + dataPropType: Type.Num, + }, + valid + ) + gen.if(not(valid), notValid) + }) + } +} + +export function validateUnion(cxt: KeywordCxt): void { + const {gen, schema, keyword, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch)) + if (alwaysValid && !it.opts.unevaluated) return + + const valid = gen.let("valid", false) + const schValid = gen.name("_valid") + + gen.block(() => + schema.forEach((_sch: AnySchema, i: number) => { + const schCxt = cxt.subschema( + { + keyword, + schemaProp: i, + compositeRule: true, + }, + schValid + ) + gen.assign(valid, _`${valid} || ${schValid}`) + const merged = cxt.mergeValidEvaluated(schCxt, schValid) + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) gen.if(not(valid)) + }) + ) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/id.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/id.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa36c4bb20f45046bb46fc998ca39fa2d9589811 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/id.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID') + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e63e2895d08710745fe5785bbdb1aaf155e05407 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/index.ts @@ -0,0 +1,16 @@ +import type {Vocabulary} from "../../types" +import idKeyword from "./id" +import refKeyword from "./ref" + +const core: Vocabulary = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + {keyword: "$comment"}, + "definitions", + idKeyword, + refKeyword, +] + +export default core diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/ref.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d59fbcb2a99564106fdcafe244f693bc88e3ea2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/core/ref.ts @@ -0,0 +1,129 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import MissingRefError from "../../compile/ref_error" +import {callValidateCode} from "../code" +import {_, nil, stringify, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, resolveRef} from "../../compile" +import {mergeEvaluated} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$ref", + schemaType: "string", + code(cxt: KeywordCxt): void { + const {gen, schema: $ref, it} = cxt + const {baseId, schemaEnv: env, validateName, opts, self} = it + const {root} = env + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() + const schOrEnv = resolveRef.call(self, root, baseId, $ref) + if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) + if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) + return inlineRefSchema(schOrEnv) + + function callRootRef(): void { + if (env === root) return callRef(cxt, validateName, env, env.$async) + const rootName = gen.scopeValue("root", {ref: root}) + return callRef(cxt, _`${rootName}.validate`, root, root.$async) + } + + function callValidate(sch: SchemaEnv): void { + const v = getValidate(cxt, sch) + callRef(cxt, v, sch, sch.$async) + } + + function inlineRefSchema(sch: AnySchema): void { + const schName = gen.scopeValue( + "schema", + opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} + ) + const valid = gen.name("valid") + const schCxt = cxt.subschema( + { + schema: sch, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, + valid + ) + cxt.mergeEvaluated(schCxt) + cxt.ok(valid) + } + }, +} + +export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { + const {gen} = cxt + return sch.validate + ? gen.scopeValue("validate", {ref: sch.validate}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` +} + +export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { + const {gen, it} = cxt + const {allErrors, schemaEnv: env, opts} = it + const passCxt = opts.passContext ? N.this : nil + if ($async) callAsyncRef() + else callSyncRef() + + function callAsyncRef(): void { + if (!env.$async) throw new Error("async schema referenced by sync schema") + const valid = gen.let("valid") + gen.try( + () => { + gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) + addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result + if (!allErrors) gen.assign(valid, true) + }, + (e) => { + gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) + addErrorsFrom(e) + if (!allErrors) gen.assign(valid, false) + } + ) + cxt.ok(valid) + } + + function callSyncRef(): void { + cxt.result( + callValidateCode(cxt, v, passCxt), + () => addEvaluatedFrom(v), + () => addErrorsFrom(v) + ) + } + + function addErrorsFrom(source: Code): void { + const errs = _`${source}.errors` + gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged + gen.assign(N.errors, _`${N.vErrors}.length`) + } + + function addEvaluatedFrom(source: Code): void { + if (!it.opts.unevaluated) return + const schEvaluated = sch?.validate?.evaluated + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) + } + } else { + const props = gen.var("props", _`${source}.evaluated.props`) + it.props = mergeEvaluated.props(gen, props, it.props, Name) + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) + } + } else { + const items = gen.var("items", _`${source}.evaluated.items`) + it.items = mergeEvaluated.items(gen, items, it.items, Name) + } + } + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..19ae6049f3464d2dd7518de70a9f10842aa88d66 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/index.ts @@ -0,0 +1,113 @@ +import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Name} from "../../compile/codegen" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" +import {resolveRef, SchemaEnv} from "../../compile" +import MissingRefError from "../../compile/ref_error" +import {schemaHasRulesButRef} from "../../compile/util" + +export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: ({params: {discrError, tagName}}) => + discrError === DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({params: {discrError, tag, tagName}}) => + _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const {gen, data, schema, parentSchema, it} = cxt + const {oneOf} = parentSchema + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option") + } + const tagName = schema.propertyName + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") + if (schema.mapping) throw new Error("discriminator: mapping is not supported") + if (!oneOf) throw new Error("discriminator: requires oneOf keyword") + const valid = gen.let("valid", false) + const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) + gen.if( + _`typeof ${tag} == "string"`, + () => validateMapping(), + () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) + ) + cxt.ok(valid) + + function validateMapping(): void { + const mapping = getMapping() + gen.if(false) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(mapping[tagValue])) + } + gen.else() + cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) + gen.endIf() + } + + function applyTagSchema(schemaProp?: number): Name { + const _valid = gen.name("valid") + const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) + cxt.mergeEvaluated(schCxt, Name) + return _valid + } + + function getMapping(): {[T in string]?: number} { + const oneOfMapping: {[T in string]?: number} = {} + const topRequired = hasRequired(parentSchema) + let tagRequired = true + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i] + if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { + const ref = sch.$ref + sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) + if (sch instanceof SchemaEnv) sch = sch.schema + if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) + } + const propSch = sch?.properties?.[tagName] + if (typeof propSch != "object") { + throw new Error( + `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` + ) + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)) + addMappings(propSch, i) + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) + return oneOfMapping + + function hasRequired({required}: AnySchemaObject): boolean { + return Array.isArray(required) && required.includes(tagName) + } + + function addMappings(sch: AnySchemaObject, i: number): void { + if (sch.const) { + addMapping(sch.const, i) + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i) + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) + } + } + + function addMapping(tagValue: unknown, i: number): void { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`) + } + oneOfMapping[tagValue] = i + } + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/types.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..bee5a278508e4926b85cf397fb601a7a3c2a78cb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/discriminator/types.ts @@ -0,0 +1,12 @@ +import type {ErrorObject} from "../../types" + +export enum DiscrError { + Tag = "tag", + Mapping = "mapping", +} + +export type DiscrErrorObj = ErrorObject< + "discriminator", + {error: E; tag: string; tagValue: unknown}, + string +> diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft2020.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..47fbf0ee6d75112abf222611ca514973833c8b53 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft2020.ts @@ -0,0 +1,23 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import dynamicVocabulary from "./dynamic" +import nextVocabulary from "./next" +import unevaluatedVocabulary from "./unevaluated" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft2020Vocabularies: Vocabulary[] = [ + dynamicVocabulary, + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(true), + formatVocabulary, + metadataVocabulary, + contentVocabulary, + nextVocabulary, + unevaluatedVocabulary, +] + +export default draft2020Vocabularies diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft7.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft7.ts new file mode 100644 index 0000000000000000000000000000000000000000..226a644aa428d808c22dfd6808392fada925ae5e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/draft7.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft7Vocabularies: Vocabulary[] = [ + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(), + formatVocabulary, + metadataVocabulary, + contentVocabulary, +] + +export default draft7Vocabularies diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca1adb912af0347a3bb8e18ca50cf51405f2ba1f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts @@ -0,0 +1,31 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, compileSchema} from "../../compile" +import {getValidate} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +} + +export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { + const {gen, it} = cxt + it.schemaEnv.root.dynamicAnchors[anchor] = true + const v = _`${N.dynamicAnchors}${getProperty(anchor)}` + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) + gen.if(_`!${v}`, () => gen.assign(v, validate)) +} + +function _getValidate(cxt: KeywordCxt): Code { + const {schemaEnv, schema, self} = cxt.it + const {root, baseId, localRefs, meta} = schemaEnv.root + const {schemaId} = self.opts + const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) + compileSchema.call(self, sch) + return getValidate(cxt, sch) +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a573f33024b4fc5045f17f0c251a3d6c75a22a7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts @@ -0,0 +1,51 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {callRef} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export function dynamicRef(cxt: KeywordCxt, ref: string): void { + const {gen, keyword, it} = cxt + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) + const anchor = ref.slice(1) + if (it.allErrors) { + _dynamicRef() + } else { + const valid = gen.let("valid", false) + _dynamicRef(valid) + cxt.ok(valid) + } + + function _dynamicRef(valid?: Name): void { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) + } else { + _callRef(it.validateName, valid)() + } + } + + function _callRef(validate: Code, valid?: Name): () => void { + return valid + ? () => + gen.block(() => { + callRef(cxt, validate) + gen.let(valid, true) + }) + : () => callRef(cxt, validate) + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d521db6638b890151a7a901991f91793553dab0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/index.ts @@ -0,0 +1,9 @@ +import type {Vocabulary} from "../../types" +import dynamicAnchor from "./dynamicAnchor" +import dynamicRef from "./dynamicRef" +import recursiveAnchor from "./recursiveAnchor" +import recursiveRef from "./recursiveRef" + +const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef] + +export default dynamic diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..25f3db96bf07a2c60fc3eb860ea93ee6337e0137 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicAnchor} from "./dynamicAnchor" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) dynamicAnchor(cxt, "") + else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored") + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..c84af0f05785affe11983f39f605a53502358c67 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicRef} from "./dynamicRef" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/errors.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9ca3f02f040298cd2b2faff35740eaae6ea098e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/errors.ts @@ -0,0 +1,18 @@ +import type {TypeError} from "../compile/validate/dataType" +import type {ApplicatorKeywordError} from "./applicator" +import type {ValidationKeywordError} from "./validation" +import type {FormatError} from "./format/format" +import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties" +import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems" +import type {DependentRequiredError} from "./validation/dependentRequired" +import type {DiscriminatorError} from "./discriminator" + +export type DefinedError = + | TypeError + | ApplicatorKeywordError + | ValidationKeywordError + | FormatError + | UnevaluatedPropertiesError + | UnevaluatedItemsError + | DependentRequiredError + | DiscriminatorError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/format.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/format.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1c13e764375dbb4dff021426a377f8103ab54f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/format.ts @@ -0,0 +1,120 @@ +import type { + AddedFormat, + FormatValidator, + AsyncFormatValidator, + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen" + +type FormatValidate = + | FormatValidator + | FormatValidator + | AsyncFormatValidator + | AsyncFormatValidator + | RegExp + | string + | true + +export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match format "${schemaCode}"`, + params: ({schemaCode}) => _`{format: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt, ruleType?: string) { + const {gen, data, $data, schema, schemaCode, it} = cxt + const {opts, errSchemaPath, schemaEnv, self} = it + if (!opts.validateFormats) return + + if ($data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`) + const fType = gen.let("fType") + const format = gen.let("format") + // TODO simplify + gen.if( + _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, + () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`), + () => gen.assign(fType, _`"string"`).assign(format, fDef) + ) + cxt.fail$data(or(unknownFmt(), invalidFmt())) + + function unknownFmt(): Code { + if (opts.strictSchema === false) return nil + return _`${schemaCode} && !${format}` + } + + function invalidFmt(): Code { + const callFormat = schemaEnv.$async + ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : _`${format}(${data})` + const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))` + return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}` + } + } + + function validateFormat(): void { + const formatDef: AddedFormat | undefined = self.formats[schema] + if (!formatDef) { + unknownFormat() + return + } + if (formatDef === true) return + const [fmtType, format, fmtRef] = getFormat(formatDef) + if (fmtType === ruleType) cxt.pass(validCondition()) + + function unknownFormat(): void { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()) + return + } + throw new Error(unknownMsg()) + + function unknownMsg(): string { + return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"` + } + } + + function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] { + const code = + fmtDef instanceof RegExp + ? regexpCode(fmtDef) + : opts.code.formats + ? _`${opts.code.formats}${getProperty(schema)}` + : undefined + const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code}) + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`] + } + + return ["string", fmtDef, fmt] + } + + function validCondition(): Code { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema") + return _`await ${fmtRef}(${data})` + } + return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})` + } + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bca2f5b3d817051e07bd768888ed7142e63c4c97 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/format/index.ts @@ -0,0 +1,6 @@ +import type {Vocabulary} from "../../types" +import formatKeyword from "./format" + +const format: Vocabulary = [formatKeyword] + +export default format diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts new file mode 100644 index 0000000000000000000000000000000000000000..f487c97f84332592ca90b09d5c046a87afd57f9b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts @@ -0,0 +1,89 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not, getProperty, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" + +export type JTDDiscriminatorError = + | _JTDTypeError<"discriminator", "object", string> + | DiscrErrorObj + | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? params.discrError === DiscrError.Tag + ? `tag "${schema}" must be string` + : `value of tag "${schema}" must be in mapping` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, parentSchema} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + + gen.if(cond) + validateDiscriminator() + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + cxt.ok(valid) + + function validateDiscriminator(): void { + const tag = gen.const("tag", _`${data}${getProperty(schema)}`) + gen.if(_`${tag} === undefined`) + cxt.error(false, {discrError: DiscrError.Tag, tag}) + gen.elseIf(_`typeof ${tag} == "string"`) + validateMapping(tag) + gen.else() + cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema}) + gen.endIf() + } + + function validateMapping(tag: Name): void { + gen.if(false) + for (const tagValue in parentSchema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(tagValue)) + } + gen.else() + cxt.error( + false, + {discrError: DiscrError.Mapping, tag}, + {instancePath: schema, schemaPath: "mapping", parentSchema: true} + ) + gen.endIf() + } + + function applyTagSchema(schemaProp: string): Name { + const _valid = gen.name("valid") + cxt.subschema( + { + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema, + }, + _valid + ) + return _valid + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/elements.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/elements.ts new file mode 100644 index 0000000000000000000000000000000000000000..983af7c0276ed83cf92e5071a2a8a63ef2d522e4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/elements.ts @@ -0,0 +1,32 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {_, not} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "elements", + schemaType: "object", + error: typeError("array"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const [valid] = checkNullable(cxt) + gen.if(not(valid), () => + gen.if( + _`Array.isArray(${data})`, + () => gen.assign(valid, validateArray(cxt)), + () => cxt.error() + ) + ) + cxt.ok(valid) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/enum.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..75464ff8e13f581679d2b33662f34ac79a23e912 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/enum.ts @@ -0,0 +1,45 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, and, Code} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" + +export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, schemaValue, parentSchema, it} = cxt + if (schema.length === 0) throw new Error("enum must have non-empty array") + if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique") + let valid: Code + const isString = _`typeof ${data} == "string"` + if (schema.length >= it.opts.loopEnum) { + let cond: Code + ;[valid, cond] = checkNullable(cxt, isString) + gen.if(cond, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`))) + if (parentSchema.nullable) valid = or(_`${data} === null`, valid) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.forOf("v", schemaValue as Code, (v) => + gen.if(_`${valid} = ${data} === ${v}`, () => gen.break()) + ) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/error.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..5069322588ebc486795ec075e49777888bbd8cdf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/error.ts @@ -0,0 +1,23 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types" +import {_, Code} from "../../compile/codegen" + +export type _JTDTypeError = ErrorObject< + K, + {type: T; nullable: boolean}, + S +> + +export function typeError(t: string): KeywordErrorDefinition { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t), + } +} + +export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string { + return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}` +} + +export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code { + return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}` +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7baebc30788d80498e59328809b6b6a312d3315 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/index.ts @@ -0,0 +1,37 @@ +import type {Vocabulary} from "../../types" +import refKeyword from "./ref" +import typeKeyword, {JTDTypeError} from "./type" +import enumKeyword, {JTDEnumError} from "./enum" +import elements, {JTDElementsError} from "./elements" +import properties, {JTDPropertiesError} from "./properties" +import optionalProperties from "./optionalProperties" +import discriminator, {JTDDiscriminatorError} from "./discriminator" +import values, {JTDValuesError} from "./values" +import union from "./union" +import metadata from "./metadata" + +const jtdVocabulary: Vocabulary = [ + "definitions", + refKeyword, + typeKeyword, + enumKeyword, + elements, + properties, + optionalProperties, + discriminator, + values, + union, + metadata, + {keyword: "additionalProperties", schemaType: "boolean"}, + {keyword: "nullable", schemaType: "boolean"}, +] + +export default jtdVocabulary + +export type JTDErrorObject = + | JTDTypeError + | JTDEnumError + | JTDElementsError + | JTDPropertiesError + | JTDDiscriminatorError + | JTDValuesError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/metadata.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..19eeb8c7d5b8f6ed1ab794cc0368f67d4be8bb8a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/metadata.ts @@ -0,0 +1,24 @@ +import {KeywordCxt} from "../../ajv" +import type {CodeKeywordDefinition} from "../../types" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "metadata", + schemaType: "object", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid) + cxt.ok(valid) + }, +} + +export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`) + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/nullable.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/nullable.ts new file mode 100644 index 0000000000000000000000000000000000000000..c74b05da72dbd4694ac215d5e5616e9050db283c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/nullable.ts @@ -0,0 +1,21 @@ +import type {KeywordCxt} from "../../compile/validate" +import {_, not, nil, Code, Name} from "../../compile/codegen" + +export function checkNullable( + {gen, data, parentSchema}: KeywordCxt, + cond: Code = nil +): [Name, Code] { + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.let(valid, _`${data} === null`) + cond = not(valid) + } else { + gen.let(valid, false) + } + return [valid, cond] +} + +export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] { + const [valid, cond_] = checkNullable(cxt, cond) + return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e91c8d91874407585b29641f22457822079fd66 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts @@ -0,0 +1,15 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {validateProperties, error} from "./properties" + +const def: CodeKeywordDefinition = { + keyword: "optionalProperties", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + if (cxt.parentSchema.properties) return + validateProperties(cxt) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/properties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dd24c5cd62d46a913d644636fc9eacbb7f8a4fe --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/properties.ts @@ -0,0 +1,184 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties, isOwnProperty} from "../code" +import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util" +import {_, and, not, Code, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +enum PropError { + Additional = "additional", + Missing = "missing", +} + +type PropKeyword = "properties" | "optionalProperties" + +type PropSchema = {[P in string]?: SchemaObject} + +export type JTDPropertiesError = + | _JTDTypeError + | ErrorObject + | ErrorObject + +export const error: KeywordErrorDefinition = { + message: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? "must NOT have additional properties" + : `must have property '${params.missingProperty}'` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` + : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "properties", + schemaType: "object", + error, + code: validateProperties, +} + +// const error: KeywordErrorDefinition = { +// message: "should NOT have additional properties", +// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +// } + +export function validateProperties(cxt: KeywordCxt): void { + checkMetadata(cxt) + const {gen, data, parentSchema, it} = cxt + const {additionalProperties, nullable} = parentSchema + if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping") + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members") + } + const [allProps, properties] = schemaProperties("properties") + const [allOptProps, optProperties] = schemaProperties("optionalProperties") + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return + } + + const [valid, cond] = + it.jtdDiscriminator === undefined + ? checkNullableObject(cxt, data) + : [gen.let("valid", false), true] + gen.if(cond, () => + gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true) + validateProps(optProperties, "optionalProperties") + if (!additionalProperties) validateAdditional() + }) + ) + cxt.pass(valid) + + function commonProperties(): boolean { + const props = parentSchema.properties as Record | undefined + const optProps = parentSchema.optionalProperties as Record | undefined + if (!(props && optProps)) return false + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) return true + } + return false + } + + function schemaProperties(keyword: string): [string[], string[]] { + const schema = parentSchema[keyword] + const allPs = schema ? allSchemaProperties(schema) : [] + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`) + } + const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p])) + return [allPs, ps] + } + + function validateProps(props: string[], keyword: string, required?: boolean): void { + const _valid = gen.var("valid") + for (const prop of props) { + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => applyPropertySchema(prop, keyword, _valid), + () => missingProperty(prop) + ) + cxt.ok(_valid) + } + + function missingProperty(prop: string): void { + if (required) { + gen.assign(_valid, false) + cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop}) + } else { + gen.assign(_valid, true) + } + } + } + + function applyPropertySchema(prop: string, keyword: string, _valid: Name): void { + cxt.subschema( + { + keyword, + schemaProp: prop, + dataProp: prop, + }, + _valid + ) + } + + function validateAdditional(): void { + gen.forIn("key", data, (key: Name) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator) + const addOptProp = isAdditional(key, allOptProps, "optionalProperties") + const extra = + addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp) + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code(_`delete ${data}[${key}]`) + } else { + cxt.error( + false, + {propError: PropError.Additional, additionalProperty: key}, + {instancePath: key, parentSchema: true} + ) + if (!it.opts.allErrors) gen.break() + } + }) + }) + } + + function isAdditional( + key: Name, + props: string[], + keyword: string, + jtdDiscriminator?: string + ): Code | true { + let additional: Code | boolean + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword) + additional = not(isOwnProperty(gen, propsSchema as Code, key)) + if (jtdDiscriminator !== undefined) { + additional = and(additional, _`${key} !== ${jtdDiscriminator}`) + } + } else if (props.length || jtdDiscriminator !== undefined) { + const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props) + additional = and(...ps.map((p) => _`${key} !== ${p}`)) + } else { + additional = true + } + return additional + } +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/ref.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..97646ee1b68885bf004ce2e629421abac07a991d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/ref.ts @@ -0,0 +1,76 @@ +import type {CodeKeywordDefinition, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {compileSchema, SchemaEnv} from "../../compile" +import {_, not, nil, stringify} from "../../compile/codegen" +import MissingRefError from "../../compile/ref_error" +import N from "../../compile/names" +import {getValidate, callRef} from "../core/ref" +import {checkMetadata} from "./metadata" + +const def: CodeKeywordDefinition = { + keyword: "ref", + schemaType: "string", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema: ref, parentSchema, it} = cxt + const { + schemaEnv: {root}, + } = it + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.var(valid, _`${data} === null`) + gen.if(not(valid), validateJtdRef) + } else { + gen.var(valid, false) + validateJtdRef() + } + cxt.ok(valid) + + function validateJtdRef(): void { + const refSchema = (root.schema as AnySchemaObject).definitions?.[ref] + if (!refSchema) { + throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`) + } + if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema) + else inlineRefSchema(refSchema) + } + + function callValidate(schema: AnySchemaObject): void { + const sch = compileSchema.call( + it.self, + new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`}) + ) + const v = getValidate(cxt, sch) + const errsCount = gen.const("_errs", N.errors) + callRef(cxt, v, sch, sch.$async) + gen.assign(valid, _`${errsCount} === ${N.errors}`) + } + + function inlineRefSchema(schema: AnySchemaObject): void { + const schName = gen.scopeValue( + "schema", + it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema} + ) + cxt.subschema( + { + schema, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}`, + }, + valid + ) + } + }, +} + +export function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + let sch: AnySchemaObject + if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true + } + return false +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/type.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/type.ts new file mode 100644 index 0000000000000000000000000000000000000000..17274300b70b11b72977a965a4410f21a8f0f19c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/type.ts @@ -0,0 +1,75 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, nil, or, Code} from "../../compile/codegen" +import validTimestamp from "../../runtime/timestamp" +import {useFunc} from "../../compile/util" +import {checkMetadata} from "./metadata" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType> + +export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +export const intRange: {[T in IntType]: [number, number, number]} = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10], +} + +export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType + +const error: KeywordErrorDefinition = { + message: (cxt) => typeErrorMessage(cxt, cxt.schema), + params: (cxt) => typeErrorParams(cxt, cxt.schema), +} + +function timestampCode(cxt: KeywordCxt): Code { + const {gen, data, it} = cxt + const {timestamp, allowDate} = it.opts + if (timestamp === "date") return _`${data} instanceof Date ` + const vts = useFunc(gen, validTimestamp) + const allowDateArg = allowDate ? _`, true` : nil + const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})` + return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString) +} + +const def: CodeKeywordDefinition = { + keyword: "type", + schemaType: "string", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {data, schema, parentSchema, it} = cxt + let cond: Code + switch (schema) { + case "boolean": + case "string": + cond = _`typeof ${data} == ${schema}` + break + case "timestamp": { + cond = timestampCode(cxt) + break + } + case "float32": + case "float64": + cond = _`typeof ${data} == "number"` + break + default: { + const sch = schema as IntType + cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)` + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") cond = _`${cond} && ${data} >= 0` + } else { + const [min, max] = intRange[sch] + cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}` + } + } + } + cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/union.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/union.ts new file mode 100644 index 0000000000000000000000000000000000000000..588f07ab4a96bb88512579ce0cc683eaa5925eb2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/union.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateUnion} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in union"}, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/values.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/values.ts new file mode 100644 index 0000000000000000000000000000000000000000..e64945077647a81d99a6460ae6e86b5394c250c4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/jtd/values.ts @@ -0,0 +1,58 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema, Type} from "../../compile/util" +import {not, or, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "values", + schemaType: "object", + error: typeError("object"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + if (alwaysValidSchema(it, schema)) { + gen.if(not(or(cond, valid)), () => cxt.error()) + } else { + gen.if(cond) + gen.assign(valid, validateMap()) + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + } + cxt.ok(valid) + + function validateMap(): Name | boolean { + const _valid = gen.name("valid") + if (it.allErrors) { + const validMap = gen.let("valid", true) + validateValues(() => gen.assign(validMap, false)) + return validMap + } + gen.var(_valid, true) + validateValues(() => gen.break()) + return _valid + + function validateValues(notValid: () => void): void { + gen.forIn("key", data, (key) => { + cxt.subschema( + { + keyword: "values", + dataProp: key, + dataPropType: Type.Str, + }, + _valid + ) + gen.if(not(_valid), notValid) + }) + } + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/metadata.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9d5af85fe921f9cd553e61da6a09234213f0e5b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/metadata.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" + +export const metadataVocabulary: Vocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +] + +export const contentVocabulary: Vocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +] diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/next.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/next.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e987ad21241259ff0453a45534d0822fa3b7e58 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/next.ts @@ -0,0 +1,8 @@ +import type {Vocabulary} from "../types" +import dependentRequired from "./validation/dependentRequired" +import dependentSchemas from "./applicator/dependentSchemas" +import limitContains from "./validation/limitContains" + +const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains] + +export default next diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7f0815dbb00cfccd96f8910bea06182f9e19993 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/index.ts @@ -0,0 +1,7 @@ +import type {Vocabulary} from "../../types" +import unevaluatedProperties from "./unevaluatedProperties" +import unevaluatedItems from "./unevaluatedItems" + +const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems] + +export default unevaluated diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..50bf0e7c17873ad2f435a92105745d4aa8ed9d26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts @@ -0,0 +1,47 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" + +export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + const items = it.items || 0 + if (items === true) return + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items}) + cxt.fail(_`${len} > ${items}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items}`) + gen.if(not(valid), () => validateItems(valid, items)) + cxt.ok(valid) + } + it.items = true + + function validateItems(valid: Name, from: Name | number): void { + gen.forRange("i", from, len, (i) => { + cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e6868fa326dab80317a39e135a4b4deb1d0f2f4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts @@ -0,0 +1,85 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import {_, not, and, Name, Code} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" +import N from "../../compile/names" + +export type UnevaluatedPropertiesError = ErrorObject< + "unevaluatedProperties", + {unevaluatedProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have unevaluated properties", + params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error, + code(cxt) { + const {gen, schema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, props} = it + if (props instanceof Name) { + gen.if(_`${props} !== true`, () => + gen.forIn("key", data, (key: Name) => + gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)) + ) + ) + } else if (props !== true) { + gen.forIn("key", data, (key: Name) => + props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)) + ) + } + it.props = true + cxt.ok(_`${errsCount} === ${N.errors}`) + + function unevaluatedPropCode(key: Name): void { + if (schema === false) { + cxt.setParams({unevaluatedProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (!alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + + function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code { + return _`!${evaluatedProps} || !${evaluatedProps}[${key}]` + } + + function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code { + const ps: Code[] = [] + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`) + } + return and(...ps) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/const.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/const.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3b94a5dcd3d0ad993a83088694b9375089f735d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/const.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type ConstError = ErrorObject<"const", {allowedValue: any}> + +const error: KeywordErrorDefinition = { + message: "must be equal to constant", + params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "const", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schemaCode, schema} = cxt + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) + } else { + cxt.fail(_`${schema} !== ${data}`) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c616cfa9ac79fabdd5e4d2ff19840adec61f813 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts @@ -0,0 +1,23 @@ +import type {CodeKeywordDefinition, ErrorObject} from "../../types" +import { + validatePropertyDeps, + error, + DependenciesErrorParams, + PropertyDependencies, +} from "../applicator/dependencies" + +export type DependentRequiredError = ErrorObject< + "dependentRequired", + DependenciesErrorParams, + PropertyDependencies +> + +const def: CodeKeywordDefinition = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error, + code: (cxt) => validatePropertyDeps(cxt), +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/enum.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..76377fb02e6a9e8843ba08b2e858a19a067b787b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/enum.ts @@ -0,0 +1,54 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, Name, Code} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, schemaCode, it} = cxt + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") + const useLoop = schema.length >= it.opts.loopEnum + let eql: Name | undefined + const getEql = (): Name => (eql ??= useFunc(gen, equal)) + + let valid: Code + if (useLoop || $data) { + valid = gen.let("valid") + cxt.block$data(valid, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const vSchema = gen.const("vSchema", schemaCode) + valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.assign(valid, false) + gen.forOf("v", schemaCode as Code, (v) => + gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) + ) + } + + function equalCode(vSchema: Name, i: number): Code { + const sch = schema[i] + return typeof sch === "object" && sch !== null + ? _`${getEql()}(${data}, ${vSchema}[${i}])` + : _`${data} === ${sch}` + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3531b19628b7dfb2526a81cd38d6c93ee1a54dbe --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/index.ts @@ -0,0 +1,49 @@ +import type {ErrorObject, Vocabulary} from "../../types" +import limitNumber, {LimitNumberError} from "./limitNumber" +import multipleOf, {MultipleOfError} from "./multipleOf" +import limitLength from "./limitLength" +import pattern, {PatternError} from "./pattern" +import limitProperties from "./limitProperties" +import required, {RequiredError} from "./required" +import limitItems from "./limitItems" +import uniqueItems, {UniqueItemsError} from "./uniqueItems" +import constKeyword, {ConstError} from "./const" +import enumKeyword, {EnumError} from "./enum" + +const validation: Vocabulary = [ + // number + limitNumber, + multipleOf, + // string + limitLength, + pattern, + // object + limitProperties, + required, + // array + limitItems, + uniqueItems, + // any + {keyword: "type", schemaType: ["string", "array"]}, + {keyword: "nullable", schemaType: "boolean"}, + constKeyword, + enumKeyword, +] + +export default validation + +type LimitError = ErrorObject< + "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", + {limit: number}, + number | {$data: string} +> + +export type ValidationKeywordError = + | LimitError + | LimitNumberError + | MultipleOfError + | PatternError + | RequiredError + | UniqueItemsError + | ConstError + | EnumError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitContains.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitContains.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bb43c1a4a66f1d8781181cbd07f06edb76aea02 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitContains.ts @@ -0,0 +1,16 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.contains === undefined) { + checkStrictMode(it, `"${keyword}" without "contains" is ignored`) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitItems.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..566de8588b3be2fcccdeff56f26338be0dc6fcb4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitItems.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxItems" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} items` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxItems" ? operators.GT : operators.LT + cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitLength.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitLength.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4f947259549ad3d0e9fe992e5a92a83696e1177 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitLength.ts @@ -0,0 +1,30 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import ucs2length from "../../runtime/ucs2length" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxLength" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} characters` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode, it} = cxt + const op = keyword === "maxLength" ? operators.GT : operators.LT + const len = + it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` + cxt.fail$data(_`${len} ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts new file mode 100644 index 0000000000000000000000000000000000000000..5499202efbfec965a9acd8c71e145e79110923d9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts @@ -0,0 +1,42 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators, Code} from "../../compile/codegen" + +const ops = operators + +type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitNumberError = ErrorObject< + Kwd, + {limit: number; comparison: Comparison}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..07fffa8b39a03798262a94da5c55ac6e3e7ce200 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxProperties" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} properties` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxProperties" ? operators.GT : operators.LT + cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fd79abbd91c41d872ec775441f48b69550e8655 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts @@ -0,0 +1,34 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" + +export type MultipleOfError = ErrorObject< + "multipleOf", + {multipleOf: number}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must be multiple of ${schemaCode}`, + params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, schemaCode, it} = cxt + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision + const res = gen.let("res") + const invalid = prec + ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : _`${res} !== parseInt(${res})` + cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/pattern.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/pattern.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b27b7d3c0dfafad85d8612a19ab1e46e899ec2c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/pattern.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {usePattern} from "../code" +import {_, str} from "../../compile/codegen" + +export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, + params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt) { + const {data, $data, schema, schemaCode, it} = cxt + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : "" + const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema) + cxt.fail$data(_`!${regExp}.test(${data})`) + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/required.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/required.ts new file mode 100644 index 0000000000000000000000000000000000000000..fea7367ed7b8f0cfeee2a73a1cecaca7f8c0c115 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/required.ts @@ -0,0 +1,98 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import { + checkReportMissingProp, + checkMissingProp, + reportMissingProp, + propertyInData, + noPropertyInData, +} from "../code" +import {_, str, nil, not, Name, Code} from "../../compile/codegen" +import {checkStrictMode} from "../../compile/util" + +export type RequiredError = ErrorObject< + "required", + {missingProperty: string}, + string[] | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`, + params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, schemaCode, data, $data, it} = cxt + const {opts} = it + if (!$data && schema.length === 0) return + const useLoop = schema.length >= opts.loopRequired + if (it.allErrors) allErrorsMode() + else exitOnErrorMode() + + if (opts.strictRequired) { + const props = cxt.parentSchema.properties + const {definedProperties} = cxt.it + for (const requiredKey of schema) { + if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` + checkStrictMode(it, msg, it.opts.strictRequired) + } + } + } + + function allErrorsMode(): void { + if (useLoop || $data) { + cxt.block$data(nil, loopAllRequired) + } else { + for (const prop of schema) { + checkReportMissingProp(cxt, prop) + } + } + } + + function exitOnErrorMode(): void { + const missing = gen.let("missing") + if (useLoop || $data) { + const valid = gen.let("valid", true) + cxt.block$data(valid, () => loopUntilMissing(missing, valid)) + cxt.ok(valid) + } else { + gen.if(checkMissingProp(cxt, schema, missing)) + reportMissingProp(cxt, missing) + gen.else() + } + } + + function loopAllRequired(): void { + gen.forOf("prop", schemaCode as Code, (prop) => { + cxt.setParams({missingProperty: prop}) + gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) + }) + } + + function loopUntilMissing(missing: Name, valid: Name): void { + cxt.setParams({missingProperty: missing}) + gen.forOf( + missing, + schemaCode as Code, + () => { + gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) + gen.if(not(valid), () => { + cxt.error() + gen.break() + }) + }, + nil + ) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..765c4d04fc2472b774838d06fe13c15a98b58a9b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts @@ -0,0 +1,79 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType" +import {_, str, Name} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type UniqueItemsError = ErrorObject< + "uniqueItems", + {i: number; j: number}, + boolean | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {i, j}}) => + str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt + if (!$data && !schema) return + const valid = gen.let("valid") + const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] + cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) + cxt.ok(valid) + + function validateUniqueItems(): void { + const i = gen.let("i", _`${data}.length`) + const j = gen.let("j") + cxt.setParams({i, j}) + gen.assign(valid, true) + gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) + } + + function canOptimize(): boolean { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") + } + + function loopN(i: Name, j: Name): void { + const item = gen.name("item") + const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) + const indices = gen.const("indices", _`{}`) + gen.for(_`;${i}--;`, () => { + gen.let(item, _`${data}[${i}]`) + gen.if(wrongType, _`continue`) + if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) + gen + .if(_`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, _`${indices}[${item}]`) + cxt.error() + gen.assign(valid, false).break() + }) + .code(_`${indices}[${item}] = ${i}`) + }) + } + + function loopN2(i: Name, j: Name): void { + const eql = useFunc(gen, equal) + const outer = gen.name("outer") + gen.label(outer).for(_`;${i}--;`, () => + gen.for(_`${j} = ${i}; ${j}--;`, () => + gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error() + gen.assign(valid, false).break(outer) + }) + ) + ) + } + }, +} + +export default def diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/release-drafter.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..eba1c60853052e361195b57c1efa7f48d6b963f5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/release-drafter.yml @@ -0,0 +1,4 @@ +template: | + ## What’s Changed + + $CHANGES diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/tests_checker.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/tests_checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..3092680ef3f3825e5056418aaa471fb2753a8c99 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/tests_checker.yml @@ -0,0 +1,3 @@ +comment: 'Could you please add tests to make sure this change works as expected?', +fileExtensions: ['.php', '.ts', '.js', '.c', '.cs', '.cpp', '.rb', '.java'] +testDir: 'test' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..7eb421708eeea7475cb9f737e96ff47df76d9057 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5.0.0 + with: + lint: true + license-check: true + node-versions: '["20", "22"]' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/examples/example.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/examples/example.js new file mode 100644 index 0000000000000000000000000000000000000000..cbba32b5935c2a05ae0898de7ffc3130314f8337 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/examples/example.js @@ -0,0 +1,72 @@ +'use strict' + +const avvio = require('..')() + +function a (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 10) +} +const pointer = a + +function b (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 20) +} + +function c (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 30) +} + +avvio + .use(first, { hello: 'world' }) + .use(duplicate, { count: 0 }) + .use(function a (instance, opts, cb) { + instance.use(pointer, { use: [b], subUse: [c] }) + .use(b) + setTimeout(cb, 42) + }) + .after(function (err, cb) { + if (err) { + console.log('something bad happened') + console.log(err) + } + console.log('after first and second') + cb() + }) + .use(duplicate, { count: 4 }) + .use(third) + .ready(function (err) { + if (err) { + throw err + } + console.log('application booted!') + }) + +avvio.on('preReady', () => { + console.log(avvio.prettyPrint()) +}) + +function first (instance, opts, cb) { + console.log('first loaded', opts) + instance.use(second) + setTimeout(cb, 42) +} + +function second (instance, opts, cb) { + console.log('second loaded') + process.nextTick(cb) +} + +function third (instance, opts, cb) { + console.log('third loaded') + cb() +} + +function duplicate (instance, opts, cb) { + console.log('duplicate loaded', opts.count) + if (opts.count > 0) { + instance.use(duplicate, { count: opts.count - 1 }) + } + setTimeout(cb, 20) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/create-promise.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/create-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..4b10c0b0657a12c70d8f3e61fa266b7cae2e9ac3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/create-promise.js @@ -0,0 +1,45 @@ +'use strict' + +/** + * @callback PromiseResolve + * @param {any|PromiseLike} value + * @returns {void} + */ + +/** + * @callback PromiseReject + * @param {any} reason + * @returns {void} + */ + +/** + * @typedef PromiseObject + * @property {Promise} promise + * @property {PromiseResolve} resolve + * @property {PromiseReject} reject + */ + +/** + * @returns {PromiseObject} + */ +function createPromise () { + /** + * @type {PromiseObject} + */ + const obj = { + resolve: null, + reject: null, + promise: null + } + + obj.promise = new Promise((resolve, reject) => { + obj.resolve = resolve + obj.reject = reject + }) + + return obj +} + +module.exports = { + createPromise +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/debug.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..e7cdc6fc4ad6ca7df49ceef4ac6dc738ef9705f9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/debug.js @@ -0,0 +1,19 @@ +'use strict' + +const { debuglog } = require('node:util') + +/** + * @callback DebugLogger + * @param {string} msg + * @param {...unknown} param + * @returns {void} + */ + +/** + * @type {DebugLogger} + */ +const debug = debuglog('avvio') + +module.exports = { + debug +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/errors.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..9aa4c8a1070f0c0219a942c0fe0b91a6391ec54b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/errors.js @@ -0,0 +1,38 @@ +'use strict' + +const { createError } = require('@fastify/error') + +module.exports = { + AVV_ERR_EXPOSE_ALREADY_DEFINED: createError( + 'AVV_ERR_EXPOSE_ALREADY_DEFINED', + "'%s' is already defined, specify an expose option for '%s'" + ), + AVV_ERR_ATTRIBUTE_ALREADY_DEFINED: createError( + 'AVV_ERR_ATTRIBUTE_ALREADY_DEFINED', + "'%s' is already defined" + ), + AVV_ERR_CALLBACK_NOT_FN: createError( + 'AVV_ERR_CALLBACK_NOT_FN', + "Callback for '%s' hook is not a function. Received: '%s'" + ), + AVV_ERR_PLUGIN_NOT_VALID: createError( + 'AVV_ERR_PLUGIN_NOT_VALID', + "Plugin must be a function or a promise. Received: '%s'" + ), + AVV_ERR_ROOT_PLG_BOOTED: createError( + 'AVV_ERR_ROOT_PLG_BOOTED', + 'Root plugin has already booted' + ), + AVV_ERR_PARENT_PLG_LOADED: createError( + 'AVV_ERR_PARENT_PLG_LOADED', + "Impossible to load '%s' plugin because the parent '%s' was already loaded" + ), + AVV_ERR_READY_TIMEOUT: createError( + 'AVV_ERR_READY_TIMEOUT', + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ), + AVV_ERR_PLUGIN_EXEC_TIMEOUT: createError( + 'AVV_ERR_PLUGIN_EXEC_TIMEOUT', + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js new file mode 100644 index 0000000000000000000000000000000000000000..6e2c80956070c57f7b2d2626737e9b3939140f21 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js @@ -0,0 +1,28 @@ +'use strict' +const { isPromiseLike } = require('./is-promise-like') +const { kAvvio } = require('./symbols') + +/** + * @callback ExecuteWithThenableCallback + * @param {Error} error + * @returns {void} + */ + +/** + * @param {Function} func + * @param {Array} args + * @param {ExecuteWithThenableCallback} [callback] + */ +function executeWithThenable (func, args, callback) { + const result = func.apply(func, args) + if (isPromiseLike(result) && !result[kAvvio]) { + // process promise but not avvio mock thenable + result.then(() => process.nextTick(callback), (error) => process.nextTick(callback, error)) + } else if (callback) { + process.nextTick(callback) + } +} + +module.exports = { + executeWithThenable +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/get-plugin-name.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/get-plugin-name.js new file mode 100644 index 0000000000000000000000000000000000000000..79bf79a1f6e7b243bb7e75a84ba25523a5a0d539 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/get-plugin-name.js @@ -0,0 +1,34 @@ +'use strict' + +// this symbol is assigned by fastify-plugin +const { kPluginMeta } = require('./symbols') + +/** + * @param {function} plugin + * @param {object} [options] + * @param {string} [options.name] + * @returns {string} + */ +function getPluginName (plugin, options) { + // use explicit function metadata if set + if (plugin[kPluginMeta] && plugin[kPluginMeta].name) { + return plugin[kPluginMeta].name + } + + // use explicit name option if set + if (options && options.name) { + return options.name + } + + // determine from the function + if (plugin.name) { + return plugin.name + } else { + // takes the first two lines of the function if nothing else works + return plugin.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ') + } +} + +module.exports = { + getPluginName +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..42003dd9311e2894cdb578eccf7d4a56fc6aee83 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js @@ -0,0 +1,23 @@ +'use strict' + +/** + * bundled or typescript plugin + * @typedef {object} BundledOrTypescriptPlugin + * @property {function} default + */ + +/** + * @param {any} maybeBundledOrTypescriptPlugin + * @returns {plugin is BundledOrTypescriptPlugin} + */ +function isBundledOrTypescriptPlugin (maybeBundledOrTypescriptPlugin) { + return ( + maybeBundledOrTypescriptPlugin !== null && + typeof maybeBundledOrTypescriptPlugin === 'object' && + typeof maybeBundledOrTypescriptPlugin.default === 'function' + ) +} + +module.exports = { + isBundledOrTypescriptPlugin +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-promise-like.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-promise-like.js new file mode 100644 index 0000000000000000000000000000000000000000..909f8dbd1bec6a222c223cd8ffe6456f41832d76 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/is-promise-like.js @@ -0,0 +1,17 @@ +'use strict' + +/** + * @param {any} maybePromiseLike + * @returns {maybePromiseLike is PromiseLike} + */ +function isPromiseLike (maybePromiseLike) { + return ( + maybePromiseLike !== null && + typeof maybePromiseLike === 'object' && + typeof maybePromiseLike.then === 'function' + ) +} + +module.exports = { + isPromiseLike +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/plugin.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a3f248d5887e88d6d9d91cdf530fa421f6b1bf1d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/plugin.js @@ -0,0 +1,279 @@ +'use strict' + +const { EventEmitter } = require('node:events') +const { inherits } = require('node:util') +const { debug } = require('./debug') +const { createPromise } = require('./create-promise') +const { AVV_ERR_PLUGIN_EXEC_TIMEOUT } = require('./errors') +const { getPluginName } = require('./get-plugin-name') +const { isPromiseLike } = require('./is-promise-like') + +/** + * @param {*} queue + * @param {*} func + * @param {*} options + * @param {boolean} isAfter + * @param {number} [timeout] + */ +function Plugin (queue, func, options, isAfter, timeout) { + this.queue = queue + this.func = func + this.options = options + + /** + * @type {boolean} + */ + this.isAfter = isAfter + /** + * @type {number} + */ + this.timeout = timeout + + /** + * @type {boolean} + */ + this.started = false + /** + * @type {string} + */ + this.name = getPluginName(func, options) + + this.queue.pause() + + /** + * @type {Error|null} + */ + this._error = null + /** + * @type {boolean} + */ + this.loaded = false + + this._promise = null + + this.startTime = null +} + +inherits(Plugin, EventEmitter) + +/** + * @callback ExecCallback + * @param {Error|null} execErr + * @returns + */ + +/** + * + * @param {*} server + * @param {ExecCallback} callback + * @returns + */ +Plugin.prototype.exec = function (server, callback) { + debug('exec', this.name) + + this.server = server + const func = this.func + const name = this.name + let completed = false + + this.options = typeof this.options === 'function' ? this.options(this.server) : this.options + + let timer = null + + /** + * @param {Error} [execErr] + */ + const done = (execErr) => { + if (completed) { + debug('loading complete', name) + return + } + + this._error = execErr + + if (execErr) { + debug('exec errored', name) + } else { + debug('exec completed', name) + } + + completed = true + + if (timer) { + clearTimeout(timer) + } + + callback(execErr) + } + + if (this.timeout > 0) { + debug('setting up timeout', name, this.timeout) + timer = setTimeout(function () { + debug('timed out', name) + timer = null + const readyTimeoutErr = new AVV_ERR_PLUGIN_EXEC_TIMEOUT(name) + // TODO Remove reference to function + readyTimeoutErr.fn = func + done(readyTimeoutErr) + }, this.timeout) + } + + this.started = true + this.startTime = Date.now() + this.emit('start', this.server ? this.server.name : null, this.name, Date.now()) + + const maybePromiseLike = func(this.server, this.options, done) + + if (isPromiseLike(maybePromiseLike)) { + debug('exec: resolving promise', name) + + maybePromiseLike.then( + () => process.nextTick(done), + (e) => process.nextTick(done, e)) + } else if (func.length < 3) { + done() + } +} + +/** + * @returns {Promise} + */ +Plugin.prototype.loadedSoFar = function () { + debug('loadedSoFar', this.name) + + if (this.loaded) { + return Promise.resolve() + } + + const setup = () => { + this.server.after((afterErr, callback) => { + this._error = afterErr + this.queue.pause() + + if (this._promise) { + if (afterErr) { + debug('rejecting promise', this.name, afterErr) + this._promise.reject(afterErr) + } else { + debug('resolving promise', this.name) + this._promise.resolve() + } + this._promise = null + } + + process.nextTick(callback, afterErr) + }) + this.queue.resume() + } + + let res + + if (!this._promise) { + this._promise = createPromise() + res = this._promise.promise + + if (!this.server) { + this.on('start', setup) + } else { + setup() + } + } else { + res = Promise.resolve() + } + + return res +} + +/** + * @callback EnqueueCallback + * @param {Error|null} enqueueErr + * @param {Plugin} result + */ + +/** + * + * @param {Plugin} plugin + * @param {EnqueueCallback} callback + */ +Plugin.prototype.enqueue = function (plugin, callback) { + debug('enqueue', this.name, plugin.name) + + this.emit('enqueue', this.server ? this.server.name : null, this.name, Date.now()) + this.queue.push(plugin, callback) +} + +/** + * @callback FinishCallback + * @param {Error|null} finishErr + * @returns + */ +/** + * + * @param {Error|null} err + * @param {FinishCallback} callback + * @returns + */ +Plugin.prototype.finish = function (err, callback) { + debug('finish', this.name, err) + + const done = () => { + if (this.loaded) { + return + } + + debug('loaded', this.name) + this.emit('loaded', this.server ? this.server.name : null, this.name, Date.now()) + this.loaded = true + + callback(err) + } + + if (err) { + if (this._promise) { + this._promise.reject(err) + this._promise = null + } + done() + return + } + + const check = () => { + debug('check', this.name, this.queue.length(), this.queue.running(), this._promise) + if (this.queue.length() === 0 && this.queue.running() === 0) { + if (this._promise) { + const wrap = () => { + debug('wrap') + queueMicrotask(check) + } + this._promise.resolve() + this._promise.promise.then(wrap, wrap) + this._promise = null + } else { + done() + } + } else { + debug('delayed', this.name) + // finish when the queue of nested plugins to load is empty + this.queue.drain = () => { + debug('drain', this.name) + this.queue.drain = noop + + // we defer the check, as a safety net for things + // that might be scheduled in the loading callback + queueMicrotask(check) + } + } + } + + queueMicrotask(check) + + // we start loading the dependents plugins only once + // the current level is finished + this.queue.resume() +} + +function noop () {} + +module.exports = { + Plugin +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/symbols.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..62cdf38e3d864597fe29574bfa2756b1af1c9fae --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/symbols.js @@ -0,0 +1,26 @@ +'use strict' + +// Internal Symbols +const kAvvio = Symbol('avvio.Boot') +const kIsOnCloseHandler = Symbol('isOnCloseHandler') +const kThenifyDoNotWrap = Symbol('avvio.ThenifyDoNotWrap') +const kUntrackNode = Symbol('avvio.TimeTree.untrackNode') +const kTrackNode = Symbol('avvio.TimeTree.trackNode') +const kGetParent = Symbol('avvio.TimeTree.getParent') +const kGetNode = Symbol('avvio.TimeTree.getNode') +const kAddNode = Symbol('avvio.TimeTree.addNode') + +// Public Symbols +const kPluginMeta = Symbol.for('plugin-meta') + +module.exports = { + kAvvio, + kIsOnCloseHandler, + kThenifyDoNotWrap, + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode, + kPluginMeta +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/thenify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/thenify.js new file mode 100644 index 0000000000000000000000000000000000000000..e1b614d3f8b842a3e4d37e3d5211d144c3aad57f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/thenify.js @@ -0,0 +1,60 @@ +'use strict' + +const { debug } = require('./debug') +const { kThenifyDoNotWrap } = require('./symbols') + +/** + * @callback PromiseConstructorLikeResolve + * @param {any} value + * @returns {void} + */ + +/** + * @callback PromiseConstructorLikeReject + * @param {reason} error + * @returns {void} + */ + +/** + * @callback PromiseConstructorLike + * @param {PromiseConstructorLikeResolve} resolve + * @param {PromiseConstructorLikeReject} reject + * @returns {void} + */ + +/** + * @returns {PromiseConstructorLike} + */ +function thenify () { + // If the instance is ready, then there is + // nothing to await. This is true during + // await server.ready() as ready() resolves + // with the server, end we will end up here + // because of automatic promise chaining. + if (this.booted) { + debug('thenify returning undefined because we are already booted') + return + } + + // Calling resolve(this._server) would fetch the then + // property on the server, which will lead it here. + // If we do not break the recursion, we will loop + // forever. + if (this[kThenifyDoNotWrap]) { + this[kThenifyDoNotWrap] = false + return + } + + debug('thenify') + return (resolve, reject) => { + const p = this._loadRegistered() + return p.then(() => { + this[kThenifyDoNotWrap] = true + return resolve(this._server) + }, reject) + } +} + +module.exports = { + thenify +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/time-tree.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/time-tree.js new file mode 100644 index 0000000000000000000000000000000000000000..5f02d68d44c9dfe5dabf735d8f8e316eb2b4ba54 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/time-tree.js @@ -0,0 +1,200 @@ +'use strict' + +const { + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode +} = require('./symbols') + +/** + * Node of the TimeTree + * @typedef {object} TimeTreeNode + * @property {string} id + * @property {string|null} parent + * @property {string} label + * @property {Array} nodes + * @property {number} start + * @property {number|undefined} stop + * @property {number|undefined} diff + */ + +class TimeTree { + constructor () { + /** + * @type {TimeTreeNode|null} root + * @public + */ + this.root = null + + /** + * @type {Map} tableId + * @public + */ + this.tableId = new Map() + + /** + * @type {Map>} tableLabel + * @public + */ + this.tableLabel = new Map() + } + + /** + * @param {TimeTreeNode} node + */ + [kTrackNode] (node) { + this.tableId.set(node.id, node) + if (this.tableLabel.has(node.label)) { + this.tableLabel.get(node.label).push(node) + } else { + this.tableLabel.set(node.label, [node]) + } + } + + /** + * @param {TimeTreeNode} node + */ + [kUntrackNode] (node) { + this.tableId.delete(node.id) + + const labelNode = this.tableLabel.get(node.label) + labelNode.pop() + + if (labelNode.length === 0) { + this.tableLabel.delete(node.label) + } + } + + /** + * @param {string} parent + * @returns {TimeTreeNode} + */ + [kGetParent] (parent) { + if (parent === null) { + return null + } else if (this.tableLabel.has(parent)) { + const parentNode = this.tableLabel.get(parent) + return parentNode[parentNode.length - 1] + } else { + return null + } + } + + /** + * + * @param {string} nodeId + * @returns {TimeTreeNode} + */ + [kGetNode] (nodeId) { + return this.tableId.get(nodeId) + } + + /** + * @param {string} parent + * @param {string} label + * @param {number} start + * @returns {TimeTreeNode["id"]} + */ + [kAddNode] (parent, label, start) { + const parentNode = this[kGetParent](parent) + const isRoot = parentNode === null + + if (isRoot) { + this.root = { + parent: null, + id: 'root', + label, + nodes: [], + start, + stop: null, + diff: -1 + } + this[kTrackNode](this.root) + return this.root.id + } + + const nodeId = `${label}-${Math.random()}` + /** + * @type {TimeTreeNode} + */ + const childNode = { + parent, + id: nodeId, + label, + nodes: [], + start, + stop: null, + diff: -1 + } + parentNode.nodes.push(childNode) + this[kTrackNode](childNode) + return nodeId + } + + /** + * @param {string} parent + * @param {string} label + * @param {number|undefined} start + * @returns {TimeTreeNode["id"]} + */ + start (parent, label, start = Date.now()) { + return this[kAddNode](parent, label, start) + } + + /** + * @param {string} nodeId + * @param {number|undefined} stop + */ + stop (nodeId, stop = Date.now()) { + const node = this[kGetNode](nodeId) + if (node) { + node.stop = stop + node.diff = (node.stop - node.start) || 0 + this[kUntrackNode](node) + } + } + + /** + * @returns {TimeTreeNode} + */ + toJSON () { + return Object.assign({}, this.root) + } + + /** + * @returns {string} + */ + prettyPrint () { + return prettyPrintTimeTree(this.toJSON()) + } +} + +/** + * @param {TimeTreeNode} obj + * @param {string|undefined} prefix + * @returns {string} + */ +function prettyPrintTimeTree (obj, prefix = '') { + let result = prefix + + const nodesCount = obj.nodes.length + const lastIndex = nodesCount - 1 + result += `${obj.label} ${obj.diff} ms\n` + + for (let i = 0; i < nodesCount; ++i) { + const node = obj.nodes[i] + const prefix_ = prefix + (i === lastIndex ? ' ' : '│ ') + + result += prefix + result += (i === lastIndex ? '└─' : '├─') + result += (node.nodes.length === 0 ? '─ ' : '┬ ') + result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2) + } + return result +} + +module.exports = { + TimeTree +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/validate-plugin.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/validate-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..374ee5616aff1d8a7ed3a68f5e92783964cce0de --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/lib/validate-plugin.js @@ -0,0 +1,26 @@ +'use strict' + +const { AVV_ERR_PLUGIN_NOT_VALID } = require('./errors') + +/** + * @param {any} maybePlugin + * @throws {AVV_ERR_PLUGIN_NOT_VALID} + * + * @returns {asserts plugin is Function|PromiseLike} + */ +function validatePlugin (maybePlugin) { + // validate if plugin is a function or Promise + if (!(maybePlugin && (typeof maybePlugin === 'function' || typeof maybePlugin.then === 'function'))) { + if (Array.isArray(maybePlugin)) { + throw new AVV_ERR_PLUGIN_NOT_VALID('array') + } else if (maybePlugin === null) { + throw new AVV_ERR_PLUGIN_NOT_VALID('null') + } else { + throw new AVV_ERR_PLUGIN_NOT_VALID(typeof maybePlugin) + } + } +} + +module.exports = { + validatePlugin +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-and-ready.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-and-ready.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ff3d7306b36a923b7b56d13aea6caf1d00e93025 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-and-ready.test.js @@ -0,0 +1,864 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('boot a plugin and then execute a call after that', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + cb() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('after without a done callback', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function (err) { + t.error(err) + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('verify when a afterred call happens', (t) => { + t.plan(3) + + const app = boot() + + app.use(function (s, opts, done) { + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.pass('afterred finished') + cb() + }) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('internal after', (t) => { + t.plan(18) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let afterCalled = false + + app.use(first) + app.use(third) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + s.after(function (err, cb) { + t.error(err) + t.notOk(afterCalled, 'after was not called') + afterCalled = true + cb() + }) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(afterCalled, 'after was not called') + secondLoaded = true + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(afterCalled, 'after was called') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(afterCalled, 'after was called') + t.pass('booted') + }) +}) + +test('ready adds at the end of the queue', (t) => { + t.plan(14) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + let readyCalled = false + + app.ready(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'after the plugin') + t.ok(afterCalled, 'after after') + readyCalled = true + process.nextTick(cb) + }) + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + t.notOk(readyCalled, 'ready not called') + pluginLoaded = true + + app.ready(function (err) { + t.error(err) + t.ok(readyCalled, 'after the first ready') + t.ok(afterCalled, 'after the after callback') + }) + + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'executing after!') + t.notOk(readyCalled, 'ready not called') + afterCalled = true + cb() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + t.ok(readyCalled, 'ready called') + }) +}) + +test('if the after/ready callback has two parameters, the first one must be the context', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done() + }) + + app.after(function (err, context, cb) { + t.error(err) + t.equal(server, context) + cb() + }) + + app.ready(function (err, context, cb) { + t.error(err) + t.equal(server, context) + cb() + }) +}) + +test('if the after/ready async, the returns must be the context generated', (t) => { + t.plan(3) + + const server = { my: 'server', index: 0 } + const app = boot(server) + app.override = function (old) { + return { ...old, index: old.index + 1 } + } + + app.use(function (s, opts, done) { + s.use(function (s, opts, done) { + s.ready().then(itself => t.same(itself, s, 'deep deep')) + done() + }) + s.ready().then(itself => t.same(itself, s, 'deep')) + done() + }) + + app.ready().then(itself => t.same(itself, server, 'outer')) +}) + +test('if the after/ready callback, the returns must be the context generated', (t) => { + t.plan(3) + + const server = { my: 'server', index: 0 } + const app = boot(server) + app.override = function (old) { + return { ...old, index: old.index + 1 } + } + + app.use(function (s, opts, done) { + s.use(function (s, opts, done) { + s.ready((_, itself, done) => { + t.same(itself, s, 'deep deep') + done() + }) + done() + }) + s.ready((_, itself, done) => { + t.same(itself, s, 'deep') + done() + }) + done() + }) + + app.ready((_, itself, done) => { + t.same(itself, server, 'outer') + done() + }) +}) + +test('error should come in the first after - one parameter', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first after - two parameters', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + cb() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first after - three parameter', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err, context, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + t.equal(context, server) + cb() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first ready - one parameter', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + }) +}) + +test('error should come in the first ready - two parameters', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + cb() + }) +}) + +test('error should come in the first ready - three parameters', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err, context, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + t.equal(context, server) + cb() + }) +}) + +test('if `use` has a callback with more then one parameter, the error must not reach ready', (t) => { + t.plan(1) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err) { + t.ok(err) + }) +}) + +test('if `use` has a callback without parameters, the error must reach ready', (t) => { + t.plan(1) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }, () => {}) + + app.ready(function (err) { + t.ok(err) + }) +}) + +test('should pass the errors from after to ready', (t) => { + t.plan(6) + + const server = {} + const app = boot(server, {}) + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after((err, done) => { + t.error(err) + done(new Error('some error')) + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(err => { + t.equal(err.message, 'some error') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('after no encapsulation', t => { + t.plan(4) + + const app = boot() + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) + next() + }) + + app.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('ready no encapsulation', t => { + t.plan(4) + + const app = boot() + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) + next() + }) + + app.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('after encapsulation with a server', t => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.after(function (err, i, done) { + t.error(err) + t.ok(i.test) + done() + }) + next() + }) + + app.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('ready encapsulation with a server', t => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.ready(function (err, i, done) { + t.error(err) + t.ok(i.test) + done() + }) + next() + }) + + app.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('after should passthrough the errors', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done(new Error('kaboom')) + }) + + app.after(function () { + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + }) + + app.ready(function (err) { + t.ok(err) + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('stop loading plugins if it errors', (t) => { + t.plan(2) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (server, opts, done) { + t.fail('this should never be called') + }) + + app.ready((err) => { + t.equal(err.message, 'kaboom') + }) +}) + +test('keep loading if there is an .after', (t) => { + t.plan(4) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('do not load nested plugin if parent errors', (t) => { + t.plan(4) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + + server.use(function second (_, opts, done) { + t.fail('this should never be called') + }) + + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function third (server, opts, done) { + t.pass('third called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('.after nested', (t) => { + t.plan(4) + + const app = boot() + + app.use(function outer (app, opts, done) { + app.use(function first (app, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function second (app, opts, done) { + t.pass('second called') + done() + }) + + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('nested error', (t) => { + t.plan(4) + + const app = boot() + + app.use(function outer (app, opts, done) { + app.use(function first (app, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (app, opts, done) { + t.fail('this should never be called') + }) + + done() + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function third (server, opts, done) { + t.pass('third called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('preReady event', (t) => { + t.plan(4) + + const app = boot() + const order = [1, 2] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.ready(() => { + t.equal(order.shift(), 2) + }) +}) + +test('preReady event (multiple)', (t) => { + t.plan(6) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 3) + }) + + app.ready(() => { + t.equal(order.shift(), 4) + }) +}) + +test('preReady event (nested)', (t) => { + t.plan(6) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + + server.on('preReady', () => { + t.equal(order.shift(), 3) + }) + + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.ready(() => { + t.equal(order.shift(), 4) + }) +}) + +test('preReady event (errored)', (t) => { + t.plan(5) + + const app = boot() + const order = [1, 2, 3] + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (server, opts, done) { + t.fail('We should not be here') + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.ready((err) => { + t.ok(err) + t.equal(order.shift(), 3) + }) +}) + +test('after return self', (t) => { + t.plan(6) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + let second = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function () { + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + // happens with after(() => app.use(..)) + return app + }) + + app.use(function (s, opts, done) { + t.ok(afterCalled, 'after called') + second = true + done() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + t.ok(second, 'second plugin loaded') + }) +}) + +test('after 1 param swallows errors with server and timeout', (t) => { + t.plan(3) + + const server = {} + boot(server, { autostart: false, timeout: 1000 }) + + server.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + server.use(function second (server, opts, done) { + t.fail('We should not be here') + }) + + server.after(function (err) { + t.ok(err) + }) + + server.ready(function (err) { + t.error(err) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-pass-through.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-pass-through.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9f1f54a641a9825be3dc1d2248ad8142af7ed00e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-pass-through.test.js @@ -0,0 +1,32 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('proper support for after with a passed async function in wrapped mode', (t) => { + const app = {} + boot(app) + + t.plan(5) + + const e = new Error('kaboom') + + app.use(function (f, opts) { + return Promise.reject(e) + }).after(function (err, cb) { + t.equal(err, e) + cb(err) + }).after(function () { + t.pass('this is just called') + }).after(function (err, cb) { + t.equal(err, e) + cb(err) + }) + + app.ready().then(() => { + t.fail('this should not be called') + }).catch(err => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-self-promise.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-self-promise.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bc0df24063a2c76d6a29d53b1523176dd754f5a5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-self-promise.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('after does not await itself', async (t) => { + t.plan(3) + + const app = {} + boot(app) + + app.use(async (app) => { + t.pass('plugin init') + }) + app.after(() => app) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-throw.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-throw.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c06e725709d42e6fdfd89f48ddc6f083829d5828 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-throw.test.js @@ -0,0 +1,24 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('catched error by Promise.reject', (t) => { + const app = boot() + t.plan(2) + + t.threw = function (err) { + t.equal(err.message, 'kaboom2') + } + + app.use(function (f, opts) { + return Promise.reject(new Error('kaboom')) + }).after(function (err) { + t.equal(err.message, 'kaboom') + throw new Error('kaboom2') + }) + + app.ready(function () { + t.fail('the ready callback should never be called') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-use-after.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-use-after.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d0ab5968b090307d470e6e9beda740e7b88dbc8d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/after-use-after.test.js @@ -0,0 +1,90 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const app = {} + +boot(app) + +test('multi after', (t) => { + t.plan(6) + + app.use(function (f, opts, cb) { + cb() + }).after(() => { + t.pass('this is just called') + + app.use(function (f, opts, cb) { + t.pass('this is just called') + cb() + }) + }).after(function () { + t.pass('this is just called') + app.use(function (f, opts, cb) { + t.pass('this is just called') + cb() + }) + }).after(function (err, cb) { + t.pass('this is just called') + cb(err) + }) + + app.ready().then(() => { + t.pass('ready') + }).catch(() => { + t.fail('this should not be called') + }) +}) + +test('after grouping - use called after after called', (t) => { + t.plan(9) + const app = {} + boot(app) + + const TEST_VALUE = {} + const OTHER_TEST_VALUE = {} + const NEW_TEST_VALUE = {} + + const sO = (fn) => { + fn[Symbol.for('skip-override')] = true + return fn + } + + app.use(sO(function (f, options, next) { + f.test = TEST_VALUE + + next() + })) + + app.after(function (err, f, done) { + t.error(err) + t.equal(f.test, TEST_VALUE) + + f.test2 = OTHER_TEST_VALUE + done() + }) + + app.use(sO(function (f, options, next) { + t.equal(f.test, TEST_VALUE) + t.equal(f.test2, OTHER_TEST_VALUE) + + f.test3 = NEW_TEST_VALUE + + next() + })) + + app.after(function (err, f, done) { + t.error(err) + t.equal(f.test, TEST_VALUE) + t.equal(f.test2, OTHER_TEST_VALUE) + t.equal(f.test3, NEW_TEST_VALUE) + done() + }) + + app.ready().then(() => { + t.pass('ready') + }).catch((e) => { + console.log(e) + t.fail('this should not be called') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/async-await.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/async-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..428e9f017b501eaddb83cc6b3867f9b3f621946a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/async-await.test.js @@ -0,0 +1,325 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const sleep = function (ms) { + return new Promise(function (resolve) { + setTimeout(resolve, ms) + }) +} + +const boot = require('..') + +test('one level', async (t) => { + t.plan(14) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + app.use(third) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + } + + async function second (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + } + + async function third (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('multiple reentrant plugin loading', async (t) => { + t.plan(31) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + let fifthLoaded = false + + app.use(first) + app.use(fifth) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + firstLoaded = true + s.use(second) + } + + async function second (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + secondLoaded = true + s.use(third) + await sleep(10) + s.use(fourth) + } + + async function third (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + thirdLoaded = true + } + + async function fourth (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fourthLoaded = true + } + + async function fifth (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fifthLoaded = true + } + + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.ok(fifthLoaded, 'fifth is loaded') + t.pass('booted') +}) + +test('async ready plugin registration (errored)', async (t) => { + t.plan(1) + + const app = boot() + + app.use(async (server, opts) => { + await sleep(10) + throw new Error('kaboom') + }) + + try { + await app.ready() + t.fail('we should not be here') + } catch (err) { + t.equal(err.message, 'kaboom') + } +}) + +test('after', async (t) => { + t.plan(15) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.after(second) + s.after(third) + } + + async function second (err) { + t.error(err) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + secondLoaded = true + } + + async function third () { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('after wrapped', async (t) => { + t.plan(15) + + const app = {} + boot(app) + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.after(second) + s.after(third) + } + + async function second (err) { + t.error(err) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + secondLoaded = true + } + + async function third () { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('promise plugins', async (t) => { + t.plan(14) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first()) + app.use(third()) + + async function first () { + return async function (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second()) + } + } + + async function second () { + return async function (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + } + } + + async function third () { + return async function (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + } + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('skip override with promise', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, func) { + t.pass('override called') + + if (func[Symbol.for('skip-override')]) { + return s + } + return Object.create(s) + } + + app.use(first()) + + async function first () { + async function fn (s, opts) { + t.equal(s, server) + t.notOk(Object.prototype.isPrototypeOf.call(server, s)) + } + + fn[Symbol.for('skip-override')] = true + + return fn + } +}) + +test('ready queue error', async (t) => { + const app = boot() + app.use(first) + + async function first (s, opts) {} + + app.ready(function (_, worker, done) { + const error = new Error('kaboom') + done(error) + }) + + await t.rejects(app.ready(), { message: 'kaboom' }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-after.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-after.test.js new file mode 100644 index 0000000000000000000000000000000000000000..eb801da55b060ee4d6ddd679d6e3d0b21151a8f5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-after.test.js @@ -0,0 +1,449 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { promisify } = require('node:util') +const sleep = promisify(setTimeout) +const fs = require('node:fs').promises +const path = require('node:path') + +test('await after - nested plugins with same tick callbacks', async (t) => { + const app = {} + boot(app) + + let secondLoaded = false + + app.use(async (app) => { + t.pass('plugin init') + app.use(async () => { + t.pass('plugin2 init') + await sleep(1) + secondLoaded = true + }) + }) + await app.after() + t.pass('reachable') + t.equal(secondLoaded, true) + + await app.ready() + t.pass('reachable') +}) + +test('await after without server', async (t) => { + const app = boot() + + let secondLoaded = false + + app.use(async (app) => { + t.pass('plugin init') + app.use(async () => { + t.pass('plugin2 init') + await sleep(1) + secondLoaded = true + }) + }) + await app.after() + t.pass('reachable') + t.equal(secondLoaded, true) + + await app.ready() + t.pass('reachable') +}) + +test('await after with cb functions', async (t) => { + const app = boot() + let secondLoaded = false + let record = '' + + app.use(async (app) => { + t.pass('plugin init') + record += 'plugin|' + app.use(async () => { + t.pass('plugin2 init') + record += 'plugin2|' + await sleep(1) + secondLoaded = true + }) + }) + await app.after(() => { + record += 'after|' + }) + t.pass('reachable') + t.equal(secondLoaded, true) + record += 'ready' + await app.ready() + t.pass('reachable') + t.equal(record, 'plugin|plugin2|after|ready') +}) + +test('await after - nested plugins with future tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + setImmediate(cb) + }) + setImmediate(cb) + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - nested async function plugins', async (t) => { + const app = {} + boot(app) + + t.plan(5) + + app.use(async (f, opts) => { + t.pass('plugin init') + await app.use(async (f, opts) => { + t.pass('plugin2 init') + }) + t.pass('reachable') + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - promise resolves to undefined', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + app.use(async (f, opts, cb) => { + app.use((f, opts, cb) => { + t.pass('plugin init') + cb() + }) + const instance = await app.after() + t.equal(instance, undefined) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - promise returning function plugins + promise chaining', async (t) => { + const app = {} + boot(app) + + t.plan(6) + + app.use((f, opts) => { + t.pass('plugin init') + return app.use((f, opts) => { + t.pass('plugin2 init') + return Promise.resolve() + }).then((f2) => { + t.equal(f2, f) + return 'test' + }).then((val) => { + t.equal(val, 'test') + }) + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - error handling, async throw', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + const e = new Error('kaboom') + + app.use(async (f, opts) => { + throw Error('kaboom') + }) + + await t.rejects(app.after(), e) + + await t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await after - error handling, async throw, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + const e = new Error('kaboom') + + app.use(async (f, opts) => { + app.use(async (f, opts) => { + throw e + }) + }) + + await t.rejects(app.after()) + await t.rejects(() => app.ready(), e) +}) + +test('await after - error handling, same tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, same tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + cb() + }) + + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, future tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, future tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + cb() + }) + await t.rejects(app.after(), Error('kaboom')) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after complex scenario', async (t) => { + const app = {} + boot(app) + t.plan(16) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + app.use(first) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(second) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(third) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + async function first () { + firstLoaded = true + } + + async function second () { + secondLoaded = true + } + + async function third (app) { + thirdLoaded = true + app.use(fourth) + } + + async function fourth () { + fourthLoaded = true + } +}) + +test('without autostart and sync/async plugin mix', async (t) => { + const app = {} + boot(app, { autostart: false }) + t.plan(21) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + app.use(first) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + app.use(second) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + await sleep(10) + + app.use(third) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + app.use(fourth) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + await app.ready() + + async function first () { + firstLoaded = true + } + + async function second () { + const contents = await fs.readFile(path.join(__dirname, 'fixtures', 'dummy.txt'), 'utf-8') + t.equal(contents, 'hello, world!') + secondLoaded = true + } + + async function third () { + await sleep(10) + thirdLoaded = true + } + + function fourth (server, opts, done) { + fourthLoaded = true + done() + } +}) + +test('without autostart', async (t) => { + const app = {} + boot(app, { autostart: false }) + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(async function first (app) { + firstLoaded = true + app.use(async () => { + await sleep(1) + secondLoaded = true + }) + }) + + await app.after() + t.equal(firstLoaded, true) + t.equal(secondLoaded, true) + + await app.use(async () => { + thirdLoaded = true + }) + + t.equal(thirdLoaded, true) + + await app.ready() +}) + +test('without autostart and with override', async (t) => { + const app = {} + const _ = boot(app, { autostart: false }) + let count = 0 + + _.override = function (s) { + const res = Object.create(s) + res.count = ++count + + return res + } + + app.use(async function first (app) { + t.equal(app.count, 1) + app.use(async (app) => { + t.equal(app.count, 2) + await app.after() + }) + }) + + await app.after() + + await app.use(async (app) => { + t.equal(app.count, 3) + }) + + await app.ready() +}) + +test('stop processing after errors', async (t) => { + t.plan(2) + + const app = boot() + + try { + await app.use(async function first (app) { + t.pass('first should be loaded') + throw new Error('kaboom') + }) + } catch (e) { + t.equal(e.message, 'kaboom') + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-self.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-self.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8d8c9908be3d5c435c0ec4cdd63eb1fb7761fc18 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-self.test.js @@ -0,0 +1,31 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('await self', async (t) => { + const app = {} + boot(app) + + t.equal(await app, app) +}) + +test('await self three times', async (t) => { + const app = {} + boot(app) + + t.equal(await app, app) + t.equal(await app, app) + t.equal(await app, app) +}) + +test('await self within plugin', async (t) => { + const app = {} + boot(app) + + app.use(async (f) => { + t.equal(await f, f) + }) + + t.equal(await app, app) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-use.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-use.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f8adee86641d5fcd5466c7a8deed12fae85c3e7f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/await-use.test.js @@ -0,0 +1,294 @@ +'use strict' + +const { test } = require('tap') +const { promisify } = require('node:util') +const sleep = promisify(setTimeout) +const boot = require('..') + +test('await use - nested plugins with same tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + await app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + cb() + }) + cb() + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - nested plugins with future tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + await app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + setImmediate(cb) + }) + setImmediate(cb) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - nested async function plugins', async (t) => { + const app = {} + boot(app) + + t.plan(5) + + await app.use(async (f, opts) => { + t.pass('plugin init') + await app.use(async (f, opts) => { + t.pass('plugin2 init') + }) + t.pass('reachable') + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - promise returning function plugins + promise chaining', async (t) => { + const app = {} + boot(app) + + t.plan(6) + + await app.use((f, opts) => { + t.pass('plugin init') + return app.use((f, opts) => { + t.pass('plugin2 init') + return Promise.resolve() + }).then(() => { + t.pass('reachable') + return 'test' + }).then((val) => { + t.equal(val, 'test') + }) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - await and use chaining', async (t) => { + const app = {} + boot(app) + + t.plan(3) + + app.use(async (f, opts, cb) => { + await app.use(async (f, opts) => { + t.pass('plugin init') + }).use(async (f, opts) => { + t.pass('plugin2 init') + }) + }) + + await app.ready() + t.pass('reachable') +}) + +function thenableRejects (t, thenable, err, msg) { + return t.rejects(async () => { await thenable }, err, msg) +} + +test('await use - error handling, async throw', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use(async (f, opts) => { + throw Error('kaboom') + }), Error('kaboom')) + + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await use - error handling, async throw, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use(async function a (f, opts) { + await app.use(async function b (f, opts) { + throw Error('kaboom') + }) + }, Error('kaboom')), 'b') + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, same tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + cb(Error('kaboom')) + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, same tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + cb() + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, future tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, future tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + cb() + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('mixed await use and non-awaited use ', async (t) => { + const app = {} + boot(app) + t.plan(16) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + await app.use(first) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(second) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + await app.use(third) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + async function first () { + firstLoaded = true + } + + async function second () { + secondLoaded = true + } + + async function third (app) { + thirdLoaded = true + app.use(fourth) + } + + async function fourth () { + fourthLoaded = true + } +}) + +test('await use - mix of same and future tick callbacks', async (t) => { + const app = {} + boot(app, { autostart: false }) + let record = '' + + t.plan(4) + + await app.use(async function plugin0 () { + t.pass('plugin0 init') + record += 'plugin0|' + }) + await app.use(async function plugin1 () { + t.pass('plugin1 init') + await sleep(500) + record += 'plugin1|' + }) + await sleep(1) + await app.use(async function plugin2 () { + t.pass('plugin2 init') + await sleep(500) + record += 'plugin2|' + }) + record += 'ready' + t.equal(record, 'plugin0|plugin1|plugin2|ready') +}) + +test('await use - fork the promise chain', (t) => { + t.plan(3) + const app = {} + boot(app, { autostart: false }) + + async function setup () { + let set = false + await app.use(async function plugin0 () { + t.pass('plugin0 init') + await sleep(500) + set = true + }) + t.equal(set, true) + } + setup() + + app.ready((err, done) => { + t.error(err) + done() + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/basic.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/basic.test.js new file mode 100644 index 0000000000000000000000000000000000000000..05a4810b7e78d9bfda32959fa00e36cf047cfc29 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/basic.test.js @@ -0,0 +1,439 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('boot an empty app', (t) => { + t.plan(1) + const app = boot() + app.on('start', () => { + t.pass('booted') + }) +}) + +test('start returns app', (t) => { + t.plan(1) + const app = boot({}, { autostart: false }) + app + .start() + .ready((err) => { + t.error(err) + }) +}) + +test('boot an app with a plugin', (t) => { + t.plan(4) + + const app = boot() + let after = false + + app.use(function (server, opts, done) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + done() + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot an app with a promisified plugin', (t) => { + t.plan(4) + + const app = boot() + let after = false + + app.use(function (server, opts) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + return Promise.resolve() + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot an app with a plugin and a callback /1', (t) => { + t.plan(2) + + const app = boot(() => { + t.pass('booted') + }) + + app.use(function (server, opts, done) { + t.pass('plugin loaded') + done() + }) +}) + +test('boot an app with a plugin and a callback /2', (t) => { + t.plan(2) + + const app = boot({}, () => { + t.pass('booted') + }) + + app.use(function (server, opts, done) { + t.pass('plugin loaded') + done() + }) +}) + +test('boot a plugin with a custom server', (t) => { + t.plan(4) + + const server = {} + const app = boot(server) + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }) + + app.onClose(() => { + t.ok('onClose called') + }) + + app.on('start', () => { + app.close(() => { + t.pass('booted') + }) + }) +}) + +test('custom instance should inherits avvio methods /1', (t) => { + t.plan(6) + + const server = {} + const app = boot(server, {}) + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after(() => { + t.ok('after called') + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(() => { + t.ok('ready called') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('custom instance should inherits avvio methods /2', (t) => { + t.plan(6) + + const server = {} + const app = new boot(server, {}) // eslint-disable-line new-cap + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after(() => { + t.ok('after called') + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(() => { + t.ok('ready called') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('boot a plugin with options', (t) => { + t.plan(3) + + const server = {} + const app = boot(server) + const myOpts = { + hello: 'world' + } + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, myOpts, 'passed options') + done() + }, myOpts) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot a plugin with a function that returns the options', (t) => { + t.plan(4) + + const server = {} + const app = boot(server) + const myOpts = { + hello: 'world' + } + const myOptsAsFunc = parent => { + t.equal(parent, server) + return parent.myOpts + } + + app.use(function (s, opts, done) { + s.myOpts = opts + done() + }, myOpts) + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, myOpts, 'passed options via function accessing parent injected variable') + done() + }, myOptsAsFunc) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('throw on non-function use', (t) => { + t.plan(1) + const app = boot() + t.throws(() => { + app.use({}) + }) +}) + +// https://github.com/mcollina/avvio/issues/20 +test('ready and nextTick', (t) => { + const app = boot() + process.nextTick(() => { + app.ready(() => { + t.end() + }) + }) +}) + +// https://github.com/mcollina/avvio/issues/20 +test('promises and microtask', (t) => { + const app = boot() + Promise.resolve() + .then(() => { + app.ready(function () { + t.end() + }) + }) +}) + +test('always loads nested plugins after the current one', (t) => { + t.plan(2) + + const server = {} + const app = boot(server) + + let second = false + + app.use(function (s, opts, done) { + app.use(function (s, opts, done) { + second = true + done() + }) + t.notOk(second) + + done() + }) + + app.on('start', () => { + t.ok(second) + }) +}) + +test('promise long resolve', (t) => { + t.plan(2) + + const app = boot() + + setTimeout(function () { + t.throws(() => { + app.use((s, opts, done) => { + done() + }) + }, 'root plugin has already booted') + }) + + app.ready(function (err) { + t.notOk(err) + }) +}) + +test('do not autostart', (t) => { + const app = boot(null, { + autostart: false + }) + app.on('start', () => { + t.fail() + }) + t.end() +}) + +test('start with ready', (t) => { + t.plan(2) + + const app = boot(null, { + autostart: false + }) + + app.on('start', () => { + t.pass() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('load a plugin after start()', (t) => { + t.plan(1) + + let startCalled = false + const app = boot(null, { + autostart: false + }) + + app.use((s, opts, done) => { + t.ok(startCalled) + done() + }) + + // we use a timer because + // it is more reliable than + // nextTick and setImmediate + // this almost always will come + // after those are completed + setTimeout(() => { + app.start() + startCalled = true + }, 2) +}) + +test('booted should be set before ready', (t) => { + t.plan(2) + + const app = boot() + + app.ready(function (err) { + t.error(err) + t.equal(app.booted, true) + }) +}) + +test('start should be emitted after ready resolves', (t) => { + t.plan(1) + + const app = boot() + let ready = false + + app.ready().then(function () { + ready = true + }) + + app.on('start', function () { + t.equal(ready, true) + }) +}) + +test('throws correctly if registering after ready', (t) => { + t.plan(1) + + const app = boot() + + app.ready(function () { + t.throws(() => { + app.use((a, b, done) => done()) + }, 'root plugin has already booted') + }) +}) + +test('preReady errors must be managed', (t) => { + t.plan(2) + + const app = boot() + + app.use((f, opts, cb) => { + cb() + }) + + app.on('preReady', () => { + throw new Error('boom') + }) + + app.ready(err => { + t.pass('ready function is called') + t.equal(err.message, 'boom') + }) +}) + +test('preReady errors do not override plugin\'s errors', (t) => { + t.plan(3) + + const app = boot() + + app.use((f, opts, cb) => { + cb(new Error('baam')) + }) + + app.on('preReady', () => { + t.pass('preReady is executed') + throw new Error('boom') + }) + + app.ready(err => { + t.pass('ready function is called') + t.equal(err.message, 'baam') + }) +}) + +test('support faux modules', (t) => { + t.plan(4) + + const app = boot() + let after = false + + // Faux modules are modules built with TypeScript + // or Babel that they export a .default property. + app.use({ + default: function (server, opts, done) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + done() + } + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/callbacks.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/callbacks.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2e7ac1c2d46876b72d835a607f45fae251cbbe7a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/callbacks.test.js @@ -0,0 +1,113 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('reentrant', (t) => { + t.plan(7) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + + app + .use(first) + .after(() => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.pass('booted') + }) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + secondLoaded = true + done() + } +}) + +test('reentrant with callbacks deferred', (t) => { + t.plan(11) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + setTimeout(() => { + try { + s.use(third) + } catch (err) { + t.equal(err.message, 'Root plugin has already booted') + } + }, 500) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + done() + } + + function third (s, opts, done) { + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.pass('booted') + }) +}) + +test('multiple loading time', t => { + t.plan(1) + const app = boot() + + function a (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 10) + } + const pointer = a + + function b (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 20) + } + + function c (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 30) + } + + app + .use(function a (instance, opts, done) { + instance.use(pointer, { use: [b], subUse: [c] }) + .use(b) + setTimeout(done, 0) + }) + .after(() => { + t.pass('booted') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fdcd58aa1d239b47255782c4ff7141a053baa62d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('catch exceptions in parent.override', (t) => { + t.plan(2) + + const server = {} + + const app = boot(server, { + autostart: false + }) + app.override = function () { + throw Error('catch it') + } + + app + .use(function () {}) + .start() + + app.ready(function (err) { + t.type(err, Error) + t.match(err, /catch it/) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/chainable.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/chainable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d07a7ac0ddde64bd8d82e5b0d639de99b3309369 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/chainable.test.js @@ -0,0 +1,67 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('chainable standalone', (t) => { + t.plan(5) + + const readyResult = boot() + .use(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) + +test('chainable automatically binded', (t) => { + t.plan(5) + + const app = {} + boot(app) + + const readyResult = app + .use(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) + +test('chainable standalone with server', (t) => { + t.plan(6) + + const server = {} + boot(server, { + expose: { + use: 'register' + } + }) + + const readyResult = server.register(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).register(function (ctx, opts, done) { + t.pass('3rd plugin') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/close.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/close.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a02914b8ed4c5f14ff0059251779e6b645c049fc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/close.test.js @@ -0,0 +1,544 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { AVV_ERR_CALLBACK_NOT_FN } = require('../lib/errors') + +test('boot an app with a plugin', (t) => { + t.plan(4) + + const app = boot() + let last = false + + app.use(function (server, opts, done) { + app.onClose(() => { + t.ok('onClose called') + t.notOk(last) + last = true + }) + done() + }) + + app.on('start', () => { + app.close(() => { + t.ok(last) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments', (t) => { + t.plan(5) + + const app = boot() + + app.use(function (server, opts, next) { + server.onClose((instance, done) => { + t.ok('called') + t.equal(server, instance) + done() + }) + next() + }) + + app.use(function (server, opts, next) { + server.onClose((instance) => { + t.ok('called') + t.equal(server, instance) + }) + next() + }) + + app.on('start', () => { + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments - fastify encapsulation test case', (t) => { + t.plan(5) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.ok(i.test) + done() + }) + next() + }) + + app.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.on('start', () => { + t.notOk(app.test) + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments - fastify encapsulation test case / 2', (t) => { + t.plan(5) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + server.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.ok(i.test) + done() + }) + next() + }) + + server.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.on('start', () => { + t.notOk(server.test) + try { + server.close() + t.pass() + } catch (err) { + t.fail(err) + } + }) +}) + +test('onClose arguments - encapsulation test case no server', (t) => { + t.plan(5) + + const app = boot() + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i) => { + t.notOk(i.test) + }) + next() + }) + + app.on('start', () => { + t.notOk(app.test) + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose should handle errors', (t) => { + t.plan(3) + + const app = boot() + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done(new Error('some error')) + }) + done() + }) + + app.on('start', () => { + app.close(err => { + t.equal(err.message, 'some error') + t.pass('Closed in the correct order') + }) + }) +}) + +test('#54 close handlers should receive same parameters when queue is not empty', (t) => { + t.plan(6) + + const context = { test: true } + const app = boot(context) + + app.use(function (server, opts, done) { + done() + }) + app.on('start', () => { + app.close((err, done) => { + t.equal(err, null) + t.pass('Closed in the correct order') + setImmediate(done) + }) + app.close(err => { + t.equal(err, null) + t.pass('Closed in the correct order') + }) + app.close(err => { + t.equal(err, null) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose should handle errors / 2', (t) => { + t.plan(4) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done(new Error('some error')) + }) + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done() + }) + done() + }) + + app.on('start', () => { + app.close(err => { + t.equal(err.message, 'some error') + t.pass('Closed in the correct order') + }) + }) +}) + +test('close arguments', (t) => { + t.plan(4) + + const app = boot() + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done() + }) + done() + }) + + app.on('start', () => { + app.close((err, instance, done) => { + t.error(err) + t.equal(instance, app) + done() + t.pass('Closed in the correct order') + }) + }) +}) + +test('close event', (t) => { + t.plan(3) + + const app = boot() + let last = false + + app.on('start', () => { + app.close(() => { + t.notOk(last) + last = true + }) + }) + + app.on('close', () => { + t.ok(last) + t.pass('event fired') + }) +}) + +test('close order', (t) => { + t.plan(5) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 3) + }) + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 2) + }) + done() + }) + done() + }) + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 1) + }) + done() + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 4) + t.pass('Closed in the correct order') + }) + }) +}) + +test('close without a cb', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + app.close() +}) + +test('onClose with 0 parameters', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (instance, opts, next) { + instance.onClose(function () { + t.ok('called') + t.equal(arguments.length, 0) + }) + next() + }) + + app.close(err => { + t.error(err) + t.pass('Closed') + }) +}) + +test('onClose with 1 parameter', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (instance, opts, next) { + instance.onClose(function (context) { + t.equal(arguments.length, 1) + }) + next() + }) + + app.close(err => { + t.error(err) + t.pass('Closed') + }) +}) + +test('close passing not a function', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close passing not a function', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close passing not a function when wrapping', (t) => { + t.plan(1) + + const app = {} + boot(app) + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close should trigger ready()', (t) => { + t.plan(2) + + const app = boot(null, { + autostart: false + }) + + app.on('start', () => { + // this will be emitted after the + // callback in close() is fired + t.pass('started') + }) + + app.close(() => { + t.pass('closed') + }) +}) + +test('close without a cb returns a promise', (t) => { + t.plan(1) + + const app = boot() + app.close().then(() => { + t.pass('promise resolves') + }) +}) + +test('close without a cb returns a promise when attaching to a server', (t) => { + t.plan(1) + + const server = {} + boot(server) + server.close().then(() => { + t.pass('promise resolves') + }) +}) + +test('close with async onClose handlers', t => { + t.plan(7) + + const app = boot() + const order = [1, 2, 3, 4, 5, 6] + + app.onClose(() => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 5) + }) + }) + + app.onClose(() => { + t.equal(order.shift(), 4) + }) + + app.onClose(instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 3) + }) + }) + + app.onClose(async instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 2) + }) + }) + + app.onClose(async () => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 1) + }) + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 6) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose callback must be a function', (t) => { + t.plan(1) + + const app = boot() + + app.use(function (server, opts, done) { + t.throws(() => app.onClose({}), new AVV_ERR_CALLBACK_NOT_FN('onClose', 'object')) + done() + }) +}) + +test('close custom server with async onClose handlers', t => { + t.plan(7) + + const server = {} + const app = boot(server) + const order = [1, 2, 3, 4, 5, 6] + + server.onClose(() => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 5) + }) + }) + + server.onClose(() => { + t.equal(order.shift(), 4) + }) + + server.onClose(instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 3) + }) + }) + + server.onClose(async instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 2) + }) + }) + + server.onClose(async () => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 1) + }) + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 6) + t.pass('Closed in the correct order') + }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/errors.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/errors.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e18138259bf1224ed6eac0a9300ed5c8ecd2a43d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/errors.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('tap') +const errors = require('../lib/errors') + +test('Correct codes of AvvioErrors', t => { + const testcases = [ + 'AVV_ERR_EXPOSE_ALREADY_DEFINED', + 'AVV_ERR_ATTRIBUTE_ALREADY_DEFINED', + 'AVV_ERR_CALLBACK_NOT_FN', + 'AVV_ERR_PLUGIN_NOT_VALID', + 'AVV_ERR_ROOT_PLG_BOOTED', + 'AVV_ERR_PARENT_PLG_LOADED', + 'AVV_ERR_READY_TIMEOUT', + 'AVV_ERR_PLUGIN_EXEC_TIMEOUT' + ] + + t.plan(testcases.length + 1) + // errors.js exposes errors and the createError fn + t.equal(testcases.length, Object.keys(errors).length) + + for (const testcase of testcases) { + const error = new errors[testcase]() + t.equal(error.code, testcase) + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df53d64683658ec10df29bf15b22f34c2d6c4608 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.mjs @@ -0,0 +1,12 @@ +import { test } from 'tap' +import boot from '../boot.js' + +test('support import', async (t) => { + const app = boot() + + app.use(import('./fixtures/esm.mjs')) + + await app.ready() + + t.equal(app.loaded, true) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d930881ea070ec7830f28efee73f308ceab8b7b4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/esm.test.js @@ -0,0 +1,14 @@ +'use strict' + +const { test } = require('tap') + +test('support esm import', (t) => { + import('./esm.mjs').then(() => { + t.pass('esm is supported') + t.end() + }).catch((err) => { + process.nextTick(() => { + throw err + }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/events-listeners.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/events-listeners.test.js new file mode 100644 index 0000000000000000000000000000000000000000..810d43b59c8fe9fb9621743241fc1241363d34dd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/events-listeners.test.js @@ -0,0 +1,23 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const noop = () => {} + +test('boot a plugin and then execute a call after that', (t) => { + t.plan(1) + + process.on('warning', (warning) => { + t.fail('we should not get a warning', warning) + }) + + const app = boot() + // eslint-disable-next-line no-var + for (var i = 0; i < 12; i++) { + app.on('preReady', noop) + } + + setTimeout(() => { + t.pass('Everything ok') + }, 500) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/expose.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/expose.test.js new file mode 100644 index 0000000000000000000000000000000000000000..422524e5e2ced2489c0cd9903bb809e2fa8eca77 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/expose.test.js @@ -0,0 +1,80 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { AVV_ERR_EXPOSE_ALREADY_DEFINED, AVV_ERR_ATTRIBUTE_ALREADY_DEFINED } = require('../lib/errors') +const { kAvvio } = require('../lib/symbols') + +for (const key of ['use', 'after', 'ready', 'onClose', 'close']) { + test('throws if ' + key + ' is by default already there', (t) => { + t.plan(1) + + const app = {} + app[key] = () => { } + + t.throws(() => boot(app), new AVV_ERR_EXPOSE_ALREADY_DEFINED(key, key)) + }) + + test('throws if ' + key + ' is already there', (t) => { + t.plan(1) + + const app = {} + app['cust' + key] = () => { } + + t.throws(() => boot(app, { expose: { [key]: 'cust' + key } }), new AVV_ERR_EXPOSE_ALREADY_DEFINED('cust' + key, key)) + }) + + test('support expose for ' + key, (t) => { + const app = {} + app[key] = () => { } + + const expose = {} + expose[key] = 'muahah' + + boot(app, { + expose + }) + + t.end() + }) +} + +test('set the kAvvio to true on the server', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.ok(server[kAvvio]) +}) + +test('.then()', t => { + t.plan(3) + + t.test('.then() can not be overwritten', (t) => { + t.plan(1) + + const server = { + then: () => {} + } + t.throws(() => boot(server), AVV_ERR_ATTRIBUTE_ALREADY_DEFINED('then')) + }) + + t.test('.then() is a function', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.type(server.then, 'function') + }) + + t.test('.then() can not be overwritten', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.throws(() => { server.then = 'invalid' }, TypeError('Cannot set property then of # which has only a getter')) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt new file mode 100644 index 0000000000000000000000000000000000000000..30f51a3fba5274d53522d0f19748456974647b4f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt @@ -0,0 +1 @@ +hello, world! \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ae3574db370a4ff4c105641c7b94172cc153a2ea --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs @@ -0,0 +1,3 @@ +export default async function (app) { + app.loaded = true +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js new file mode 100644 index 0000000000000000000000000000000000000000..cc19b0652658499ffa659889f482d677c9739b9f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = function noNext (app, opts, next) { + // no call to next +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1dbd4dfb128c228f3cc7145c15c8e7c2db14a7dc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js @@ -0,0 +1,16 @@ +'use strict' + +const { test } = require('tap') +const boot = require('../..') + +test('should print the time tree', (t) => { + t.plan(2) + const app = boot() + + app.use(function first (instance, opts, cb) { + const out = instance.prettyPrint().split('\n') + t.equal(out[0], 'root -1 ms') + t.equal(out[1], '└── first -1 ms') + cb() + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js new file mode 100644 index 0000000000000000000000000000000000000000..99ed5c69887f61955c78b9236029f2bc11a277d7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js @@ -0,0 +1,55 @@ +'use strict' + +const { test } = require('tap') +const { createPromise } = require('../../lib/create-promise') + +test('createPromise() returns an object', (t) => { + t.plan(3) + t.type(createPromise(), 'object') + t.equal(Array.isArray(createPromise()), false) + t.notOk(Array.isArray(createPromise() !== null)) +}) + +test('createPromise() returns an attribute with attribute resolve', (t) => { + t.plan(1) + t.ok('resolve' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute reject', (t) => { + t.plan(1) + t.ok('reject' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute createPromise', (t) => { + t.plan(1) + t.ok('promise' in createPromise()) +}) + +test('when resolve is called, createPromise attribute is resolved', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.pass() + }) + .catch(() => { + t.fail() + }) + p.resolve() +}) + +test('when reject is called, createPromise attribute is rejected', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.fail() + }) + .catch(() => { + t.pass() + }) + + p.reject() +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f51ac4ec22f3755c850bbf627ae3ecafa3c76e7d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js @@ -0,0 +1,82 @@ +'use strict' + +const { test } = require('tap') +const { executeWithThenable } = require('../../lib/execute-with-thenable') +const { kAvvio } = require('../../lib/symbols') + +test('executeWithThenable', (t) => { + t.plan(6) + + t.test('passes the arguments to the function', (t) => { + t.plan(5) + + executeWithThenable((...args) => { + t.equal(args.length, 3) + t.equal(args[0], 1) + t.equal(args[1], 2) + t.equal(args[2], 3) + }, [1, 2, 3], (err) => { + t.error(err) + }) + }) + + t.test('function references this to itself', (t) => { + t.plan(2) + + const func = function () { + t.equal(this, func) + } + executeWithThenable(func, [], (err) => { + t.error(err) + }) + }) + + t.test('handle resolving Promise of func', (t) => { + t.plan(1) + + const fn = function () { + return Promise.resolve(42) + } + + executeWithThenable(fn, [], (err) => { + t.error(err) + }) + }) + + t.test('handle rejecting Promise of func', (t) => { + t.plan(1) + + const fn = function () { + return Promise.reject(new Error('Arbitrary Error')) + } + + executeWithThenable(fn, [], (err) => { + t.equal(err.message, 'Arbitrary Error') + }) + }) + + t.test('dont handle avvio mocks PromiseLike results but use callback if provided', (t) => { + t.plan(1) + + const fn = function () { + const result = Promise.resolve(42) + result[kAvvio] = true + } + + executeWithThenable(fn, [], (err) => { + t.error(err) + }) + }) + + t.test('dont handle avvio mocks Promises and if no callback is provided', (t) => { + t.plan(1) + + const fn = function () { + t.pass(1) + const result = Promise.resolve(42) + result[kAvvio] = true + } + + executeWithThenable(fn, []) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2cb385397c9e35c44f3d67daf2ae613152561495 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js @@ -0,0 +1,67 @@ +'use strict' + +const { test } = require('tap') +const { getPluginName } = require('../../lib/get-plugin-name') +const { kPluginMeta } = require('../../lib/symbols') + +test('getPluginName of function', (t) => { + t.plan(1) + + t.equal(getPluginName(function aPlugin () { }), 'aPlugin') +}) + +test('getPluginName of async function', (t) => { + t.plan(1) + + t.equal(getPluginName(async function aPlugin () { }), 'aPlugin') +}) + +test('getPluginName of arrow function without name', (t) => { + t.plan(2) + + t.equal(getPluginName(() => { }), '() => { }') + t.equal(getPluginName(() => { return 'random' }), '() => { return \'random\' }') +}) + +test('getPluginName of arrow function assigned to variable', (t) => { + t.plan(1) + + const namedArrowFunction = () => { } + t.equal(getPluginName(namedArrowFunction), 'namedArrowFunction') +}) + +test("getPluginName based on Symbol 'plugin-meta' /1", (t) => { + t.plan(1) + + function plugin () { + + } + + plugin[kPluginMeta] = {} + t.equal(getPluginName(plugin), 'plugin') +}) + +test("getPluginName based on Symbol 'plugin-meta' /2", (t) => { + t.plan(1) + + function plugin () { + + } + + plugin[kPluginMeta] = { + name: 'fastify-non-existent' + } + t.equal(getPluginName(plugin), 'fastify-non-existent') +}) + +test('getPluginName if null is provided as options', (t) => { + t.plan(1) + + t.equal(getPluginName(function a () {}, null), 'a') +}) + +test('getPluginName if name is provided in options', (t) => { + t.plan(1) + + t.equal(getPluginName(function defaultName () {}, { name: 'providedName' }), 'providedName') +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b81029b714686af47469dab3ca1100448543992f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const { isBundledOrTypescriptPlugin } = require('../../lib/is-bundled-or-typescript-plugin') + +test('isBundledOrTypescriptPlugin', (t) => { + t.plan(9) + + t.equal(isBundledOrTypescriptPlugin(1), false) + t.equal(isBundledOrTypescriptPlugin('function'), false) + t.equal(isBundledOrTypescriptPlugin({}), false) + t.equal(isBundledOrTypescriptPlugin([]), false) + t.equal(isBundledOrTypescriptPlugin(null), false) + + t.equal(isBundledOrTypescriptPlugin(function () {}), false) + t.equal(isBundledOrTypescriptPlugin(new Promise((resolve) => resolve)), false) + t.equal(isBundledOrTypescriptPlugin(Promise.resolve()), false) + + t.equal(isBundledOrTypescriptPlugin({ default: () => {} }), true) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f1407661f3447d386054332ed4105ccc4a506250 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const { isPromiseLike } = require('../../lib/is-promise-like') + +test('isPromiseLike', (t) => { + t.plan(9) + + t.equal(isPromiseLike(1), false) + t.equal(isPromiseLike('function'), false) + t.equal(isPromiseLike({}), false) + t.equal(isPromiseLike([]), false) + t.equal(isPromiseLike(null), false) + + t.equal(isPromiseLike(function () {}), false) + t.equal(isPromiseLike(new Promise((resolve) => resolve)), true) + t.equal(isPromiseLike(Promise.resolve()), true) + + t.equal(isPromiseLike({ then: () => {} }), true) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/thenify.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/thenify.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2004a0a40f3ce8c5208d824daaea95a02dd3f450 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/thenify.test.js @@ -0,0 +1,123 @@ +'use strict' + +const { test, mockRequire } = require('tap') +const { kThenifyDoNotWrap } = require('../../lib/symbols') + +test('thenify', (t) => { + t.plan(7) + + t.test('return undefined if booted', (t) => { + t.plan(2) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify returning undefined because we are already booted') } + } + }) + const result = thenify.call({ + booted: true + }) + t.equal(result, undefined) + }) + + t.test('return undefined if kThenifyDoNotWrap is true', (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + const result = thenify.call({ + [kThenifyDoNotWrap]: true + }) + t.equal(result, undefined) + }) + + t.test('return PromiseConstructorLike if kThenifyDoNotWrap is false', (t) => { + t.plan(3) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify') } + } + }) + const promiseContructorLike = thenify.call({ + [kThenifyDoNotWrap]: false + }) + + t.type(promiseContructorLike, 'function') + t.equal(promiseContructorLike.length, 2) + }) + + t.test('return PromiseConstructorLike', (t) => { + t.plan(3) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify') } + } + }) + const promiseContructorLike = thenify.call({}) + + t.type(promiseContructorLike, 'function') + t.equal(promiseContructorLike.length, 2) + }) + + t.test('resolve should return _server', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.resolve() + }, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.equal(value, 'server') + }, function (reason) { + t.error(reason) + }) + }) + + t.test('resolving should set kThenifyDoNotWrap to true', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.resolve() + }, + [kThenifyDoNotWrap]: false, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.equal(server[kThenifyDoNotWrap], true) + }, function (reason) { + t.error(reason) + }) + }) + + t.test('rejection should pass through to reject', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.reject(new Error('Arbitrary rejection')) + }, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.error(value) + }, function (reason) { + t.equal(reason.message, 'Arbitrary rejection') + }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8bef526c263e97af12d9d36fc488c077bdc26165 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js @@ -0,0 +1,391 @@ +'use strict' + +const { test } = require('tap') +const { TimeTree } = require('../../lib/time-tree') + +test('TimeTree is constructed with a root attribute, set to null', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.root, null) +}) + +test('TimeTree is constructed with an empty tableId-Map', t => { + t.plan(2) + + const tree = new TimeTree() + t.ok(tree.tableId instanceof Map) + t.equal(tree.tableId.size, 0) +}) + +test('TimeTree is constructed with an empty tableLabel-Map', t => { + t.plan(2) + + const tree = new TimeTree() + t.ok(tree.tableLabel instanceof Map) + t.equal(tree.tableLabel.size, 0) +}) + +test('TimeTree#toJSON dumps the content of the TimeTree', t => { + t.plan(1) + + const tree = new TimeTree() + t.same(tree.toJSON(), {}) +}) + +test('TimeTree#toJSON is creating new instances of its content, ensuring being immutable', t => { + t.plan(1) + + const tree = new TimeTree() + t.not(tree.toJSON(), tree.toJSON()) +}) + +test('TimeTree#start is adding a node with correct shape, root-node', t => { + t.plan(15) + + const tree = new TimeTree() + tree.start(null, 'root') + + const rootNode = tree.root + + t.equal(Object.keys(rootNode).length, 7) + t.ok('parent' in rootNode) + t.equal(rootNode.parent, null) + t.ok('id' in rootNode) + t.type(rootNode.id, 'string') + t.ok('label' in rootNode) + t.type(rootNode.label, 'string') + t.ok('nodes' in rootNode) + t.ok(Array.isArray(rootNode.nodes)) + t.ok('start' in rootNode) + t.ok(Number.isInteger(rootNode.start)) + t.ok('stop' in rootNode) + t.type(rootNode.stop, 'null') + t.ok('diff' in rootNode) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start is adding a node with correct shape, child-node', t => { + t.plan(16) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + const rootNode = tree.root + + t.equal(rootNode.nodes.length, 1) + + const childNode = rootNode.nodes[0] + + t.equal(Object.keys(childNode).length, 7) + t.ok('parent' in childNode) + t.type(childNode.parent, 'string') + t.ok('id' in childNode) + t.type(childNode.id, 'string') + t.ok('label' in childNode) + t.type(childNode.label, 'string') + t.ok('nodes' in childNode) + t.ok(Array.isArray(childNode.nodes)) + t.ok('start' in childNode) + t.ok(Number.isInteger(childNode.start)) + t.ok('stop' in childNode) + t.type(childNode.stop, 'null') + t.ok('diff' in childNode) + t.type(childNode.diff, 'number') +}) + +test('TimeTree#start is adding a root element when parent is null', t => { + t.plan(9) + + const tree = new TimeTree() + tree.start(null, 'root') + + const rootNode = tree.root + + t.type(rootNode, 'object') + t.equal(Object.keys(rootNode).length, 7) + t.equal(rootNode.parent, null) + t.equal(rootNode.id, 'root') + t.equal(rootNode.label, 'root') + t.ok(Array.isArray(rootNode.nodes)) + t.equal(rootNode.nodes.length, 0) + t.ok(Number.isInteger(rootNode.start)) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start is adding a root element when parent does not exist', t => { + t.plan(9) + + const tree = new TimeTree() + tree.start('invalid', 'root') + + const rootNode = tree.root + + t.type(rootNode, 'object') + t.equal(Object.keys(rootNode).length, 7) + t.equal(rootNode.parent, null) + t.equal(rootNode.id, 'root') + t.equal(rootNode.label, 'root') + t.ok(Array.isArray(rootNode.nodes)) + t.equal(rootNode.nodes.length, 0) + t.ok(Number.isInteger(rootNode.start)) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start parameter start can override automatically generated start time', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root', 1337) + + t.ok(tree.root.start, 1337) +}) + +test('TimeTree#start returns id of root, when adding a root node /1', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.start(null, 'root'), 'root') +}) + +test('TimeTree#start returns id of root, when adding a root node /2', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.start(null, '/'), 'root') +}) + +test('TimeTree#start returns id of child, when adding a child node', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root') + t.match(tree.start('root', 'child'), /^child-[0-9.]+$/) +}) + +test('TimeTree tracks node ids /1', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree tracks node ids /2', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('child', 'grandchild') + + t.equal(tree.tableId.size, 3) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) + t.ok(tree.tableId.has(tree.root.nodes[0].nodes[0].id)) +}) + +test('TimeTree tracks node ids /3', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + t.equal(tree.tableId.size, 3) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) + t.ok(tree.tableId.has(tree.root.nodes[1].id)) +}) + +test('TimeTree tracks node labels /1', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + t.equal(tree.tableLabel.size, 3) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) + t.ok(tree.tableLabel.has('sibling')) +}) + +test('TimeTree tracks node labels /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) + +test('TimeTree#stop returns undefined', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root') + + t.type(tree.stop('root'), 'undefined') +}) + +test('TimeTree#stop sets stop value of node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('root') + t.type(tree.root.stop, 'number') + t.ok(Number.isInteger(tree.root.stop)) +}) + +test('TimeTree#stop parameter stop is used as stop value of node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('root', 1337) + t.type(tree.root.stop, 'number') + t.equal(tree.root.stop, 1337) +}) + +test('TimeTree#stop calculates the diff', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root', 1) + t.type(tree.root.diff, 'number') + t.equal(tree.root.diff, -1) + tree.stop('root', 5) + + t.type(tree.root.diff, 'number') + t.equal(tree.root.diff, 4) +}) + +test('TimeTree#stop does nothing when node is not found', t => { + t.plan(2) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('invalid') + t.type(tree.root.stop, 'null') +}) + +test('TimeTree untracks node ids /1', t => { + t.plan(2) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + t.equal(tree.tableId.size, 1) + t.ok(tree.tableId.has('root')) +}) + +test('TimeTree untracks node ids /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('child', 'grandchild') + + tree.stop(tree.root.nodes[0].nodes[0].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree untracks node ids /3', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[1].id)) +}) + +test('TimeTree untracks node ids /4', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[1].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree untracks node labels /1', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + tree.stop(tree.root.nodes[1].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) + +test('TimeTree untracks node labels /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('sibling')) +}) + +test('TimeTree does not untrack label if used by other node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a3aa956ec0be48cd294b0fa9f99ea906028be412 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js @@ -0,0 +1,19 @@ +'use strict' + +const { test } = require('tap') +const { validatePlugin } = require('../../lib/validate-plugin') +const { AVV_ERR_PLUGIN_NOT_VALID } = require('../../lib/errors') + +test('validatePlugin', (t) => { + t.plan(8) + + t.throws(() => validatePlugin(1), new AVV_ERR_PLUGIN_NOT_VALID('number')) + t.throws(() => validatePlugin('function'), new AVV_ERR_PLUGIN_NOT_VALID('string')) + t.throws(() => validatePlugin({}), new AVV_ERR_PLUGIN_NOT_VALID('object')) + t.throws(() => validatePlugin([]), new AVV_ERR_PLUGIN_NOT_VALID('array')) + t.throws(() => validatePlugin(null), new AVV_ERR_PLUGIN_NOT_VALID('null')) + + t.doesNotThrow(() => validatePlugin(function () {})) + t.doesNotThrow(() => validatePlugin(new Promise((resolve) => resolve))) + t.doesNotThrow(() => validatePlugin(Promise.resolve())) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/load-plugin.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/load-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e1400edf5da8e8becacecce95fcf678274404753 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/load-plugin.test.js @@ -0,0 +1,123 @@ +'use strict' + +const fastq = require('fastq') +const boot = require('..') +const { test } = require('tap') +const { Plugin } = require('../lib/plugin') + +test('successfully load a plugin with sync function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin with sync function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done(Error('ArbitraryError')) + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin with sync function without done as a parameter', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts) { }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('successfully load a plugin with async function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), async function (instance, opts) { }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin with async function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), async function (instance, opts) { + throw Error('ArbitraryError') + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin when function is a Promise, which resolves to a function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve(function (instance, opts, done) { + done() + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin when function is a Promise, which resolves to a function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve(function (instance, opts, done) { + done(Error('ArbitraryError')) + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin when function is a Promise, which resolves to a function, which is wrapped in default', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve({ + default: function (instance, opts, done) { + done() + } + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin when function is a Promise, which resolves to a function, which is wrapped in default', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve({ + default: function (instance, opts, done) { + done(Error('ArbitraryError')) + } + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/no-done.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/no-done.test.js new file mode 100644 index 0000000000000000000000000000000000000000..0270545d54e90906789d0150b42db6fc699af6c4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/no-done.test.js @@ -0,0 +1,18 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('not taking done does not throw error.', (t) => { + t.plan(2) + + const app = boot() + + app.use(noDone).ready((err) => { + t.notOk(err, 'no error') + }) + + function noDone (s, opts) { + t.pass('did not throw') + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9593935aa40a05d9f0b7d63820308e07e67975cf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js @@ -0,0 +1,33 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('../boot') + +test('onReadyTimeout', async (t) => { + const app = boot({}, { + timeout: 10, // 10 ms + autostart: false + }) + + app.use(function one (innerApp, opts, next) { + t.pass('loaded') + innerApp.ready(function readyNoResolve (err, done) { + t.notOk(err) + t.pass('first ready called') + // Do not call done() to timeout + }) + next() + }) + + await app.start() + + try { + await app.ready() + t.fail('should throw') + } catch (err) { + t.equal(err.message, 'Plugin did not start in time: \'readyNoResolve\'. You may have forgotten to call \'done\' function or to resolve a Promise') + // And not Plugin did not start in time: 'bound _encapsulateThreeParam'. You may have forgotten to call 'done' function or to resolve a Promise + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/override.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/override.test.js new file mode 100644 index 0000000000000000000000000000000000000000..674daaa7d0dc1e0afa137f73286d3f79f6020f7e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/override.test.js @@ -0,0 +1,374 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('..') + +test('custom inheritance', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s) { + t.equal(s, server) + + const res = Object.create(s) + res.b = 42 + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }) +}) + +test('custom inheritance multiple levels', (t) => { + t.plan(6) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) +}) + +test('custom inheritance multiple levels twice', (t) => { + t.plan(10) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + s1.use(third) + let prev + + cb() + + function second (s2, opts, cb) { + prev = s2 + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + + function third (s3, opts, cb) { + t.not(s3, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s3)) + t.notOk(Object.prototype.isPrototypeOf.call(prev, s3)) + t.equal(s3.count, 2) + cb() + } + }) +}) + +test('custom inheritance multiple levels with multiple heads', (t) => { + t.plan(13) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) + + app.use(function third (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(fourth) + + cb() + + function fourth (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) + + app.ready(function () { + t.equal(server.count, 0) + }) +}) + +test('fastify test case', (t) => { + t.plan(7) + + const noop = () => {} + + function build () { + const app = boot(server, {}) + app.override = function (s) { + return Object.create(s) + } + + server.add = function (name, fn, cb) { + if (this[name]) return cb(new Error('already existent')) + this[name] = fn + cb() + } + + return server + + function server (req, res) {} + } + + const instance = build() + t.ok(instance.add) + t.ok(instance.use) + + instance.use((i, opts, cb) => { + t.not(i, instance) + t.ok(Object.prototype.isPrototypeOf.call(instance, i)) + + i.add('test', noop, (err) => { + t.error(err) + t.ok(i.test) + cb() + }) + }) + + instance.ready(() => { + t.notOk(instance.test) + }) +}) + +test('override should pass also the plugin function', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn) { + t.type(fn, 'function') + t.equal(fn, first) + return s + } + + app.use(first) + + function first (s, opts, cb) { + t.equal(s, server) + cb() + } +}) + +test('skip override - fastify test case', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, func) { + if (func[Symbol.for('skip-override')]) { + return s + } + return Object.create(s) + } + + first[Symbol.for('skip-override')] = true + app.use(first) + + function first (s, opts, cb) { + t.equal(s, server) + t.notOk(Object.prototype.isPrototypeOf.call(server, s)) + cb() + } +}) + +test('override can receive options object', (t) => { + t.plan(4) + + const server = { my: 'server' } + const options = { hello: 'world' } + const app = boot(server) + + app.override = function (s, fn, opts) { + t.equal(s, server) + t.same(opts, options) + + const res = Object.create(s) + res.b = 42 + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }, options) +}) + +test('override can receive options function', (t) => { + t.plan(8) + + const server = { my: 'server' } + const options = { hello: 'world' } + const app = boot(server) + + app.override = function (s, fn, opts) { + t.equal(s, server) + if (typeof opts !== 'function') { + t.same(opts, options) + } + + const res = Object.create(s) + res.b = 42 + res.bar = 'world' + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + s.foo = 'bar' + cb() + }, options) + + app.use(function second (s, opts, cb) { + t.notOk(s.foo) + t.same(opts, { hello: 'world' }) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }, p => ({ hello: p.bar })) +}) + +test('after trigger override', t => { + t.plan(8) + + const server = { count: 0 } + const app = boot(server) + + let overrideCalls = 0 + app.override = function (s, fn, opts) { + overrideCalls++ + const res = Object.create(s) + res.count = res.count + 1 + return res + } + + app + .use(function first (s, opts, cb) { + t.equal(s.count, 1, 'should trigger override') + cb() + }) + .after(function () { + t.equal(overrideCalls, 1, 'after with 0 parameter should not trigger override') + }) + .after(function (err) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 1 parameter should not trigger override') + }) + .after(function (err, done) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 2 parameters should not trigger override') + done() + }) + .after(function (err, context, done) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 3 parameters should not trigger override') + done() + }) + .after(async function () { + t.equal(overrideCalls, 1, 'async after with 0 parameter should not trigger override') + }) + .after(async function (err) { + if (err) throw err + t.equal(overrideCalls, 1, 'async after with 1 parameter should not trigger override') + }) + .after(async function (err, context) { + if (err) throw err + t.equal(overrideCalls, 1, 'async after with 2 parameters should not trigger override') + }) +}) + +test('custom inheritance override in after', (t) => { + t.plan(6) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.after(() => { + s1.use(second) + }) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bdad133a4f59884292ab532dd105f8aac9615b01 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js @@ -0,0 +1,84 @@ +'use strict' + +const { test } = require('tap') +const fastq = require('fastq') +const boot = require('..') +const { Plugin } = require('../lib/plugin') + +test('loadedSoFar resolves a Promise, if plugin.loaded is set to true', async (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + plugin.loaded = true + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar resolves a Promise, if plugin was loaded by avvio', async (t) => { + t.plan(2) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) + + await app.ready() + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar resolves a Promise, if .after() has no error', async t => { + t.plan(1) + const app = boot() + + app.after = function (callback) { + callback(null, () => {}) + } + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function () {}) + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar rejects a Promise, if .after() has an error', async t => { + t.plan(1) + const app = boot() + + app.after = function (fn) { + fn(new Error('ArbitraryError'), () => {}) + } + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function () {}) + + await t.rejects(plugin.loadedSoFar(), new Error('ArbitraryError')) +}) + +test('loadedSoFar resolves a Promise, if Plugin is attached to avvio after it the Plugin was instantiated', async t => { + t.plan(1) + + const plugin = new Plugin(fastq(null, null, 1), function (instance, opts, done) { + done() + }, false, 0) + + const promise = plugin.loadedSoFar() + + plugin.server = boot() + plugin.emit('start') + await t.resolves(promise) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-name.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-name.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fa129a51c574ed05e1ac4e718790466af64f9f81 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-name.test.js @@ -0,0 +1,69 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { kPluginMeta } = require('../lib/symbols') + +test('plugins get a name from the plugin metadata if it is set', async (t) => { + t.plan(1) + const app = boot() + + const func = (app, opts, next) => next() + func[kPluginMeta] = { name: 'a-test-plugin' } + app.use(func) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'a-test-plugin' } + ] + }) +}) + +test('plugins get a name from the options if theres no metadata', async (t) => { + t.plan(1) + const app = boot() + + function testPlugin (app, opts, next) { next() } + app.use(testPlugin, { name: 'test registration options name' }) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'test registration options name' } + ] + }) +}) + +test('plugins get a name from the function name if theres no name in the options and no metadata', async (t) => { + t.plan(1) + const app = boot() + + function testPlugin (app, opts, next) { next() } + app.use(testPlugin) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'testPlugin' } + ] + }) +}) + +test('plugins get a name from the function source if theres no other option', async (t) => { + t.plan(1) + const app = boot() + + app.use((app, opts, next) => next()) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: '(app, opts, next) => next()' } + ] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..13ecdd8f5968c2ffb15aa6cede9b1b62f17eb4ba --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js @@ -0,0 +1,33 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('..') + +test('do not load', async (t) => { + const app = boot({}, { timeout: 10 }) + + app.use(first) + + async function first (s, opts) { + await s.use(second) + } + + async function second (s, opts) { + await s.use(third) + } + + function third (s, opts) { + return new Promise((resolve, reject) => { + // no resolve + }) + } + + try { + await app.start() + t.fail('should throw') + } catch (err) { + t.equal(err.message, 'Plugin did not start in time: \'third\'. You may have forgotten to call \'done\' function or to resolve a Promise') + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js new file mode 100644 index 0000000000000000000000000000000000000000..22b97ca05cd85376da6cc3c90a3c52e0b08addf7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js @@ -0,0 +1,218 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +const message = (name) => `Plugin did not start in time: '${name}'. You may have forgotten to call 'done' function or to resolve a Promise` + +test('timeout without calling next - callbacks', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(one) + function one (app, opts, next) { + // do not call next on purpose + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, one) + t.equal(err.message, message('one')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - promises', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(two) + function two (app, opts) { + return new Promise(function (resolve) { + // do not call resolve on purpose + }) + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, two) + t.equal(err.message, message('two')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - use file as name', (t) => { + t.plan(3) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(require('./fixtures/plugin-no-next')) + app.ready((err) => { + t.ok(err) + t.equal(err.message, message('noNext')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - use code as name', (t) => { + t.plan(3) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(function (app, opts, next) { + // do not call next on purpose - code as name + }) + + app.ready((err) => { + t.ok(err) + t.equal(err.message, message('function (app, opts, next) { -- // do not call next on purpose - code as name')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('does not keep going', (t) => { + t.plan(2) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(function three (app, opts, next) { + next(new Error('kaboom')) + }) + app.ready((err) => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) +}) + +test('throw in override without autostart', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server, { + timeout: 10, + autostart: false + }) + + app.override = function (s) { + throw new Error('kaboom') + } + + app.use(function (s, opts, cb) { + t.fail('this is never reached') + }) + + setTimeout(function () { + app.ready((err) => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) + }, 20) +}) + +test('timeout without calling next in ready and ignoring the error', (t) => { + t.plan(11) + const app = boot({}, { + timeout: 10, // 10 ms + autostart: false + }) + + let preReady = false + + app.use(function one (app, opts, next) { + t.pass('loaded') + app.ready(function readyOk (err, done) { + t.notOk(err) + t.pass('first ready called') + done() + }) + next() + }) + + app.on('preReady', () => { + t.pass('preReady should be called') + preReady = true + }) + + app.on('start', () => { + t.pass('start should be called') + }) + + app.ready(function onReadyWithoutDone (err, done) { + t.pass('wrong ready called') + t.ok(preReady, 'preReady already called') + t.notOk(err) + // done() // Don't call done + }) + + app.ready(function onReadyTwo (err) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + // don't rethrow the error + }) + + app.start() +}) + +test('timeout without calling next in ready and rethrowing the error', (t) => { + t.plan(11) + const app = boot({}, { + timeout: 10, // 10 ms + autostart: true + }) + + app.use(function one (app, opts, next) { + t.pass('loaded') + app.ready(function readyOk (err, done) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + done(err) + }) + next() + }) + + app.on('preReady', () => { + t.pass('preReady should be called') + }) + + app.on('start', () => { + t.pass('start should be called in any case') + }) + + app.ready(function onReadyWithoutDone (err, done) { + t.pass('wrong ready called') + t.notOk(err) + // done() // Don't call done + }) + + app.ready(function onReadyTwo (err, done) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + done(err) + }) + + app.start() +}) + +test('nested timeout do not crash - await', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(one) + async function one (app, opts) { + await app.use(two) + } + + function two (app, opts, next) { + // do not call next on purpose + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, two) + t.equal(err.message, message('two')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/pretty-print.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/pretty-print.test.js new file mode 100644 index 0000000000000000000000000000000000000000..734ab0806e8b783ea1d4525179697a1fa8d49680 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/pretty-print.test.js @@ -0,0 +1,75 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('pretty print', t => { + t.plan(19) + + const app = boot() + app + .use(first) + .use(duplicate, { count: 3 }) + .use(second).after(afterUse).after(after) + .use(duplicate, { count: 2 }) + .use(third).after(after) + .use(duplicate, { count: 1 }) + + const linesExpected = [/^root \d+ ms$/, + /^├── first \d+ ms$/, + /^├─┬ duplicate \d+ ms$/, + /^│ └─┬ duplicate \d+ ms$/, + /^│ {3}└─┬ duplicate \d+ ms$/, + /^│ {5}└── duplicate \d+ ms$/, + /^├── second \d+ ms$/, + /^├─┬ bound _after \d+ ms$/, + /^│ └── afterInsider \d+ ms$/, + /^├── bound _after \d+ ms$/, + /^├─┬ duplicate \d+ ms$/, + /^│ └─┬ duplicate \d+ ms$/, + /^│ {3}└── duplicate \d+ ms$/, + /^├── third \d+ ms$/, + /^├── bound _after \d+ ms$/, + /^└─┬ duplicate \d+ ms$/, + /^ {2}└── duplicate \d+ ms$/, + '' + ] + + app.on('preReady', function show () { + const print = app.prettyPrint() + const lines = print.split('\n') + + t.equal(lines.length, linesExpected.length) + lines.forEach((l, i) => { + t.match(l, linesExpected[i]) + }) + }) + + function first (s, opts, done) { + done() + } + function second (s, opts, done) { + done() + } + function third (s, opts, done) { + done() + } + function after (err, cb) { + cb(err) + } + function afterUse (err, cb) { + app.use(afterInsider) + cb(err) + } + + function afterInsider (s, opts, done) { + done() + } + + function duplicate (instance, opts, cb) { + if (opts.count > 0) { + instance.use(duplicate, { count: opts.count - 1 }) + } + setTimeout(cb, 20) + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/reentrant.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/reentrant.test.js new file mode 100644 index 0000000000000000000000000000000000000000..184be9c41c6738aac37a2d865b4b9a5f8f241981 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/reentrant.test.js @@ -0,0 +1,124 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('one level', (t) => { + t.plan(13) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + app.use(third) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') + }) +}) + +test('multiple reentrant plugin loading', (t) => { + t.plan(31) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + let fifthLoaded = false + + app.use(first) + app.use(fifth) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + secondLoaded = true + s.use(third) + s.use(fourth) + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + thirdLoaded = true + done() + } + + function fourth (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fourthLoaded = true + done() + } + + function fifth (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fifthLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.ok(fifthLoaded, 'fifth is loaded') + t.pass('booted') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/to-json.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/to-json.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d37725acde10d401be53802f70fb587dcfa558a2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/to-json.test.js @@ -0,0 +1,151 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('to json', (t) => { + t.plan(4) + + const app = boot() + app + .use(one) + .use(two) + .use(three) + + const outJson = { + id: 'root', + label: 'root', + start: /\d+/, + nodes: [] + } + + app.on('preReady', function show () { + const json = app.toJSON() + outJson.stop = /\d*/ + outJson.diff = /\d*/ + t.match(json, outJson) + }) + + function one (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'one', + start: /\d+/ + }) + t.match(json, outJson) + done() + } + function two (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'two', + start: /\d+/ + }) + t.match(json, outJson) + done() + } + function three (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'three', + start: /\d+/ + }) + t.match(json, outJson) + done() + } +}) + +test('to json multi-level hierarchy', (t) => { + t.plan(4) + + const server = { name: 'asd', count: 0 } + const app = boot(server) + + const outJson = { + id: 'root', + label: 'root', + start: /\d+/, + nodes: [ + { + id: /.+/, + parent: 'root', + start: /\d+/, + label: 'first', + nodes: [ + { + id: /.+/, + parent: 'first', + start: /\d+/, + label: 'second', + nodes: [], + stop: /\d+/, + diff: /\d+/ + }, + { + id: /.+/, + parent: 'first', + start: /\d+/, + label: 'third', + nodes: [ + { + id: /.+/, + parent: 'third', + start: /\d+/, + label: 'fourth', + nodes: [], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + + app.on('preReady', function show () { + const json = app.toJSON() + t.match(json, outJson) + }) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + res.name = 'qwe' + return res + } + + app.use(function first (s1, opts, cb) { + s1.use(second) + s1.use(third) + cb() + + function second (s2, opts, cb) { + t.equal(s2.count, 2) + cb() + } + + function third (s3, opts, cb) { + s3.use(fourth) + t.equal(s3.count, 2) + cb() + } + + function fourth (s4, opts, cb) { + t.equal(s4.count, 3) + cb() + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/twice-done.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/twice-done.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ecff9c55de53eb64a4ed6f5fbb0e9f053997fc4e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/twice-done.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('calling done twice does not throw error', (t) => { + t.plan(2) + + const app = boot() + + app + .use(twiceDone) + .ready((err) => { + t.notOk(err, 'no error') + }) + + function twiceDone (s, opts, done) { + done() + done() + t.pass('did not throw') + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/index.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..43497d0cad59dce1c495ec7ca382f37ab5feeb05 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/index.ts @@ -0,0 +1,411 @@ +import * as avvio from "../../"; + +{ + // avvio with no argument + const app = avvio(); + + app.override = (server, fn, options) => server; + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.use(async (server, options) => {}, + (server) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); +} + +{ + // avvio with done + const app = avvio(() => undefined); + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.use(async (server, options) => {}, + (server) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); +} + +{ + const server = { typescriptIs: "amazing" }; + // avvio with server + const app = avvio(server); + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + }); + + app.use(async (server, options) => {}, + ((server) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + })); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.typescriptIs; + + done(); + } + ); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.typescriptIs; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + } + ); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + } + ); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + }); +} + +{ + const server = { hello: "world" }; + const options = { + autostart: false, + expose: { after: "after", ready: "ready", use: "use", close: "close", onClose : "onClose" }, + timeout: 50000 + }; + // avvio with server and options + const app = avvio(server, options); +} + +{ + const server = { hello: "world" }; + const options = { + autostart: false, + expose: { after: "after", ready: "ready", use: "use" } + }; + // avvio with server, options and done callback + const app = avvio(server, options, () => undefined); +} + +{ + const app = avvio(); + const plugin: avvio.Plugin = async (): Promise => {}; + const promise = plugin(app, {}, undefined as any); + (promise instanceof Promise); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/tsconfig.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b170f36f4e994b3462921781ed1ba86fd14ed658 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/avvio/test/types/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": ["./index.ts"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/bignumber.js/doc/API.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000000000000000000000000000000000000..a16c034bee22d52331fa0a9c137d7c98c756664c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2249 @@ + + + + + + +bignumber.js API + + + + + + +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+

+ Note that the BigNnumber constructor accepts an n of type number purely + as a convenience so that string quotes don't have to be typed when entering literal values, + and that it is the toString value of n that is used rather than its + underlying binary floating point value converted to decimal. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal or exponential notation. + Values in other bases must be in normal notation. Values in any base can have fraction digits, + i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff' or '0xFF' + (but not '0xfF'), are valid, as are string values with the octal and binary + prefixs '0o' and '0b'. String values in octal literal form without + the prefix will be interpreted as decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number and has more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+

+ A BigNumber can also be created from an object literal. + Use isBigNumber to check that it is well-formed. +

+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true })    // '777.123'
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power operations + with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using Node.js. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
+// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+
+global.crypto = crypto;
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+  FORMAT: {
+    // string to prepend
+    prefix: '',
+    // decimal separator
+    decimalSeparator: '.',
+    // grouping separator of the integer part
+    groupSeparator: ',',
+    // primary grouping size of the integer part
+    groupSize: 3,
+    // secondary grouping size of the integer part
+    secondaryGroupSize: 0,
+    // grouping separator of the fraction part
+    fractionGroupSeparator: ' ',
+    // grouping size of the fraction part
+    fractionGroupSize: 0,
+    // string to append
+    suffix: ''
+  }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain whitespace or a repeated character, or the sign indicators + '+' and '-', or the decimal separator '.'. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+  DECIMAL_PLACES: 40,
+  ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+  EXPONENTIAL_AT: [-10, 20],
+  RANGE: [-500, 500],
+  CRYPTO: true,
+  MODULO_MODE: BigNumber.ROUND_FLOOR,
+  POW_PRECISION: 80,
+  FORMAT: {
+    groupSize: 3,
+    groupSeparator: ' ',
+    decimalSeparator: ','
+  },
+  ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+

+ If value is a BigNumber instance and BigNumber.DEBUG is true, + then this method will also check if value is well-formed, and throw if it is not. + See Errors. +

+

+ The check can be useful if creating a BigNumber from an object literal. + See BigNumber. +

+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x)    // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x)    // '[BigNumber Error] Invalid BigNumber'
+ + + +
maximum.max(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr)                // '14'
+ + + +
minimum.min(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr)                // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ To be able to set CRYPTO to true when using + Node.js, the crypto object must be available globally: +

+
// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+global.crypto = crypto;
+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +
sum.sum(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the sum of the arguments.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9')      // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr)            // '43.9999'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ +
DEBUG
+

undefined|false|true

+

+ If BigNumber.DEBUG is set true then an error will be thrown + if this BigNumber constructor receives an invalid value, such as + a value of type number with more than 15 significant digits. + See BigNumber. +

+

+ An error will also be thrown if the isBigNumber + method receives a BigNumber that is not well-formed. + See isBigNumber. +

+
BigNumber.DEBUG = true
+ + +

INSTANCE

+ + +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function () {
+  return this.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1.1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN. +

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the format object. +

+

+ See FORMAT and the examples below for the properties of the + format object, their types, and their usage. A formatting object may contain + some or all of the recognised properties. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the + FORMAT object is used. +

+

+ Throws if dp, rm or format is invalid. See + Errors. +

+
+fmt = {
+  prefix: '',
+  decimalSeparator: '.',
+  groupSeparator: ',',
+  groupSize: 3,
+  secondaryGroupSize: 0,
+  fractionGroupSeparator: ' ',
+  fractionGroupSize: 0,
+  suffix: ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat()                              // '123,456,789.123456789'
+x.toFormat(3)                             // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat()                              // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+  prefix: '=> ',
+  decimalSeparator: ',',
+  groupSeparator: '.',
+  groupSize: 3,
+  secondaryGroupSize: 2
+}
+
+x.toFormat()                              // '123 456 789.12345 6789'
+x.toFormat(fmt)                           // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt)                        // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt)    // '=> 12.34.56.789,124'
+ + + +
+ toFraction.toFraction([maximum_denominator]) + ⇒ [BigNumber, BigNumber] +
+

+ maximum_denominator: + number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns an array of two BigNumbers representing the value of this BigNumber as a simple + fraction with an integer numerator and an integer denominator. The denominator will be a + positive non-zero value less than or equal to maximum_denominator. +

+

+ If a maximum_denominator is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if maximum_denominator is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes + the minus sign for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
isBigNumberInvalid BigNumber*
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
+ toFormat + Argument not an object
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+  // ...
+} catch (e) {
+  if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+      // ...
+  }
+}
+ + + +

Type coercion

+

+ To prevent the accidental use of a BigNumber in primitive number operations, or the + accidental addition of a BigNumber to a string, the valueOf method can be safely + overwritten as shown below. +

+

+ The valueOf method is the same as the + toJSON method, and both are the same as the + toString method except they do not take a base + argument and they include the minus sign for negative zero. +

+
+BigNumber.prototype.valueOf = function () {
+  throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2                    // '[BigNumber Error] valueOf called!'
+x + 'abc'                // '[BigNumber Error] valueOf called!'
+
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/compile.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..dce69beb90ece5c3b0ca234a949418f9f34eedbc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/compile.js @@ -0,0 +1,60 @@ +'use strict'; + +const fill = require('fill-range'); +const utils = require('./utils'); + +const compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } + + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (const child of node.nodes) { + output += walk(child, node); + } + } + + return output; + }; + + return walk(ast); +}; + +module.exports = compile; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/constants.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..2bb3b8840382c56700869b3a9e1f958fcce01efd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/constants.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = { + MAX_LENGTH: 10000, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/expand.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/expand.js new file mode 100644 index 0000000000000000000000000000000000000000..35b2c41d6afdb8f0197959e26079f266e48370d3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/expand.js @@ -0,0 +1,113 @@ +'use strict'; + +const fill = require('fill-range'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +const append = (queue = '', stash = '', enclose = false) => { + const result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (const item of queue) { + if (Array.isArray(item)) { + for (const value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; + + const walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + const enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + const child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +module.exports = expand; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/parse.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..3a6988e629f52aee6609dc5ec290a5e9ff47cecb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/parse.js @@ -0,0 +1,331 @@ +'use strict'; + +const stringify = require('./stringify'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = require('./constants'); + +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + const type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/stringify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcf872c31894f81a8c64d9202fd607e4fd7ea2b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/stringify.js @@ -0,0 +1,32 @@ +'use strict'; + +const utils = require('./utils'); + +module.exports = (ast, options = {}) => { + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (const child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/utils.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..d19311fe044ad5157624077670dc297e8b53da49 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/braces/lib/utils.js @@ -0,0 +1,122 @@ +'use strict'; + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + const node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } + } + return result; + }; + + flat(args); + return result; +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..784b0dbd6ad7ed7a64b1ba1e132e44ea1b31ab84 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.d.ts @@ -0,0 +1,114 @@ +/** + * Parse options. + */ +export interface ParseOptions { + /** + * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). + * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode + * a previously-encoded cookie value into a JavaScript string. + * + * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error + * is thrown it will return the cookie's original value. If you provide your own encode/decode + * scheme you must ensure errors are appropriately handled. + * + * @default decode + */ + decode?: (str: string) => string | undefined; +} +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + */ +export declare function parse(str: string, options?: ParseOptions): Record; +/** + * Serialize options. + */ +export interface SerializeOptions { + /** + * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1). + * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode + * a value into a string suited for a cookie's value, and should mirror `decode` when parsing. + * + * @default encodeURIComponent + */ + encode?: (str: string) => string; + /** + * Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2). + * + * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and + * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, + * so if both are set, they should point to the same date and time. + */ + maxAge?: number; + /** + * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1). + * When no expiration is set clients consider this a "non-persistent cookie" and delete it the current session is over. + * + * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and + * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, + * so if both are set, they should point to the same date and time. + */ + expires?: Date; + /** + * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3). + * When no domain is set clients consider the cookie to apply to the current domain only. + */ + domain?: string; + /** + * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4). + * When no path is set, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4). + */ + path?: string; + /** + * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6). + * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`. + */ + httpOnly?: boolean; + /** + * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5). + * When enabled, clients will only send the cookie back if the browser has a HTTPS connection. + */ + secure?: boolean; + /** + * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/). + * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches. + * + * This is an attribute that has not yet been fully standardized, and may change in the future. + * This also means clients may ignore this attribute until they understand it. More information + * about can be found in [the proposal](https://github.com/privacycg/CHIPS). + */ + partitioned?: boolean; + /** + * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + * + * - `'low'` will set the `Priority` attribute to `Low`. + * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + * - `'high'` will set the `Priority` attribute to `High`. + * + * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1). + */ + priority?: "low" | "medium" | "high"; + /** + * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + * + * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + * + * More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7). + */ + sameSite?: boolean | "lax" | "strict" | "none"; +} +/** + * Serialize data into a cookie header. + * + * Serialize a name value pair into a cookie string suitable for + * http headers. An optional options object specifies cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + */ +export declare function serialize(name: string, val: string, options?: SerializeOptions): string; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..423acb4e7ad146bdc44b7c27205f90136ad1f5fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/cookie/dist/index.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parse = parse; +exports.serialize = serialize; +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + * + * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191 + * Allow same range as cookie value, except `=`, which delimits end of name. + */ +const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/; +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + * + * Allowing more characters: https://github.com/jshttp/cookie/issues/191 + * Comma, backslash, and DQUOTE are not part of the parsing algorithm. + */ +const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/; +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =