Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1import type * as checks from "./checks.js";2import { globalConfig } from "./core.js";3import type { $ZodConfig } from "./core.js";4import type * as errors from "./errors.js";5import type * as schemas from "./schemas.js";6 7// json8export type JSONType = string | number | boolean | null | JSONType[] | { [key: string]: JSONType };9export type JWTAlgorithm =10 | "HS256"11 | "HS384"12 | "HS512"13 | "RS256"14 | "RS384"15 | "RS512"16 | "ES256"17 | "ES384"18 | "ES512"19 | "PS256"20 | "PS384"21 | "PS512"22 | "EdDSA"23 | (string & {});24 25export type HashAlgorithm = "md5" | "sha1" | "sha256" | "sha384" | "sha512";26export type HashEncoding = "hex" | "base64" | "base64url";27export type HashFormat = `${HashAlgorithm}_${HashEncoding}`;28export type IPVersion = "v4" | "v6";29export type MimeTypes =30 | "application/json"31 | "application/xml"32 | "application/x-www-form-urlencoded"33 | "application/javascript"34 | "application/pdf"35 | "application/zip"36 | "application/vnd.ms-excel"37 | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"38 | "application/msword"39 | "application/vnd.openxmlformats-officedocument.wordprocessingml.document"40 | "application/vnd.ms-powerpoint"41 | "application/vnd.openxmlformats-officedocument.presentationml.presentation"42 | "application/octet-stream"43 | "application/graphql"44 | "text/html"45 | "text/plain"46 | "text/css"47 | "text/javascript"48 | "text/csv"49 | "image/png"50 | "image/jpeg"51 | "image/gif"52 | "image/svg+xml"53 | "image/webp"54 | "audio/mpeg"55 | "audio/ogg"56 | "audio/wav"57 | "audio/webm"58 | "video/mp4"59 | "video/webm"60 | "video/ogg"61 | "font/woff"62 | "font/woff2"63 | "font/ttf"64 | "font/otf"65 | "multipart/form-data"66 | (string & {});67export type ParsedTypes =68 | "string"69 | "number"70 | "bigint"71 | "boolean"72 | "symbol"73 | "undefined"74 | "object"75 | "function"76 | "file"77 | "date"78 | "array"79 | "map"80 | "set"81 | "nan"82 | "null"83 | "promise";84 85// utils86export type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : false;87export type AssertNotEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? false : true;88export type AssertExtends<T, U> = T extends U ? T : never;89export type IsAny<T> = 0 extends 1 & T ? true : false;90export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;91export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;92export type MakePartial<T, K extends keyof T> = Omit<T, K> & InexactPartial<Pick<T, K>>;93export type MakeRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;94 95export type Exactly<T, X> = T & Record<Exclude<keyof X, keyof T>, never>;96export type NoUndefined<T> = T extends undefined ? never : T;97export type Whatever = {} | undefined | null;98export type LoosePartial<T extends object> = InexactPartial<T> & {99 [k: string]: unknown;100};101export type Mask<Keys extends PropertyKey> = { [K in Keys]?: true };102export type Writeable<T> = { -readonly [P in keyof T]: T[P] } & {};103export type InexactPartial<T> = {104 [P in keyof T]?: T[P] | undefined;105};106export type EmptyObject = Record<string, never>;107export type BuiltIn =108 | (((...args: any[]) => any) | (new (...args: any[]) => any))109 | { readonly [Symbol.toStringTag]: string }110 | Date111 | Error112 | Generator113 | Promise<unknown>114 | RegExp;115export type MakeReadonly<T> = T extends Map<infer K, infer V>116 ? ReadonlyMap<K, V>117 : T extends Set<infer V>118 ? ReadonlySet<V>119 : T extends [infer Head, ...infer Tail]120 ? readonly [Head, ...Tail]121 : T extends Array<infer V>122 ? ReadonlyArray<V>123 : T extends BuiltIn124 ? T125 : Readonly<T>;126export type SomeObject = Record<PropertyKey, any>;127export type Identity<T> = T;128export type Flatten<T> = Identity<{ [k in keyof T]: T[k] }>;129export type Mapped<T> = { [k in keyof T]: T[k] };130export type Prettify<T> = {131 // @ts-ignore132 [K in keyof T]: T[K];133} & {};134 135export type NoNeverKeys<T> = {136 [k in keyof T]: [T[k]] extends [never] ? never : k;137}[keyof T];138export type NoNever<T> = Identity<{139 [k in NoNeverKeys<T>]: k extends keyof T ? T[k] : never;140}>;141export type Extend<A extends SomeObject, B extends SomeObject> = Flatten<142 // fast path when there is no keys overlap143 keyof A & keyof B extends never144 ? A & B145 : {146 [K in keyof A as K extends keyof B ? never : K]: A[K];147 } & {148 [K in keyof B]: B[K];149 }150>;151 152export type TupleItems = ReadonlyArray<schemas.SomeType>;153export type AnyFunc = (...args: any[]) => any;154export type IsProp<T, K extends keyof T> = T[K] extends AnyFunc ? never : K;155export type MaybeAsync<T> = T | Promise<T>;156export type KeyOf<T> = keyof OmitIndexSignature<T>;157export type OmitIndexSignature<T> = {158 [K in keyof T as string extends K ? never : K extends string ? K : never]: T[K];159};160export type ExtractIndexSignature<T> = {161 [K in keyof T as string extends K ? K : K extends string ? never : K]: T[K];162};163export type Keys<T extends object> = keyof OmitIndexSignature<T>;164 165export type SchemaClass<T extends schemas.SomeType> = {166 new (def: T["_zod"]["def"]): T;167};168export type EnumValue = string | number; // | bigint | boolean | symbol;169export type EnumLike = Readonly<Record<string, EnumValue>>;170export type ToEnum<T extends EnumValue> = Flatten<{ [k in T]: k }>;171export type KeysEnum<T extends object> = ToEnum<Exclude<keyof T, symbol>>;172export type KeysArray<T extends object> = Flatten<(keyof T & string)[]>;173export type Literal = string | number | bigint | boolean | null | undefined;174export type LiteralArray = Array<Literal>;175export type Primitive = string | number | symbol | bigint | boolean | null | undefined;176export type PrimitiveArray = Array<Primitive>;177export type HasSize = { size: number };178export type HasLength = { length: number }; // string | Array<unknown> | Set<unknown> | File;179export type Numeric = number | bigint | Date;180export type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseError<T>;181export type SafeParseSuccess<T> = { success: true; data: T; error?: never };182export type SafeParseError<T> = {183 success: false;184 data?: never;185 error: errors.$ZodError<T>;186};187 188export type PropValues = Record<string, Set<Primitive>>;189export type PrimitiveSet = Set<Primitive>;190 191// functions192export function assertEqual<A, B>(val: AssertEqual<A, B>): AssertEqual<A, B> {193 return val;194}195 196export function assertNotEqual<A, B>(val: AssertNotEqual<A, B>): AssertNotEqual<A, B> {197 return val;198}199 200export function assertIs<T>(_arg: T): void {}201 202export function assertNever(_x: never): never {203 throw new Error("Unexpected value in exhaustive check");204}205export function assert<T>(_: any): asserts _ is T {}206 207export function getEnumValues(entries: EnumLike): EnumValue[] {208 const numericValues = Object.values(entries).filter((v) => typeof v === "number");209 const values = Object.entries(entries)210 .filter(([k, _]) => numericValues.indexOf(+k) === -1)211 .map(([_, v]) => v);212 return values;213}214 215export function joinValues<T extends Primitive[]>(array: T, separator = "|"): string {216 return array.map((val) => stringifyPrimitive(val)).join(separator);217}218 219export function jsonStringifyReplacer(_: string, value: any): any {220 if (typeof value === "bigint") return value.toString();221 return value;222}223 224export function cached<T>(getter: () => T): { value: T } {225 const set = false;226 return {227 get value() {228 if (!set) {229 const value = getter();230 Object.defineProperty(this, "value", { value });231 return value;232 }233 throw new Error("cached value already set");234 },235 };236}237 238export function nullish(input: any): boolean {239 return input === null || input === undefined;240}241 242export function cleanRegex(source: string): string {243 const start = source.startsWith("^") ? 1 : 0;244 const end = source.endsWith("$") ? source.length - 1 : source.length;245 return source.slice(start, end);246}247 248export function floatSafeRemainder(val: number, step: number): number {249 const ratio = val / step;250 const roundedRatio = Math.round(ratio);251 // Use a relative epsilon scaled to the magnitude of the result252 const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);253 if (Math.abs(ratio - roundedRatio) < tolerance) return 0;254 return ratio - roundedRatio;255}256 257const EVALUATING = /* @__PURE__*/ Symbol("evaluating");258 259export function defineLazy<T, K extends keyof T>(object: T, key: K, getter: () => T[K]): void {260 let value: T[K] | typeof EVALUATING | undefined = undefined;261 Object.defineProperty(object, key, {262 get() {263 if (value === EVALUATING) {264 // Circular reference detected, return undefined to break the cycle265 return undefined as T[K];266 }267 if (value === undefined) {268 value = EVALUATING;269 value = getter();270 }271 return value;272 },273 set(v) {274 Object.defineProperty(object, key, {275 value: v,276 // configurable: true,277 });278 // object[key] = v;279 },280 configurable: true,281 });282}283 284export function objectClone(obj: object) {285 return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));286}287 288export function assignProp<T extends object, K extends PropertyKey>(289 target: T,290 prop: K,291 value: K extends keyof T ? T[K] : any292): void {293 Object.defineProperty(target, prop, {294 value,295 writable: true,296 enumerable: true,297 configurable: true,298 });299}300 301export function mergeDefs(...defs: Record<string, any>[]): any {302 const mergedDescriptors: Record<string, PropertyDescriptor> = {};303 304 for (const def of defs) {305 const descriptors = Object.getOwnPropertyDescriptors(def);306 Object.assign(mergedDescriptors, descriptors);307 }308 309 return Object.defineProperties({}, mergedDescriptors);310}311 312export function cloneDef(schema: schemas.$ZodType): any {313 return mergeDefs(schema._zod.def);314}315 316export function getElementAtPath(obj: any, path: (string | number)[] | null | undefined): any {317 if (!path) return obj;318 return path.reduce((acc, key) => acc?.[key], obj);319}320 321export function promiseAllObject<T extends object>(promisesObj: T): Promise<{ [k in keyof T]: Awaited<T[k]> }> {322 const keys = Object.keys(promisesObj);323 const promises = keys.map((key) => (promisesObj as any)[key]);324 325 return Promise.all(promises).then((results) => {326 const resolvedObj: any = {};327 for (let i = 0; i < keys.length; i++) {328 resolvedObj[keys[i]!] = results[i];329 }330 return resolvedObj;331 });332}333 334export function randomString(length = 10): string {335 const chars = "abcdefghijklmnopqrstuvwxyz";336 let str = "";337 for (let i = 0; i < length; i++) {338 str += chars[Math.floor(Math.random() * chars.length)];339 }340 return str;341}342 343export function esc(str: string): string {344 return JSON.stringify(str);345}346 347export function slugify(input: string): string {348 return input349 .toLowerCase()350 .trim()351 .replace(/[^\w\s-]/g, "")352 .replace(/[\s_-]+/g, "-")353 .replace(/^-+|-+$/g, "");354}355 356export const captureStackTrace: (targetObject: object, constructorOpt?: Function) => void = (357 "captureStackTrace" in Error ? Error.captureStackTrace : (..._args: any[]) => {}358) as any;359 360export function isObject(data: any): data is Record<PropertyKey, unknown> {361 return typeof data === "object" && data !== null && !Array.isArray(data);362}363 364export const allowsEval: { value: boolean } = /* @__PURE__*/ cached(() => {365 // Skip the probe under `jitless`: strict CSPs report the caught `new Function`366 // as a `securitypolicyviolation` even though the throw is swallowed.367 if (globalConfig.jitless) {368 return false;369 }370 371 // @ts-ignore372 if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {373 return false;374 }375 376 try {377 const F = Function;378 new F("");379 return true;380 } catch (_) {381 return false;382 }383});384 385export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {386 if (isObject(o) === false) return false;387 388 // modified constructor389 const ctor = o.constructor;390 if (ctor === undefined) return true;391 392 if (typeof ctor !== "function") return true;393 394 // modified prototype395 const prot = ctor.prototype;396 if (isObject(prot) === false) return false;397 398 // ctor doesn't have static `isPrototypeOf`399 if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {400 return false;401 }402 403 return true;404}405 406export function shallowClone(o: any): any {407 if (isPlainObject(o)) return { ...o };408 if (Array.isArray(o)) return [...o];409 if (o instanceof Map) return new Map(o);410 if (o instanceof Set) return new Set(o);411 return o;412}413 414export function numKeys(data: any): number {415 let keyCount = 0;416 for (const key in data) {417 if (Object.prototype.hasOwnProperty.call(data, key)) {418 keyCount++;419 }420 }421 return keyCount;422}423 424export const getParsedType = (data: any): ParsedTypes => {425 const t = typeof data;426 427 switch (t) {428 case "undefined":429 return "undefined";430 431 case "string":432 return "string";433 434 case "number":435 return Number.isNaN(data) ? "nan" : "number";436 437 case "boolean":438 return "boolean";439 440 case "function":441 return "function";442 443 case "bigint":444 return "bigint";445 446 case "symbol":447 return "symbol";448 449 case "object":450 if (Array.isArray(data)) {451 return "array";452 }453 if (data === null) {454 return "null";455 }456 if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {457 return "promise";458 }459 if (typeof Map !== "undefined" && data instanceof Map) {460 return "map";461 }462 if (typeof Set !== "undefined" && data instanceof Set) {463 return "set";464 }465 if (typeof Date !== "undefined" && data instanceof Date) {466 return "date";467 }468 // @ts-ignore469 if (typeof File !== "undefined" && data instanceof File) {470 return "file";471 }472 return "object";473 474 default:475 throw new Error(`Unknown data type: ${t}`);476 }477};478 479export const propertyKeyTypes: Set<string> = /* @__PURE__*/ new Set(["string", "number", "symbol"]);480export const primitiveTypes: Set<string> = /* @__PURE__*/ new Set([481 "string",482 "number",483 "bigint",484 "boolean",485 "symbol",486 "undefined",487]);488export function escapeRegex(str: string): string {489 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");490}491 492// zod-specific utils493export function clone<T extends schemas.$ZodType>(inst: T, def?: T["_zod"]["def"], params?: { parent: boolean }): T {494 const cl = new inst._zod.constr(def ?? inst._zod.def);495 if (!def || params?.parent) cl._zod.parent = inst;496 return cl as any;497}498 499export type EmptyToNever<T> = keyof T extends never ? never : T;500 501export type Normalize<T> = T extends undefined502 ? never503 : T extends Record<any, any>504 ? Flatten<505 {506 [k in keyof Omit<T, "error" | "message">]: T[k];507 } & ("error" extends keyof T508 ? {509 error?: Exclude<T["error"], string>;510 // path?: PropertyKey[] | undefined;511 // message?: string | undefined;512 }513 : unknown)514 >515 : never;516 517export function normalizeParams<T>(_params: T): Normalize<T> {518 const params: any = _params;519 520 if (!params) return {} as any;521 if (typeof params === "string") return { error: () => params } as any;522 if (params?.message !== undefined) {523 if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params");524 params.error = params.message;525 }526 delete params.message;527 if (typeof params.error === "string") return { ...params, error: () => params.error } as any;528 return params;529}530 531export function createTransparentProxy<T extends object>(getter: () => T): T {532 let target: T;533 return new Proxy(534 {},535 {536 get(_, prop, receiver) {537 target ??= getter();538 return Reflect.get(target, prop, receiver);539 },540 set(_, prop, value, receiver) {541 target ??= getter();542 return Reflect.set(target, prop, value, receiver);543 },544 has(_, prop) {545 target ??= getter();546 return Reflect.has(target, prop);547 },548 deleteProperty(_, prop) {549 target ??= getter();550 return Reflect.deleteProperty(target, prop);551 },552 ownKeys(_) {553 target ??= getter();554 return Reflect.ownKeys(target);555 },556 getOwnPropertyDescriptor(_, prop) {557 target ??= getter();558 return Reflect.getOwnPropertyDescriptor(target, prop);559 },560 defineProperty(_, prop, descriptor) {561 target ??= getter();562 return Reflect.defineProperty(target, prop, descriptor);563 },564 }565 ) as T;566}567 568export function stringifyPrimitive(value: any): string {569 if (typeof value === "bigint") return value.toString() + "n";570 if (typeof value === "string") return `"${value}"`;571 return `${value}`;572}573 574export function optionalKeys(shape: schemas.$ZodShape): string[] {575 return Object.keys(shape).filter((k) => {576 return shape[k]!._zod.optin === "optional" && shape[k]!._zod.optout === "optional";577 });578}579 580export type CleanKey<T extends PropertyKey> = T extends `?${infer K}` ? K : T extends `${infer K}?` ? K : T;581export type ToCleanMap<T extends schemas.$ZodLooseShape> = {582 [k in keyof T]: k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k;583};584export type FromCleanMap<T extends schemas.$ZodLooseShape> = {585 [k in keyof T as k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k]: k;586};587 588export const NUMBER_FORMAT_RANGES: Record<checks.$ZodNumberFormats, [number, number]> = {589 safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],590 int32: [-2147483648, 2147483647],591 uint32: [0, 4294967295],592 float32: [-3.4028234663852886e38, 3.4028234663852886e38],593 float64: [-Number.MAX_VALUE, Number.MAX_VALUE],594};595 596export const BIGINT_FORMAT_RANGES: Record<checks.$ZodBigIntFormats, [bigint, bigint]> = {597 int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],598 uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],599};600 601export function pick(schema: schemas.$ZodObject, mask: Record<string, unknown>): any {602 const currDef = schema._zod.def;603 604 const checks = currDef.checks;605 const hasChecks = checks && checks.length > 0;606 if (hasChecks) {607 throw new Error(".pick() cannot be used on object schemas containing refinements");608 }609 610 const def = mergeDefs(schema._zod.def, {611 get shape() {612 const newShape: Writeable<schemas.$ZodShape> = {};613 for (const key in mask) {614 if (!(key in currDef.shape)) {615 throw new Error(`Unrecognized key: "${key}"`);616 }617 if (!mask[key]) continue;618 newShape[key] = currDef.shape[key]!;619 }620 621 assignProp(this, "shape", newShape); // self-caching622 return newShape;623 },624 checks: [],625 });626 627 return clone(schema, def) as any;628}629 630export function omit(schema: schemas.$ZodObject, mask: object): any {631 const currDef = schema._zod.def;632 633 const checks = currDef.checks;634 const hasChecks = checks && checks.length > 0;635 if (hasChecks) {636 throw new Error(".omit() cannot be used on object schemas containing refinements");637 }638 639 const def = mergeDefs(schema._zod.def, {640 get shape() {641 const newShape: Writeable<schemas.$ZodShape> = { ...schema._zod.def.shape };642 for (const key in mask) {643 if (!(key in currDef.shape)) {644 throw new Error(`Unrecognized key: "${key}"`);645 }646 if (!(mask as any)[key]) continue;647 648 delete newShape[key];649 }650 assignProp(this, "shape", newShape); // self-caching651 return newShape;652 },653 checks: [],654 });655 656 return clone(schema, def);657}658 659export function extend(schema: schemas.$ZodObject, shape: schemas.$ZodShape): any {660 if (!isPlainObject(shape)) {661 throw new Error("Invalid input to extend: expected a plain object");662 }663 664 const checks = schema._zod.def.checks;665 const hasChecks = checks && checks.length > 0;666 if (hasChecks) {667 // Only throw if new shape overlaps with existing shape668 // Use getOwnPropertyDescriptor to check key existence without accessing values669 const existingShape = schema._zod.def.shape;670 for (const key in shape) {671 if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {672 throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");673 }674 }675 }676 677 const def = mergeDefs(schema._zod.def, {678 get shape() {679 const _shape = { ...schema._zod.def.shape, ...shape };680 assignProp(this, "shape", _shape); // self-caching681 return _shape;682 },683 });684 return clone(schema, def) as any;685}686 687export function safeExtend(schema: schemas.$ZodObject, shape: schemas.$ZodShape): any {688 if (!isPlainObject(shape)) {689 throw new Error("Invalid input to safeExtend: expected a plain object");690 }691 const def = mergeDefs(schema._zod.def, {692 get shape() {693 const _shape = { ...schema._zod.def.shape, ...shape };694 assignProp(this, "shape", _shape); // self-caching695 return _shape;696 },697 });698 return clone(schema, def) as any;699}700 701export function merge(a: schemas.$ZodObject, b: schemas.$ZodObject): any {702 if (a._zod.def.checks?.length) {703 throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");704 }705 const def = mergeDefs(a._zod.def, {706 get shape() {707 const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };708 assignProp(this, "shape", _shape); // self-caching709 return _shape;710 },711 get catchall() {712 return b._zod.def.catchall;713 },714 checks: b._zod.def.checks ?? [],715 });716 717 return clone(a, def) as any;718}719 720export function partial(721 Class: SchemaClass<schemas.$ZodOptional> | null,722 schema: schemas.$ZodObject,723 mask: object | undefined724): any {725 const currDef = schema._zod.def;726 const checks = currDef.checks;727 const hasChecks = checks && checks.length > 0;728 if (hasChecks) {729 throw new Error(".partial() cannot be used on object schemas containing refinements");730 }731 732 const def = mergeDefs(schema._zod.def, {733 get shape() {734 const oldShape = schema._zod.def.shape;735 const shape: Writeable<schemas.$ZodShape> = { ...oldShape };736 737 if (mask) {738 for (const key in mask) {739 if (!(key in oldShape)) {740 throw new Error(`Unrecognized key: "${key}"`);741 }742 if (!(mask as any)[key]) continue;743 // if (oldShape[key]!._zod.optin === "optional") continue;744 shape[key] = Class745 ? new Class({746 type: "optional",747 innerType: oldShape[key]!,748 })749 : oldShape[key]!;750 }751 } else {752 for (const key in oldShape) {753 // if (oldShape[key]!._zod.optin === "optional") continue;754 shape[key] = Class755 ? new Class({756 type: "optional",757 innerType: oldShape[key]!,758 })759 : oldShape[key]!;760 }761 }762 763 assignProp(this, "shape", shape); // self-caching764 return shape;765 },766 checks: [],767 });768 769 return clone(schema, def) as any;770}771 772export function required(773 Class: SchemaClass<schemas.$ZodNonOptional>,774 schema: schemas.$ZodObject,775 mask: object | undefined776): any {777 const def = mergeDefs(schema._zod.def, {778 get shape() {779 const oldShape = schema._zod.def.shape;780 const shape: Writeable<schemas.$ZodShape> = { ...oldShape };781 782 if (mask) {783 for (const key in mask) {784 if (!(key in shape)) {785 throw new Error(`Unrecognized key: "${key}"`);786 }787 if (!(mask as any)[key]) continue;788 // overwrite with non-optional789 shape[key] = new Class({790 type: "nonoptional",791 innerType: oldShape[key]!,792 });793 }794 } else {795 for (const key in oldShape) {796 // overwrite with non-optional797 shape[key] = new Class({798 type: "nonoptional",799 innerType: oldShape[key]!,800 });801 }802 }803 804 assignProp(this, "shape", shape); // self-caching805 return shape;806 },807 });808 809 return clone(schema, def) as any;810}811 812export type Constructor<T, Def extends any[] = any[]> = new (...args: Def) => T;813 814// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom815export function aborted(x: schemas.ParsePayload, startIndex = 0): boolean {816 if (x.aborted === true) return true;817 for (let i = startIndex; i < x.issues.length; i++) {818 if (x.issues[i]?.continue !== true) {819 return true;820 }821 }822 return false;823}824 825// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).826// Used to respect `abort: true` in .refine() even for checks that have a `when` function.827export function explicitlyAborted(x: schemas.ParsePayload, startIndex = 0): boolean {828 if (x.aborted === true) return true;829 for (let i = startIndex; i < x.issues.length; i++) {830 if (x.issues[i]?.continue === false) {831 return true;832 }833 }834 return false;835}836 837export function prefixIssues(path: PropertyKey, issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[] {838 return issues.map((iss) => {839 (iss as any).path ??= [];840 (iss as any).path.unshift(path);841 return iss;842 });843}844 845export function unwrapMessage(message: string | { message: string } | undefined | null): string | undefined {846 return typeof message === "string" ? message : message?.message;847}848 849export function finalizeIssue(850 iss: errors.$ZodRawIssue,851 ctx: schemas.ParseContextInternal | undefined,852 config: $ZodConfig853): errors.$ZodIssue {854 const message = iss.message855 ? iss.message856 : (unwrapMessage(iss.inst?._zod.def?.error?.(iss as never)) ??857 unwrapMessage(ctx?.error?.(iss as never)) ??858 unwrapMessage(config.customError?.(iss)) ??859 unwrapMessage(config.localeError?.(iss)) ??860 "Invalid input");861 862 const { inst: _inst, continue: _continue, input: _input, ...rest } = iss as any;863 rest.path ??= [];864 rest.message = message;865 if (ctx?.reportInput) {866 rest.input = _input;867 }868 return rest;869}870 871export function getSizableOrigin(input: any): "set" | "map" | "file" | "unknown" {872 if (input instanceof Set) return "set";873 if (input instanceof Map) return "map";874 // @ts-ignore875 if (input instanceof File) return "file";876 return "unknown";877}878 879export function getLengthableOrigin(input: any): "array" | "string" | "unknown" {880 if (Array.isArray(input)) return "array";881 if (typeof input === "string") return "string";882 return "unknown";883}884 885export function parsedType(data: unknown): errors.$ZodInvalidTypeExpected {886 const t = typeof data;887 switch (t) {888 case "number": {889 return Number.isNaN(data) ? "nan" : "number";890 }891 case "object": {892 if (data === null) {893 return "null";894 }895 if (Array.isArray(data)) {896 return "array";897 }898 899 const obj = data as object;900 if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {901 return (obj.constructor as { name: string }).name;902 }903 }904 }905 return t;906}907 908////////// REFINES //////////909export function issue(_iss: string, input: any, inst: any): errors.$ZodRawIssue;910export function issue(_iss: errors.$ZodRawIssue): errors.$ZodRawIssue;911export function issue(...args: [string | errors.$ZodRawIssue, any?, any?]): errors.$ZodRawIssue {912 const [iss, input, inst] = args;913 if (typeof iss === "string") {914 return {915 message: iss,916 code: "custom",917 input,918 inst,919 };920 }921 922 return { ...iss };923}924 925export function cleanEnum(obj: Record<string, EnumValue>): EnumValue[] {926 return Object.entries(obj)927 .filter(([k, _]) => {928 // return true if NaN, meaning it's not a number, thus a string key929 return Number.isNaN(Number.parseInt(k, 10));930 })931 .map((el) => el[1]);932}933 934// Codec utility functions935export function base64ToUint8Array(base64: string): InstanceType<typeof Uint8Array> {936 const binaryString = atob(base64);937 const bytes = new Uint8Array(binaryString.length);938 for (let i = 0; i < binaryString.length; i++) {939 bytes[i] = binaryString.charCodeAt(i);940 }941 return bytes;942}943 944export function uint8ArrayToBase64(bytes: Uint8Array): string {945 let binaryString = "";946 for (let i = 0; i < bytes.length; i++) {947 binaryString += String.fromCharCode(bytes[i]);948 }949 return btoa(binaryString);950}951 952export function base64urlToUint8Array(base64url: string): InstanceType<typeof Uint8Array> {953 const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");954 const padding = "=".repeat((4 - (base64.length % 4)) % 4);955 return base64ToUint8Array(base64 + padding);956}957 958export function uint8ArrayToBase64url(bytes: Uint8Array): string {959 return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");960}961 962export function hexToUint8Array(hex: string): InstanceType<typeof Uint8Array> {963 const cleanHex = hex.replace(/^0x/, "");964 if (cleanHex.length % 2 !== 0) {965 throw new Error("Invalid hex string length");966 }967 const bytes = new Uint8Array(cleanHex.length / 2);968 for (let i = 0; i < cleanHex.length; i += 2) {969 bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);970 }971 return bytes;972}973 974export function uint8ArrayToHex(bytes: Uint8Array): string {975 return Array.from(bytes)976 .map((b) => b.toString(16).padStart(2, "0"))977 .join("");978}979 980// instanceof981export abstract class Class {982 constructor(..._args: any[]) {}983}984 