UNPKG

@ioris/core

Version:

This package provides the core functionality for the [@ioris](https://www.npmjs.com/search?q=%40ioris) ecosystem for managing music lyrics with time synchronization.

4 lines 945 kB
{ "version": 3, "sources": ["../src/Constants.ts", "../src/factories/createChar.ts", "../src/factories/createWord.ts", "../src/factories/createLine.ts", "../src/factories/createParagraph.ts", "../src/factories/createLyric.ts", "../src/schemas/result.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/bg.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/timeline.schema.ts", "../src/features/editing/helpers.ts", "../src/features/editing/merge.ts", "../src/features/editing/shift.ts", "../src/features/editing/split.ts", "../src/utils/helpers.ts", "../src/utils/current.ts", "../src/utils/navigation.ts", "../src/utils/analysis.ts", "../src/utils/grid.ts", "../src/utils/update.ts"], "sourcesContent": ["export const CHAR_TYPES = {\n WHITESPACE: \"whitespace\",\n ALPHABET: \"alphabet\",\n NUMBER: \"number\",\n KANJI: \"kanji\",\n HIRAGANA: \"hiragana\",\n KATAKANA: \"katakana\",\n OTHER: \"other\",\n} as const;\n\nexport type CharType = (typeof CHAR_TYPES)[keyof typeof CHAR_TYPES];\n\nexport type WordTimeline = {\n wordID: string;\n text: string;\n begin: number;\n end: number;\n hasWhitespace?: boolean;\n hasNewLine?: boolean;\n};\n", "import { CHAR_TYPES, type CharType } from \"../Constants\";\nimport type { Char } from \"../types\";\n\nexport type CreateCharArgs = {\n wordID: string;\n position: number;\n text: string;\n begin: number;\n end: number;\n};\n\nfunction getCharType(text: string): CharType {\n if (/^\\s+$/.test(text)) {\n return CHAR_TYPES.WHITESPACE;\n }\n if (/^[a-zA-Z]+$/.test(text)) {\n return CHAR_TYPES.ALPHABET;\n }\n if (/^[0-9]+$/.test(text)) {\n return CHAR_TYPES.NUMBER;\n }\n if (/^[\\u4E00-\\u9FFF]+$/.test(text)) {\n return CHAR_TYPES.KANJI;\n }\n if (/^[\\u3040-\\u309F]+$/.test(text)) {\n return CHAR_TYPES.HIRAGANA;\n }\n if (/^[\\u30A0-\\u30FF]+$/.test(text)) {\n return CHAR_TYPES.KATAKANA;\n }\n return CHAR_TYPES.OTHER;\n}\n\nexport function createChar(args: CreateCharArgs): Char {\n const id = `char-${crypto.randomUUID()}`;\n const type = getCharType(args.text);\n\n return Object.freeze({\n id,\n wordID: args.wordID,\n text: args.text,\n type,\n position: args.position,\n begin: args.begin,\n end: args.end,\n });\n}\n", "import type { WordTimeline } from \"../Constants\";\nimport type { Word } from \"../types\";\nimport { createChar } from \"./createChar\";\n\nexport type CreateWordArgs = {\n lineID: string;\n position: number;\n timeline: WordTimeline | Omit<WordTimeline, \"wordID\">;\n};\n\nfunction isWordTimeline(\n timeline: WordTimeline | Omit<WordTimeline, \"wordID\">,\n): timeline is WordTimeline {\n return (timeline as WordTimeline).wordID !== undefined;\n}\n\nexport function createWord(args: CreateWordArgs): Word {\n const id = isWordTimeline(args.timeline)\n ? args.timeline.wordID\n : `word-${crypto.randomUUID()}`;\n\n const timeline: WordTimeline = {\n ...args.timeline,\n wordID: id,\n hasNewLine: args.timeline.hasNewLine ?? false,\n hasWhitespace: args.timeline.hasWhitespace ?? false,\n };\n\n const charTexts = timeline.text.split(\"\");\n const wordDuration = timeline.end - timeline.begin;\n const durationByChar = wordDuration / charTexts.length;\n\n const chars = charTexts.map((char, index) => {\n const position = index + 1;\n return createChar({\n wordID: id,\n position,\n text: char,\n begin: timeline.begin + index * durationByChar,\n end: timeline.begin + position * durationByChar,\n });\n });\n\n return Object.freeze({\n id,\n lineID: args.lineID,\n position: args.position,\n timeline,\n chars,\n });\n}\n", "import type { WordTimeline } from \"../Constants\";\nimport type { Line, Word } from \"../types\";\nimport { createWord } from \"./createWord\";\n\nexport type CreateLineArgs = {\n position: number;\n timelines: WordTimeline[];\n jointNearWord?: boolean;\n};\n\nfunction confirmJointNearWord(\n timeline: WordTimeline,\n nextTimeline: WordTimeline | undefined,\n lastWord: Word | undefined,\n jointNearWord: boolean,\n): { isJoint: boolean; hasWhitespace: boolean } | undefined {\n const isWhitespace = /^\\s+$/.test(timeline.text);\n if (isWhitespace) {\n return undefined;\n }\n\n const nextIsWhitespace = nextTimeline\n ? /^\\s+$/.test(nextTimeline.text)\n : false;\n const hasWhitespace = timeline.hasWhitespace || nextIsWhitespace;\n\n if (jointNearWord !== false) {\n if (\n lastWord &&\n lastWord.timeline.end - timeline.begin <= 0.1 &&\n !lastWord.timeline.hasNewLine &&\n !lastWord.timeline.hasWhitespace\n ) {\n return { isJoint: true, hasWhitespace };\n }\n }\n return { isJoint: false, hasWhitespace };\n}\n\nexport function createLine(args: CreateLineArgs): Line {\n const id = `line-${crypto.randomUUID()}`;\n const sortedTimelines = args.timelines.sort((a, b) => a.begin - b.begin);\n\n const words: Word[] = [];\n\n for (let index = 0; index < sortedTimelines.length; index++) {\n const timeline = sortedTimelines[index];\n const nextTimeline = sortedTimelines[index + 1];\n const lastWord = words[words.length - 1];\n\n const jointResult = confirmJointNearWord(\n timeline,\n nextTimeline,\n lastWord,\n args.jointNearWord === true,\n );\n\n if (!jointResult) {\n continue;\n }\n\n const { isJoint, hasWhitespace } = jointResult;\n\n if (lastWord && isJoint) {\n const updatedWord = createWord({\n lineID: id,\n position: words.length,\n timeline: {\n wordID: lastWord.id,\n begin: lastWord.timeline.begin,\n end: timeline.end,\n text: lastWord.timeline.text + timeline.text,\n hasNewLine: timeline.hasNewLine === true,\n hasWhitespace,\n },\n });\n words[words.length - 1] = updatedWord;\n } else {\n const word = createWord({\n lineID: id,\n position: words.length + 1,\n timeline: {\n ...timeline,\n hasWhitespace,\n },\n });\n words.push(word);\n }\n }\n\n return Object.freeze({\n id,\n position: args.position,\n words,\n });\n}\n", "import type { WordTimeline } from \"../Constants\";\nimport type { Paragraph } from \"../types\";\nimport { createLine } from \"./createLine\";\n\nexport type CreateParagraphArgs = {\n position: number;\n timelines: WordTimeline[][];\n lineTokenizer?: (lineArgs: {\n position: number;\n timelines: WordTimeline[];\n }) => Promise<\n Map<\n number,\n { position: number; timelines: WordTimeline[]; jointNearWord?: boolean }\n >\n >;\n paragraphTokenizer?: (\n timelines: WordTimeline[][],\n ) => Promise<WordTimeline[][]>;\n};\n\nexport async function createParagraph(\n args: CreateParagraphArgs,\n): Promise<Paragraph> {\n const id = `paragraph-${crypto.randomUUID()}`;\n\n let timelines = args.timelines;\n\n if (args.paragraphTokenizer) {\n timelines = await args.paragraphTokenizer(timelines);\n }\n\n const mergedTimelines = timelines.reduce<WordTimeline[][]>(\n (acc, timeline) => {\n const lastTimelines = acc[acc.length - 1];\n const last = lastTimelines\n ? lastTimelines[lastTimelines.length - 1]\n : null;\n const thisFirst = timeline[0];\n\n if (!thisFirst) {\n console.error(\"thisFirst is undefined\", timelines, timeline);\n return acc;\n }\n\n if (\n last &&\n (last.end > thisFirst.begin ||\n (last.end === thisFirst.begin && last.text.length < 6))\n ) {\n last.end = thisFirst.end;\n last.text += ` ${thisFirst.text}`;\n return acc;\n }\n\n acc.push(timeline);\n return acc;\n },\n [],\n );\n\n const lineCreateArgsPromises = mergedTimelines.map(\n async (timeline, index) => {\n const position = index + 1;\n\n if (args.lineTokenizer) {\n return await args.lineTokenizer({ position, timelines: timeline });\n }\n\n return new Map([\n [\n position,\n {\n jointNearWord: true,\n position,\n timelines: timeline,\n },\n ],\n ]);\n },\n );\n\n const resolvedArgsArray = await Promise.all(lineCreateArgsPromises);\n\n const lines = [];\n\n for (const lineByPosition of resolvedArgsArray) {\n for (const [, lineArgs] of lineByPosition) {\n const position = lines.length + 1;\n const line = createLine({\n ...lineArgs,\n position,\n });\n lines.push(line);\n }\n }\n\n return Object.freeze({\n id,\n position: args.position,\n lines,\n });\n}\n", "import type {\n Line,\n Lyric,\n LyricIndex,\n Paragraph,\n Word,\n WordTimeline,\n} from \"../types\";\nimport { createParagraph } from \"./createParagraph\";\n\nexport type CreateLyricArgs = {\n initID?: boolean;\n id?: string;\n resourceID: string;\n timelines: WordTimeline[][][];\n lineTokenizer?: (lineArgs: {\n position: number;\n timelines: WordTimeline[];\n }) => Promise<\n Map<\n number,\n { position: number; timelines: WordTimeline[]; jointNearWord?: boolean }\n >\n >;\n paragraphTokenizer?: (\n timelines: WordTimeline[][],\n ) => Promise<WordTimeline[][]>;\n offsetSec?: number;\n};\n\n/**\n * Calculate duration from timelines (last end - first begin)\n * Returns 0 if timelines is empty\n */\nfunction calculateDuration(timelines: WordTimeline[][][]): number {\n const allWords = timelines.flat(2);\n if (allWords.length === 0) return 0;\n\n const firstWord = allWords[0];\n const lastWord = allWords[allWords.length - 1];\n return Number((lastWord.end - firstWord.begin).toFixed(2));\n}\n\n/**\n * Build LyricIndex\n */\nfunction buildIndex(paragraphs: readonly Paragraph[]): LyricIndex {\n const wordByCharId = new Map<string, Word>();\n const lineByWordId = new Map<string, Line>();\n const paragraphByLineId = new Map<string, Paragraph>();\n const wordById = new Map<string, Word>();\n const lineById = new Map<string, Line>();\n const paragraphById = new Map<string, Paragraph>();\n\n for (const paragraph of paragraphs) {\n paragraphById.set(paragraph.id, paragraph);\n\n for (const line of paragraph.lines) {\n lineById.set(line.id, line);\n paragraphByLineId.set(line.id, paragraph);\n\n for (const word of line.words) {\n wordById.set(word.id, word);\n lineByWordId.set(word.id, line);\n\n for (const char of word.chars) {\n wordByCharId.set(char.id, word);\n }\n }\n }\n }\n\n return Object.freeze({\n wordByCharId,\n lineByWordId,\n paragraphByLineId,\n wordById,\n lineById,\n paragraphById,\n });\n}\n\nexport async function createLyric(args: CreateLyricArgs): Promise<Lyric> {\n const id = args.id\n ? args.id\n : args.initID\n ? `lyric-${crypto.randomUUID()}`\n : \"\";\n\n const paragraphPromises = args.timelines.map(async (timelines, index) => {\n const position = index + 1;\n return await createParagraph({\n position,\n timelines,\n lineTokenizer: args.lineTokenizer,\n paragraphTokenizer: args.paragraphTokenizer,\n });\n });\n\n const paragraphs = await Promise.all(paragraphPromises);\n const _index = buildIndex(paragraphs);\n const duration = calculateDuration(args.timelines);\n\n return Object.freeze({\n id,\n resourceID: args.resourceID,\n duration,\n offsetSec: args.offsetSec ?? 0,\n paragraphs,\n _index,\n });\n}\n", "/**\n * Result type definitions\n * Used as return values for factory functions and validation functions\n */\n\nexport type ValidationError = {\n readonly code: string;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n};\n\nexport type Success<T> = {\n readonly success: true;\n readonly data: T;\n};\n\nexport type Failure = {\n readonly success: false;\n readonly error: ValidationError;\n};\n\nexport type ValidationResult<T> = Success<T> | Failure;\n\n/**\n * Create a success result\n */\nexport function success<T>(data: T): Success<T> {\n return Object.freeze({\n success: true,\n data,\n });\n}\n\n/**\n * Create a failure result\n */\nexport function failure(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): Failure {\n return Object.freeze({\n success: false,\n error: Object.freeze({\n code,\n message,\n details,\n }),\n });\n}\n\n/**\n * Check if the result is a success (type guard)\n */\nexport function isSuccess<T>(\n result: ValidationResult<T>,\n): result is Success<T> {\n return result.success === true;\n}\n\n/**\n * Check if the result is a failure (type guard)\n */\nexport function isFailure<T>(result: ValidationResult<T>): result is Failure {\n return result.success === false;\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 if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\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 function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\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 if (typeof ctor !== \"function\")\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 = (issue) => issue.message) {\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 = (issue) => issue.message) {\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 * \u2716 Expected number, received string at \"username\n * favoriteNumbers[0]\n * \u2716 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(`\u2716 ${issue.message}`);\n if (issue.path?.length)\n lines.push(` \u2192 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) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) =>