@microfox/brave
Version:
TypeScript SDK for Brave APIs.
1 lines • 805 kB
Source Map (JSON)
{"version":3,"sources":["../src/BraveSdk.ts","../src/lib/headers.ts","../../../node_modules/zod/v4/classic/external.js","../../../node_modules/zod/v4/core/index.js","../../../node_modules/zod/v4/core/core.js","../../../node_modules/zod/v4/core/util.js","../../../node_modules/zod/v4/core/errors.js","../../../node_modules/zod/v4/core/parse.js","../../../node_modules/zod/v4/core/regexes.js","../../../node_modules/zod/v4/core/checks.js","../../../node_modules/zod/v4/core/doc.js","../../../node_modules/zod/v4/core/versions.js","../../../node_modules/zod/v4/core/schemas.js","../../../node_modules/zod/v4/locales/index.js","../../../node_modules/zod/v4/locales/ar.js","../../../node_modules/zod/v4/locales/az.js","../../../node_modules/zod/v4/locales/be.js","../../../node_modules/zod/v4/locales/ca.js","../../../node_modules/zod/v4/locales/cs.js","../../../node_modules/zod/v4/locales/da.js","../../../node_modules/zod/v4/locales/de.js","../../../node_modules/zod/v4/locales/en.js","../../../node_modules/zod/v4/locales/eo.js","../../../node_modules/zod/v4/locales/es.js","../../../node_modules/zod/v4/locales/fa.js","../../../node_modules/zod/v4/locales/fi.js","../../../node_modules/zod/v4/locales/fr.js","../../../node_modules/zod/v4/locales/fr-CA.js","../../../node_modules/zod/v4/locales/he.js","../../../node_modules/zod/v4/locales/hu.js","../../../node_modules/zod/v4/locales/id.js","../../../node_modules/zod/v4/locales/is.js","../../../node_modules/zod/v4/locales/it.js","../../../node_modules/zod/v4/locales/ja.js","../../../node_modules/zod/v4/locales/ka.js","../../../node_modules/zod/v4/locales/km.js","../../../node_modules/zod/v4/locales/kh.js","../../../node_modules/zod/v4/locales/ko.js","../../../node_modules/zod/v4/locales/lt.js","../../../node_modules/zod/v4/locales/mk.js","../../../node_modules/zod/v4/locales/ms.js","../../../node_modules/zod/v4/locales/nl.js","../../../node_modules/zod/v4/locales/no.js","../../../node_modules/zod/v4/locales/ota.js","../../../node_modules/zod/v4/locales/ps.js","../../../node_modules/zod/v4/locales/pl.js","../../../node_modules/zod/v4/locales/pt.js","../../../node_modules/zod/v4/locales/ru.js","../../../node_modules/zod/v4/locales/sl.js","../../../node_modules/zod/v4/locales/sv.js","../../../node_modules/zod/v4/locales/ta.js","../../../node_modules/zod/v4/locales/th.js","../../../node_modules/zod/v4/locales/tr.js","../../../node_modules/zod/v4/locales/uk.js","../../../node_modules/zod/v4/locales/ua.js","../../../node_modules/zod/v4/locales/ur.js","../../../node_modules/zod/v4/locales/vi.js","../../../node_modules/zod/v4/locales/zh-CN.js","../../../node_modules/zod/v4/locales/zh-TW.js","../../../node_modules/zod/v4/locales/yo.js","../../../node_modules/zod/v4/core/registries.js","../../../node_modules/zod/v4/core/api.js","../../../node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/zod/v4/core/json-schema.js","../../../node_modules/zod/v4/classic/iso.js","../../../node_modules/zod/v4/classic/errors.js","../../../node_modules/zod/v4/classic/parse.js","../../../node_modules/zod/v4/classic/schemas.js","../../../node_modules/zod/v4/classic/compat.js","../../../node_modules/zod/v4/classic/coerce.js","../src/schemas/request-headers.ts","../src/schemas/request-search-params.ts","../src/schemas/index.ts"],"sourcesContent":["import { createDefaultMicrofoxUsageTracker } from '@microfox/usage-tracker';\nimport {\n createHeaders,\n createLocalSearchHeaders,\n LocalSearchHeaders,\n RequestHeaders,\n} from './lib/headers';\nimport {\n BraveSDKOptions,\n BraveSDKOptionsSchema,\n ImageSearchParams,\n NewsSearchParams,\n SpellcheckSearchParams,\n SuggestSearchParams,\n VideoSearchParams,\n} from './schemas';\nimport { ImageSearchApiResponse } from './schemas/image-response-schema';\nimport { SummarizerSearchParams } from './schemas/index';\nimport { NewsSearchApiResponse } from './schemas/news-response-schema';\nimport {\n LocalSearchParams,\n WebSearchParams,\n} from './schemas/request-search-params';\nimport { SpellCheckSearchApiResponse } from './schemas/spellcheck-response-schema';\nimport { SuggestSearchApiResponse } from './schemas/suggest-response-schema';\nimport { SummarizerSearchApiResponse } from './schemas/summarise-response-schema';\nimport { VideoSearchApiResponse } from './schemas/video-response-schema';\nimport {\n LocalDescriptionsSearchApiResponse,\n LocalPoiSearchApiResponse,\n WebSearchApiResponse,\n} from './schemas/web-response-schemas';\n\nexport type MiddlewareFunction = (request: {\n url: URL;\n params: Record<string, any>;\n headers: RequestHeaders | LocalSearchHeaders;\n useLocalSearchHeaders: boolean;\n}) => Promise<{\n url: URL;\n params: Record<string, any>;\n headers: RequestHeaders | LocalSearchHeaders;\n useLocalSearchHeaders: boolean;\n}>;\n\nexport interface BatchRequestOptions {\n delay?: number; // Delay between requests in milliseconds\n onProgress?: (completed: number, total: number) => void; // Progress callback\n}\n\nexport type BatchRequest = {\n type:\n | 'web'\n | 'image'\n | 'video'\n | 'news'\n | 'suggest'\n | 'spellcheck'\n | 'summarizer'\n | 'localPoi'\n | 'localDescriptions';\n params:\n | WebSearchParams\n | ImageSearchParams\n | VideoSearchParams\n | NewsSearchParams\n | SuggestSearchParams\n | SpellcheckSearchParams\n | SummarizerSearchParams\n | LocalSearchParams;\n};\n\nclass BraveSDK {\n private apiKey: string;\n private baseUrl = 'https://api.search.brave.com/res/v1';\n private headers: RequestHeaders;\n private localSearchHeaders: LocalSearchHeaders;\n private middleware: MiddlewareFunction[] = [];\n\n constructor(options?: BraveSDKOptions) {\n const validatedOptions = options\n ? BraveSDKOptionsSchema.parse(options)\n : undefined;\n this.apiKey = validatedOptions?.apiKey || process.env.BRAVE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new Error(\n 'API key is required. Please provide it in the constructor or set the BRAVE_API_KEY environment variable.',\n );\n }\n\n // Initialize headers\n this.headers = createHeaders({\n apiKey: this.apiKey,\n ...validatedOptions?.headers,\n });\n this.localSearchHeaders = createLocalSearchHeaders({\n apiKey: this.apiKey,\n ...validatedOptions?.localSearchHeaders,\n });\n\n if (options?.enableRedisTracking) {\n this.middleware.push(async request => {\n // TODO: Implement Redis tracking\n return request;\n });\n }\n }\n\n /**\n * Add a middleware function to the SDK\n * @param middleware The middleware function to add\n */\n use(middleware: MiddlewareFunction): void {\n this.middleware.push(middleware);\n }\n\n private async request<T>(\n endpoint: string,\n params: Record<string, any> = {},\n useLocalSearchHeaders = false,\n ): Promise<T> {\n let url = new URL(`${this.baseUrl}${endpoint}`);\n let currentParams = { ...params };\n let currentHeaders = useLocalSearchHeaders\n ? this.localSearchHeaders\n : this.headers;\n let currentUseLocalSearchHeaders = useLocalSearchHeaders;\n\n // Apply all middleware functions in sequence\n for (const middleware of this.middleware) {\n const result = await middleware({\n url,\n params: currentParams,\n headers: currentHeaders,\n useLocalSearchHeaders: currentUseLocalSearchHeaders,\n });\n url = result.url;\n currentParams = result.params;\n currentHeaders = result.headers;\n currentUseLocalSearchHeaders = result.useLocalSearchHeaders;\n }\n\n // Apply the final parameters to the URL\n Object.entries(currentParams).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach(v => url.searchParams.append(key, v.toString()));\n } else if (value !== undefined) {\n url.searchParams.append(key, value.toString());\n }\n });\n\n const response = await fetch(url.toString(), {\n headers: currentHeaders,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const tracker = createDefaultMicrofoxUsageTracker();\n tracker?.trackApi1Usage('brave', 'dataForSearch', {\n requestCount: 1,\n });\n\n return response.json() as Promise<T>;\n }\n\n async webSearch(params: WebSearchParams): Promise<WebSearchApiResponse> {\n return this.request<WebSearchApiResponse>('/web/search', params);\n }\n\n async batchWebSearch(\n params: WebSearchParams[],\n ): Promise<WebSearchApiResponse[]> {\n return this.batchProcess(params.map(p => ({ type: 'web', params: p })));\n }\n\n async localPoiSearch(\n params: LocalSearchParams,\n ): Promise<LocalPoiSearchApiResponse> {\n return this.request<LocalPoiSearchApiResponse>('/local/pois', params, true);\n }\n\n async localDescriptionsSearch(\n params: LocalSearchParams,\n ): Promise<LocalDescriptionsSearchApiResponse> {\n return this.request<LocalDescriptionsSearchApiResponse>(\n '/local/descriptions',\n params,\n true,\n );\n }\n\n async summarizerSearch(\n params: SummarizerSearchParams,\n ): Promise<SummarizerSearchApiResponse> {\n return this.request<SummarizerSearchApiResponse>(\n '/summarizer/search',\n params,\n );\n }\n\n async imageSearch(\n params: ImageSearchParams,\n ): Promise<ImageSearchApiResponse> {\n return this.request<ImageSearchApiResponse>('/images/search', params);\n }\n\n async batchImageSearch(\n params: ImageSearchParams[],\n ): Promise<ImageSearchApiResponse[]> {\n return this.batchProcess(params.map(p => ({ type: 'image', params: p })));\n }\n\n async videoSearch(\n params: VideoSearchParams,\n ): Promise<VideoSearchApiResponse> {\n return this.request<VideoSearchApiResponse>('/videos/search', params);\n }\n\n async batchVideoSearch(\n params: VideoSearchParams[],\n ): Promise<VideoSearchApiResponse[]> {\n return this.batchProcess(params.map(p => ({ type: 'video', params: p })));\n }\n\n async newsSearch(params: NewsSearchParams): Promise<NewsSearchApiResponse> {\n return this.request<NewsSearchApiResponse>('/news/search', params);\n }\n\n async batchNewsSearch(\n params: NewsSearchParams[],\n ): Promise<NewsSearchApiResponse[]> {\n return this.batchProcess(params.map(p => ({ type: 'news', params: p })));\n }\n\n async suggestSearch(\n params: SuggestSearchParams,\n ): Promise<SuggestSearchApiResponse> {\n return this.request<SuggestSearchApiResponse>('/suggest/search', params);\n }\n\n async spellcheckSearch(\n params: SpellcheckSearchParams,\n ): Promise<SpellCheckSearchApiResponse> {\n return this.request<SpellCheckSearchApiResponse>(\n '/spellcheck/search',\n params,\n );\n }\n\n /**\n * Process multiple requests sequentially with a configurable delay\n * @param requests Array of requests to process\n * @param options Configuration options for batch processing\n * @returns Array of responses in the same order as requests\n */\n async batchProcess<T extends any[]>(\n requests: BatchRequest[],\n options: BatchRequestOptions = {},\n ): Promise<T> {\n const { delay = 1000, onProgress } = options;\n const results: any[] = [];\n const total = requests.length;\n\n for (let i = 0; i < total; i++) {\n const request = requests[i];\n let response: any;\n\n try {\n switch (request.type) {\n case 'web':\n response = await this.webSearch(request.params as WebSearchParams);\n break;\n case 'image':\n response = await this.imageSearch(\n request.params as ImageSearchParams,\n );\n break;\n case 'video':\n response = await this.videoSearch(\n request.params as VideoSearchParams,\n );\n break;\n case 'news':\n response = await this.newsSearch(\n request.params as NewsSearchParams,\n );\n break;\n case 'suggest':\n response = await this.suggestSearch(\n request.params as SuggestSearchParams,\n );\n break;\n case 'spellcheck':\n response = await this.spellcheckSearch(\n request.params as SpellcheckSearchParams,\n );\n break;\n case 'summarizer':\n response = await this.summarizerSearch(\n request.params as SummarizerSearchParams,\n );\n break;\n case 'localPoi':\n response = await this.localPoiSearch(\n request.params as LocalSearchParams,\n );\n break;\n case 'localDescriptions':\n response = await this.localDescriptionsSearch(\n request.params as LocalSearchParams,\n );\n break;\n default:\n throw new Error(`Unknown request type: ${request.type}`);\n }\n\n results.push(response);\n } catch (error) {\n results.push({\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n\n if (onProgress) {\n onProgress(i + 1, total);\n }\n\n // Add delay between requests, except for the last one\n if (i < total - 1) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n return results as T;\n }\n}\n\nexport function createBraveSDK(options?: BraveSDKOptions): BraveSDK {\n return new BraveSDK(options);\n}\n","import { z } from 'zod';\nimport {\n RequestHeadersSchema,\n LocalSearchHeadersSchema,\n} from '../schemas/request-headers';\n\nexport type RequestHeaders = z.infer<typeof RequestHeadersSchema>;\nexport type LocalSearchHeaders = z.infer<typeof LocalSearchHeadersSchema>;\n\nexport const DEFAULT_USER_AGENTS = {\n android:\n 'Mozilla/5.0 (Linux; Android 13; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36',\n ios: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1',\n macos:\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/',\n windows:\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/',\n} as const;\n\nexport type Platform = keyof typeof DEFAULT_USER_AGENTS;\n\nexport interface LocationHeaders {\n latitude?: number;\n longitude?: number;\n timezone?: string;\n city?: string;\n state?: string;\n stateName?: string;\n country?: string;\n postalCode?: string;\n}\n\nexport function createHeaders(options: {\n apiKey: string;\n platform?: Platform;\n location?: LocationHeaders;\n apiVersion?: string;\n cacheControl?: string;\n}): RequestHeaders {\n const headers: RequestHeaders = {\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip',\n 'X-Subscription-Token': options.apiKey,\n };\n\n if (options.platform) {\n headers['User-Agent'] = DEFAULT_USER_AGENTS[options.platform];\n }\n\n if (options.apiVersion) {\n headers['Api-Version'] = options.apiVersion;\n }\n\n if (options.cacheControl) {\n headers['Cache-Control'] = options.cacheControl;\n }\n\n if (options.location) {\n const {\n latitude,\n longitude,\n timezone,\n city,\n state,\n stateName,\n country,\n postalCode,\n } = options.location;\n\n if (latitude !== undefined) headers['X-Loc-Lat'] = latitude;\n if (longitude !== undefined) headers['X-Loc-Long'] = longitude;\n if (timezone) headers['X-Loc-Timezone'] = timezone;\n if (city) headers['X-Loc-City'] = city;\n if (state) headers['X-Loc-State'] = state;\n if (stateName) headers['X-Loc-State-Name'] = stateName;\n if (country) headers['X-Loc-Country'] = country;\n if (postalCode) headers['X-Loc-Postal-Code'] = postalCode;\n }\n\n return headers;\n}\n\nexport function createLocalSearchHeaders(options: {\n apiKey: string;\n platform?: Platform;\n apiVersion?: string;\n cacheControl?: string;\n}): LocalSearchHeaders {\n const headers: LocalSearchHeaders = {\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip',\n 'X-Subscription-Token': options.apiKey,\n };\n\n if (options.platform) {\n headers['User-Agent'] = DEFAULT_USER_AGENTS[options.platform];\n }\n\n if (options.apiVersion) {\n headers['Api-Version'] = options.apiVersion;\n }\n\n if (options.cacheControl) {\n headers['Cache-Control'] = options.cacheControl;\n }\n\n return headers;\n}\n","export * as core from \"../core/index.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./errors.js\";\nexport * from \"./parse.js\";\nexport * from \"./compat.js\";\n// zod-specified\nimport { config } from \"../core/index.js\";\nimport en from \"../locales/en.js\";\nconfig(en());\nexport { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, toJSONSchema, TimePrecision, util, NEVER, } from \"../core/index.js\";\nexport * as locales from \"../locales/index.js\";\n// iso\n// must be exported from top-level\n// https://github.com/colinhacks/zod/issues/4491\nexport { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from \"./iso.js\";\nexport * as iso from \"./iso.js\";\nexport * as coerce from \"./coerce.js\";\n","export * from \"./core.js\";\nexport * from \"./parse.js\";\nexport * from \"./errors.js\";\nexport * from \"./schemas.js\";\nexport * from \"./checks.js\";\nexport * from \"./versions.js\";\nexport * as util from \"./util.js\";\nexport * as regexes from \"./regexes.js\";\nexport * as locales from \"../locales/index.js\";\nexport * from \"./registries.js\";\nexport * from \"./doc.js\";\nexport * from \"./api.js\";\nexport * from \"./to-json-schema.js\";\nexport * as JSONSchema from \"./json-schema.js\";\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n var _a;\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod ?? {},\n enumerable: false,\n });\n (_a = inst._zod).traits ?? (_a.traits = new Set());\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n for (const k in _.prototype) {\n if (!(k in inst))\n Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });\n }\n inst._zod.constr = _;\n inst._zod.def = def;\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error();\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\"Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = {\n ...schema._zod.def,\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: schema._zod.def.checks,\n };\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx)